bridge.go 9.0 KB

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