bridge.go 10 KB

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