bridge.go 9.1 KB

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