bridge.go 9.6 KB

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