bridge.go 10 KB

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