bridge.go 9.5 KB

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