bridge.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. "strconv"
  19. "strings"
  20. "text/template"
  21. "go.mau.fi/whatsmeow/types"
  22. "maunium.net/go/mautrix/event"
  23. "maunium.net/go/mautrix/id"
  24. )
  25. type BridgeConfig struct {
  26. UsernameTemplate string `yaml:"username_template"`
  27. DisplaynameTemplate string `yaml:"displayname_template"`
  28. DeliveryReceipts bool `yaml:"delivery_receipts"`
  29. MaxConnectionAttempts int `yaml:"max_connection_attempts"`
  30. ConnectionRetryDelay int `yaml:"connection_retry_delay"`
  31. ReportConnectionRetry bool `yaml:"report_connection_retry"`
  32. PortalMessageBuffer int `yaml:"portal_message_buffer"`
  33. CallNotices struct {
  34. Start bool `yaml:"start"`
  35. End bool `yaml:"end"`
  36. } `yaml:"call_notices"`
  37. HistorySync struct {
  38. CreatePortals bool `yaml:"create_portals"`
  39. Backfill bool `yaml:"backfill"`
  40. DoublePuppetBackfill bool `yaml:"double_puppet_backfill"`
  41. }
  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. LoginSharedSecret string `yaml:"login_shared_secret"`
  49. PrivateChatPortalMeta bool `yaml:"private_chat_portal_meta"`
  50. BridgeNotices bool `yaml:"bridge_notices"`
  51. ResendBridgeInfo bool `yaml:"resend_bridge_info"`
  52. MuteBridging bool `yaml:"mute_bridging"`
  53. ArchiveTag string `yaml:"archive_tag"`
  54. PinnedTag string `yaml:"pinned_tag"`
  55. TagOnlyOnCreate bool `yaml:"tag_only_on_create"`
  56. MarkReadOnlyOnCreate bool `yaml:"mark_read_only_on_create"`
  57. EnableStatusBroadcast bool `yaml:"enable_status_broadcast"`
  58. WhatsappThumbnail bool `yaml:"whatsapp_thumbnail"`
  59. AllowUserInvite bool `yaml:"allow_user_invite"`
  60. CommandPrefix string `yaml:"command_prefix"`
  61. Encryption struct {
  62. Allow bool `yaml:"allow"`
  63. Default bool `yaml:"default"`
  64. KeySharing struct {
  65. Allow bool `yaml:"allow"`
  66. RequireCrossSigning bool `yaml:"require_cross_signing"`
  67. RequireVerification bool `yaml:"require_verification"`
  68. } `yaml:"key_sharing"`
  69. } `yaml:"encryption"`
  70. Permissions PermissionConfig `yaml:"permissions"`
  71. Relay RelaybotConfig `yaml:"relay"`
  72. usernameTemplate *template.Template `yaml:"-"`
  73. displaynameTemplate *template.Template `yaml:"-"`
  74. }
  75. func (bc *BridgeConfig) setDefaults() {
  76. bc.MaxConnectionAttempts = 3
  77. bc.ConnectionRetryDelay = -1
  78. bc.ReportConnectionRetry = true
  79. bc.PortalMessageBuffer = 128
  80. bc.CallNotices.Start = true
  81. bc.CallNotices.End = true
  82. bc.HistorySync.CreatePortals = true
  83. bc.UserAvatarSync = true
  84. bc.BridgeMatrixLeave = true
  85. bc.SyncWithCustomPuppets = true
  86. bc.DefaultBridgePresence = true
  87. bc.DefaultBridgeReceipts = true
  88. bc.BridgeNotices = true
  89. bc.EnableStatusBroadcast = true
  90. bc.Relay.AdminOnly = true
  91. }
  92. type umBridgeConfig BridgeConfig
  93. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  94. err := unmarshal((*umBridgeConfig)(bc))
  95. if err != nil {
  96. return err
  97. }
  98. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  99. if err != nil {
  100. return err
  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. PermissionLevelRelaybot 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":
  167. (*pc)[key] = PermissionLevelRelaybot
  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 PermissionLevelRelaybot:
  191. rawPC[key] = "relaybot"
  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) IsRelaybotWhitelisted(userID id.UserID) bool {
  203. return pc.GetPermissionLevel(userID) >= PermissionLevelRelaybot
  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 id.UserID
  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. var output strings.Builder
  259. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  260. Sender: Sender{
  261. UserID: sender,
  262. MemberEventContent: member,
  263. },
  264. Content: content,
  265. Message: content.FormattedBody,
  266. })
  267. return output.String(), err
  268. }