bridge.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. DoublePuppetBackfill bool `yaml:"double_puppet_backfill"`
  43. RequestFullSync bool `yaml:"request_full_sync"`
  44. AutoRequestMedia bool `yaml:"auto_request_media"`
  45. MaxInitialConversations int `yaml:"max_initial_conversations"`
  46. Immediate struct {
  47. WorkerCount int `yaml:"worker_count"`
  48. MaxEvents int `yaml:"max_events"`
  49. } `yaml:"immediate"`
  50. Deferred []DeferredConfig `yaml:"deferred"`
  51. Media []DeferredConfig `yaml:"media"`
  52. } `yaml:"history_sync"`
  53. UserAvatarSync bool `yaml:"user_avatar_sync"`
  54. BridgeMatrixLeave bool `yaml:"bridge_matrix_leave"`
  55. SyncWithCustomPuppets bool `yaml:"sync_with_custom_puppets"`
  56. SyncDirectChatList bool `yaml:"sync_direct_chat_list"`
  57. DefaultBridgeReceipts bool `yaml:"default_bridge_receipts"`
  58. DefaultBridgePresence bool `yaml:"default_bridge_presence"`
  59. SendPresenceOnTyping bool `yaml:"send_presence_on_typing"`
  60. ForceActiveDeliveryReceipts bool `yaml:"force_active_delivery_receipts"`
  61. DoublePuppetServerMap map[string]string `yaml:"double_puppet_server_map"`
  62. DoublePuppetAllowDiscovery bool `yaml:"double_puppet_allow_discovery"`
  63. LoginSharedSecretMap map[string]string `yaml:"login_shared_secret_map"`
  64. PrivateChatPortalMeta bool `yaml:"private_chat_portal_meta"`
  65. BridgeNotices bool `yaml:"bridge_notices"`
  66. ResendBridgeInfo bool `yaml:"resend_bridge_info"`
  67. MuteBridging bool `yaml:"mute_bridging"`
  68. ArchiveTag string `yaml:"archive_tag"`
  69. PinnedTag string `yaml:"pinned_tag"`
  70. TagOnlyOnCreate bool `yaml:"tag_only_on_create"`
  71. MarkReadOnlyOnCreate bool `yaml:"mark_read_only_on_create"`
  72. EnableStatusBroadcast bool `yaml:"enable_status_broadcast"`
  73. MuteStatusBroadcast bool `yaml:"mute_status_broadcast"`
  74. StatusBroadcastTag string `yaml:"status_broadcast_tag"`
  75. WhatsappThumbnail bool `yaml:"whatsapp_thumbnail"`
  76. AllowUserInvite bool `yaml:"allow_user_invite"`
  77. FederateRooms bool `yaml:"federate_rooms"`
  78. URLPreviews bool `yaml:"url_previews"`
  79. DisappearingMessagesInGroups bool `yaml:"disappearing_messages_in_groups"`
  80. DisableBridgeAlerts bool `yaml:"disable_bridge_alerts"`
  81. CommandPrefix string `yaml:"command_prefix"`
  82. ManagementRoomText struct {
  83. Welcome string `yaml:"welcome"`
  84. WelcomeConnected string `yaml:"welcome_connected"`
  85. WelcomeUnconnected string `yaml:"welcome_unconnected"`
  86. AdditionalHelp string `yaml:"additional_help"`
  87. } `yaml:"management_room_text"`
  88. Encryption struct {
  89. Allow bool `yaml:"allow"`
  90. Default bool `yaml:"default"`
  91. KeySharing struct {
  92. Allow bool `yaml:"allow"`
  93. RequireCrossSigning bool `yaml:"require_cross_signing"`
  94. RequireVerification bool `yaml:"require_verification"`
  95. } `yaml:"key_sharing"`
  96. } `yaml:"encryption"`
  97. Permissions PermissionConfig `yaml:"permissions"`
  98. Relay RelaybotConfig `yaml:"relay"`
  99. usernameTemplate *template.Template `yaml:"-"`
  100. displaynameTemplate *template.Template `yaml:"-"`
  101. }
  102. type umBridgeConfig BridgeConfig
  103. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  104. err := unmarshal((*umBridgeConfig)(bc))
  105. if err != nil {
  106. return err
  107. }
  108. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  109. if err != nil {
  110. return err
  111. } else if !strings.Contains(bc.FormatUsername("1234567890"), "1234567890") {
  112. return fmt.Errorf("username template is missing user ID placeholder")
  113. }
  114. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  115. if err != nil {
  116. return err
  117. }
  118. return nil
  119. }
  120. type UsernameTemplateArgs struct {
  121. UserID id.UserID
  122. }
  123. type legacyContactInfo struct {
  124. types.ContactInfo
  125. Phone string
  126. Notify string
  127. VName string
  128. Name string
  129. Short string
  130. JID string
  131. }
  132. func (bc BridgeConfig) FormatDisplayname(jid types.JID, contact types.ContactInfo) (string, int8) {
  133. var buf strings.Builder
  134. _ = bc.displaynameTemplate.Execute(&buf, legacyContactInfo{
  135. ContactInfo: contact,
  136. Notify: contact.PushName,
  137. VName: contact.BusinessName,
  138. Name: contact.FullName,
  139. Short: contact.FirstName,
  140. Phone: "+" + jid.User,
  141. JID: "+" + jid.User,
  142. })
  143. var quality int8
  144. switch {
  145. case len(contact.PushName) > 0 || len(contact.BusinessName) > 0:
  146. quality = 3
  147. case len(contact.FullName) > 0 || len(contact.FirstName) > 0:
  148. quality = 2
  149. default:
  150. quality = 1
  151. }
  152. return buf.String(), quality
  153. }
  154. func (bc BridgeConfig) FormatUsername(username string) string {
  155. var buf strings.Builder
  156. _ = bc.usernameTemplate.Execute(&buf, username)
  157. return buf.String()
  158. }
  159. type PermissionConfig map[string]PermissionLevel
  160. type PermissionLevel int
  161. const (
  162. PermissionLevelDefault PermissionLevel = 0
  163. PermissionLevelRelay PermissionLevel = 5
  164. PermissionLevelUser PermissionLevel = 10
  165. PermissionLevelAdmin PermissionLevel = 100
  166. )
  167. func (pc *PermissionConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  168. rawPC := make(map[string]string)
  169. err := unmarshal(&rawPC)
  170. if err != nil {
  171. return err
  172. }
  173. if *pc == nil {
  174. *pc = make(map[string]PermissionLevel)
  175. }
  176. for key, value := range rawPC {
  177. switch strings.ToLower(value) {
  178. case "relaybot", "relay":
  179. (*pc)[key] = PermissionLevelRelay
  180. case "user":
  181. (*pc)[key] = PermissionLevelUser
  182. case "admin":
  183. (*pc)[key] = PermissionLevelAdmin
  184. default:
  185. val, err := strconv.Atoi(value)
  186. if err != nil {
  187. (*pc)[key] = PermissionLevelDefault
  188. } else {
  189. (*pc)[key] = PermissionLevel(val)
  190. }
  191. }
  192. }
  193. return nil
  194. }
  195. func (pc *PermissionConfig) MarshalYAML() (interface{}, error) {
  196. if *pc == nil {
  197. return nil, nil
  198. }
  199. rawPC := make(map[string]string)
  200. for key, value := range *pc {
  201. switch value {
  202. case PermissionLevelRelay:
  203. rawPC[key] = "relay"
  204. case PermissionLevelUser:
  205. rawPC[key] = "user"
  206. case PermissionLevelAdmin:
  207. rawPC[key] = "admin"
  208. default:
  209. rawPC[key] = strconv.Itoa(int(value))
  210. }
  211. }
  212. return rawPC, nil
  213. }
  214. func (pc PermissionConfig) IsRelayWhitelisted(userID id.UserID) bool {
  215. return pc.GetPermissionLevel(userID) >= PermissionLevelRelay
  216. }
  217. func (pc PermissionConfig) IsWhitelisted(userID id.UserID) bool {
  218. return pc.GetPermissionLevel(userID) >= PermissionLevelUser
  219. }
  220. func (pc PermissionConfig) IsAdmin(userID id.UserID) bool {
  221. return pc.GetPermissionLevel(userID) >= PermissionLevelAdmin
  222. }
  223. func (pc PermissionConfig) GetPermissionLevel(userID id.UserID) PermissionLevel {
  224. permissions, ok := pc[string(userID)]
  225. if ok {
  226. return permissions
  227. }
  228. _, homeserver, _ := userID.Parse()
  229. permissions, ok = pc[homeserver]
  230. if len(homeserver) > 0 && ok {
  231. return permissions
  232. }
  233. permissions, ok = pc["*"]
  234. if ok {
  235. return permissions
  236. }
  237. return PermissionLevelDefault
  238. }
  239. type RelaybotConfig struct {
  240. Enabled bool `yaml:"enabled"`
  241. AdminOnly bool `yaml:"admin_only"`
  242. MessageFormats map[event.MessageType]string `yaml:"message_formats"`
  243. messageTemplates *template.Template `yaml:"-"`
  244. }
  245. type umRelaybotConfig RelaybotConfig
  246. func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  247. err := unmarshal((*umRelaybotConfig)(rc))
  248. if err != nil {
  249. return err
  250. }
  251. rc.messageTemplates = template.New("messageTemplates")
  252. for key, format := range rc.MessageFormats {
  253. _, err := rc.messageTemplates.New(string(key)).Parse(format)
  254. if err != nil {
  255. return err
  256. }
  257. }
  258. return nil
  259. }
  260. type Sender struct {
  261. UserID string
  262. event.MemberEventContent
  263. }
  264. type formatData struct {
  265. Sender Sender
  266. Message string
  267. Content *event.MessageEventContent
  268. }
  269. func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member event.MemberEventContent) (string, error) {
  270. if len(member.Displayname) == 0 {
  271. member.Displayname = sender.String()
  272. }
  273. member.Displayname = template.HTMLEscapeString(member.Displayname)
  274. var output strings.Builder
  275. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  276. Sender: Sender{
  277. UserID: template.HTMLEscapeString(sender.String()),
  278. MemberEventContent: member,
  279. },
  280. Content: content,
  281. Message: content.FormattedBody,
  282. })
  283. return output.String(), err
  284. }