bridge.go 9.2 KB

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