bridge.go 9.0 KB

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