bridge.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package config
  17. import (
  18. "fmt"
  19. "strconv"
  20. "strings"
  21. "text/template"
  22. "go.mau.fi/whatsmeow/types"
  23. "maunium.net/go/mautrix/event"
  24. "maunium.net/go/mautrix/id"
  25. )
  26. type DeferredConfig struct {
  27. StartDaysAgo int `yaml:"start_days_ago"`
  28. MaxBatchEvents int `yaml:"max_batch_events"`
  29. BatchDelay int `yaml:"batch_delay"`
  30. }
  31. type BridgeConfig struct {
  32. UsernameTemplate string `yaml:"username_template"`
  33. DisplaynameTemplate string `yaml:"displayname_template"`
  34. PersonalFilteringSpaces bool `yaml:"personal_filtering_spaces"`
  35. DeliveryReceipts bool `yaml:"delivery_receipts"`
  36. PortalMessageBuffer int `yaml:"portal_message_buffer"`
  37. CallStartNotices bool `yaml:"call_start_notices"`
  38. IdentityChangeNotices bool `yaml:"identity_change_notices"`
  39. HistorySync struct {
  40. CreatePortals bool `yaml:"create_portals"`
  41. Backfill bool `yaml:"backfill"`
  42. BackfillMedia bool `yaml:"backfill_media"`
  43. EnqueueBackfillMediaNextStart bool `yaml:"enqueue_backfill_media_next_start"`
  44. DoublePuppetBackfill bool `yaml:"double_puppet_backfill"`
  45. RequestFullSync bool `yaml:"request_full_sync"`
  46. MaxInitialConversations int `yaml:"max_initial_conversations"`
  47. Immediate struct {
  48. WorkerCount int `yaml:"worker_count"`
  49. MaxEvents int `yaml:"max_events"`
  50. } `yaml:"immediate"`
  51. Deferred []DeferredConfig `yaml:"deferred"`
  52. Media []DeferredConfig `yaml:"media"`
  53. } `yaml:"history_sync"`
  54. UserAvatarSync bool `yaml:"user_avatar_sync"`
  55. BridgeMatrixLeave bool `yaml:"bridge_matrix_leave"`
  56. SyncWithCustomPuppets bool `yaml:"sync_with_custom_puppets"`
  57. SyncDirectChatList bool `yaml:"sync_direct_chat_list"`
  58. DefaultBridgeReceipts bool `yaml:"default_bridge_receipts"`
  59. DefaultBridgePresence bool `yaml:"default_bridge_presence"`
  60. SendPresenceOnTyping bool `yaml:"send_presence_on_typing"`
  61. ForceActiveDeliveryReceipts bool `yaml:"force_active_delivery_receipts"`
  62. DoublePuppetServerMap map[string]string `yaml:"double_puppet_server_map"`
  63. DoublePuppetAllowDiscovery bool `yaml:"double_puppet_allow_discovery"`
  64. LoginSharedSecretMap map[string]string `yaml:"login_shared_secret_map"`
  65. PrivateChatPortalMeta bool `yaml:"private_chat_portal_meta"`
  66. BridgeNotices bool `yaml:"bridge_notices"`
  67. ResendBridgeInfo bool `yaml:"resend_bridge_info"`
  68. MuteBridging bool `yaml:"mute_bridging"`
  69. ArchiveTag string `yaml:"archive_tag"`
  70. PinnedTag string `yaml:"pinned_tag"`
  71. TagOnlyOnCreate bool `yaml:"tag_only_on_create"`
  72. MarkReadOnlyOnCreate bool `yaml:"mark_read_only_on_create"`
  73. EnableStatusBroadcast bool `yaml:"enable_status_broadcast"`
  74. MuteStatusBroadcast bool `yaml:"mute_status_broadcast"`
  75. StatusBroadcastTag string `yaml:"status_broadcast_tag"`
  76. WhatsappThumbnail bool `yaml:"whatsapp_thumbnail"`
  77. AllowUserInvite bool `yaml:"allow_user_invite"`
  78. FederateRooms bool `yaml:"federate_rooms"`
  79. URLPreviews bool `yaml:"url_previews"`
  80. DisappearingMessagesInGroups bool `yaml:"disappearing_messages_in_groups"`
  81. DisableBridgeAlerts bool `yaml:"disable_bridge_alerts"`
  82. CommandPrefix string `yaml:"command_prefix"`
  83. ManagementRoomText struct {
  84. Welcome string `yaml:"welcome"`
  85. WelcomeConnected string `yaml:"welcome_connected"`
  86. WelcomeUnconnected string `yaml:"welcome_unconnected"`
  87. AdditionalHelp string `yaml:"additional_help"`
  88. } `yaml:"management_room_text"`
  89. Encryption struct {
  90. Allow bool `yaml:"allow"`
  91. Default bool `yaml:"default"`
  92. KeySharing struct {
  93. Allow bool `yaml:"allow"`
  94. RequireCrossSigning bool `yaml:"require_cross_signing"`
  95. RequireVerification bool `yaml:"require_verification"`
  96. } `yaml:"key_sharing"`
  97. } `yaml:"encryption"`
  98. Permissions PermissionConfig `yaml:"permissions"`
  99. Relay RelaybotConfig `yaml:"relay"`
  100. usernameTemplate *template.Template `yaml:"-"`
  101. displaynameTemplate *template.Template `yaml:"-"`
  102. }
  103. type umBridgeConfig BridgeConfig
  104. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  105. err := unmarshal((*umBridgeConfig)(bc))
  106. if err != nil {
  107. return err
  108. }
  109. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  110. if err != nil {
  111. return err
  112. } else if !strings.Contains(bc.FormatUsername("1234567890"), "1234567890") {
  113. return fmt.Errorf("username template is missing user ID placeholder")
  114. }
  115. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  116. if err != nil {
  117. return err
  118. }
  119. return nil
  120. }
  121. type UsernameTemplateArgs struct {
  122. UserID id.UserID
  123. }
  124. type legacyContactInfo struct {
  125. types.ContactInfo
  126. Phone string
  127. Notify string
  128. VName string
  129. Name string
  130. Short string
  131. JID string
  132. }
  133. func (bc BridgeConfig) FormatDisplayname(jid types.JID, contact types.ContactInfo) (string, int8) {
  134. var buf strings.Builder
  135. _ = bc.displaynameTemplate.Execute(&buf, legacyContactInfo{
  136. ContactInfo: contact,
  137. Notify: contact.PushName,
  138. VName: contact.BusinessName,
  139. Name: contact.FullName,
  140. Short: contact.FirstName,
  141. Phone: "+" + jid.User,
  142. JID: "+" + jid.User,
  143. })
  144. var quality int8
  145. switch {
  146. case len(contact.PushName) > 0 || len(contact.BusinessName) > 0:
  147. quality = 3
  148. case len(contact.FullName) > 0 || len(contact.FirstName) > 0:
  149. quality = 2
  150. default:
  151. quality = 1
  152. }
  153. return buf.String(), quality
  154. }
  155. func (bc BridgeConfig) FormatUsername(username string) string {
  156. var buf strings.Builder
  157. _ = bc.usernameTemplate.Execute(&buf, username)
  158. return buf.String()
  159. }
  160. type PermissionConfig map[string]PermissionLevel
  161. type PermissionLevel int
  162. const (
  163. PermissionLevelDefault PermissionLevel = 0
  164. PermissionLevelRelay PermissionLevel = 5
  165. PermissionLevelUser PermissionLevel = 10
  166. PermissionLevelAdmin PermissionLevel = 100
  167. )
  168. func (pc *PermissionConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  169. rawPC := make(map[string]string)
  170. err := unmarshal(&rawPC)
  171. if err != nil {
  172. return err
  173. }
  174. if *pc == nil {
  175. *pc = make(map[string]PermissionLevel)
  176. }
  177. for key, value := range rawPC {
  178. switch strings.ToLower(value) {
  179. case "relaybot", "relay":
  180. (*pc)[key] = PermissionLevelRelay
  181. case "user":
  182. (*pc)[key] = PermissionLevelUser
  183. case "admin":
  184. (*pc)[key] = PermissionLevelAdmin
  185. default:
  186. val, err := strconv.Atoi(value)
  187. if err != nil {
  188. (*pc)[key] = PermissionLevelDefault
  189. } else {
  190. (*pc)[key] = PermissionLevel(val)
  191. }
  192. }
  193. }
  194. return nil
  195. }
  196. func (pc *PermissionConfig) MarshalYAML() (interface{}, error) {
  197. if *pc == nil {
  198. return nil, nil
  199. }
  200. rawPC := make(map[string]string)
  201. for key, value := range *pc {
  202. switch value {
  203. case PermissionLevelRelay:
  204. rawPC[key] = "relay"
  205. case PermissionLevelUser:
  206. rawPC[key] = "user"
  207. case PermissionLevelAdmin:
  208. rawPC[key] = "admin"
  209. default:
  210. rawPC[key] = strconv.Itoa(int(value))
  211. }
  212. }
  213. return rawPC, nil
  214. }
  215. func (pc PermissionConfig) IsRelayWhitelisted(userID id.UserID) bool {
  216. return pc.GetPermissionLevel(userID) >= PermissionLevelRelay
  217. }
  218. func (pc PermissionConfig) IsWhitelisted(userID id.UserID) bool {
  219. return pc.GetPermissionLevel(userID) >= PermissionLevelUser
  220. }
  221. func (pc PermissionConfig) IsAdmin(userID id.UserID) bool {
  222. return pc.GetPermissionLevel(userID) >= PermissionLevelAdmin
  223. }
  224. func (pc PermissionConfig) GetPermissionLevel(userID id.UserID) PermissionLevel {
  225. permissions, ok := pc[string(userID)]
  226. if ok {
  227. return permissions
  228. }
  229. _, homeserver, _ := userID.Parse()
  230. permissions, ok = pc[homeserver]
  231. if len(homeserver) > 0 && ok {
  232. return permissions
  233. }
  234. permissions, ok = pc["*"]
  235. if ok {
  236. return permissions
  237. }
  238. return PermissionLevelDefault
  239. }
  240. type RelaybotConfig struct {
  241. Enabled bool `yaml:"enabled"`
  242. AdminOnly bool `yaml:"admin_only"`
  243. MessageFormats map[event.MessageType]string `yaml:"message_formats"`
  244. messageTemplates *template.Template `yaml:"-"`
  245. }
  246. type umRelaybotConfig RelaybotConfig
  247. func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  248. err := unmarshal((*umRelaybotConfig)(rc))
  249. if err != nil {
  250. return err
  251. }
  252. rc.messageTemplates = template.New("messageTemplates")
  253. for key, format := range rc.MessageFormats {
  254. _, err := rc.messageTemplates.New(string(key)).Parse(format)
  255. if err != nil {
  256. return err
  257. }
  258. }
  259. return nil
  260. }
  261. type Sender struct {
  262. UserID string
  263. event.MemberEventContent
  264. }
  265. type formatData struct {
  266. Sender Sender
  267. Message string
  268. Content *event.MessageEventContent
  269. }
  270. func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member event.MemberEventContent) (string, error) {
  271. if len(member.Displayname) == 0 {
  272. member.Displayname = sender.String()
  273. }
  274. member.Displayname = template.HTMLEscapeString(member.Displayname)
  275. var output strings.Builder
  276. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  277. Sender: Sender{
  278. UserID: template.HTMLEscapeString(sender.String()),
  279. MemberEventContent: member,
  280. },
  281. Content: content,
  282. Message: content.FormattedBody,
  283. })
  284. return output.String(), err
  285. }