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. Relaybot RelaybotConfig `yaml:"relaybot"`
  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. }
  91. type umBridgeConfig BridgeConfig
  92. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  93. err := unmarshal((*umBridgeConfig)(bc))
  94. if err != nil {
  95. return err
  96. }
  97. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  98. if err != nil {
  99. return err
  100. }
  101. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  102. if err != nil {
  103. return err
  104. }
  105. return nil
  106. }
  107. type UsernameTemplateArgs struct {
  108. UserID id.UserID
  109. }
  110. type legacyContactInfo struct {
  111. types.ContactInfo
  112. Phone string
  113. Notify string
  114. VName string
  115. Name string
  116. Short string
  117. JID string
  118. }
  119. func (bc BridgeConfig) FormatDisplayname(jid types.JID, contact types.ContactInfo) (string, int8) {
  120. var buf strings.Builder
  121. _ = bc.displaynameTemplate.Execute(&buf, legacyContactInfo{
  122. ContactInfo: contact,
  123. Notify: contact.PushName,
  124. VName: contact.BusinessName,
  125. Name: contact.FullName,
  126. Short: contact.FirstName,
  127. Phone: "+" + jid.User,
  128. JID: "+" + jid.User,
  129. })
  130. var quality int8
  131. switch {
  132. case len(contact.PushName) > 0 || len(contact.BusinessName) > 0:
  133. quality = 3
  134. case len(contact.FullName) > 0 || len(contact.FirstName) > 0:
  135. quality = 2
  136. default:
  137. quality = 1
  138. }
  139. return buf.String(), quality
  140. }
  141. func (bc BridgeConfig) FormatUsername(username string) string {
  142. var buf strings.Builder
  143. _ = bc.usernameTemplate.Execute(&buf, username)
  144. return buf.String()
  145. }
  146. type PermissionConfig map[string]PermissionLevel
  147. type PermissionLevel int
  148. const (
  149. PermissionLevelDefault PermissionLevel = 0
  150. PermissionLevelRelaybot PermissionLevel = 5
  151. PermissionLevelUser PermissionLevel = 10
  152. PermissionLevelAdmin PermissionLevel = 100
  153. )
  154. func (pc *PermissionConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  155. rawPC := make(map[string]string)
  156. err := unmarshal(&rawPC)
  157. if err != nil {
  158. return err
  159. }
  160. if *pc == nil {
  161. *pc = make(map[string]PermissionLevel)
  162. }
  163. for key, value := range rawPC {
  164. switch strings.ToLower(value) {
  165. case "relaybot":
  166. (*pc)[key] = PermissionLevelRelaybot
  167. case "user":
  168. (*pc)[key] = PermissionLevelUser
  169. case "admin":
  170. (*pc)[key] = PermissionLevelAdmin
  171. default:
  172. val, err := strconv.Atoi(value)
  173. if err != nil {
  174. (*pc)[key] = PermissionLevelDefault
  175. } else {
  176. (*pc)[key] = PermissionLevel(val)
  177. }
  178. }
  179. }
  180. return nil
  181. }
  182. func (pc *PermissionConfig) MarshalYAML() (interface{}, error) {
  183. if *pc == nil {
  184. return nil, nil
  185. }
  186. rawPC := make(map[string]string)
  187. for key, value := range *pc {
  188. switch value {
  189. case PermissionLevelRelaybot:
  190. rawPC[key] = "relaybot"
  191. case PermissionLevelUser:
  192. rawPC[key] = "user"
  193. case PermissionLevelAdmin:
  194. rawPC[key] = "admin"
  195. default:
  196. rawPC[key] = strconv.Itoa(int(value))
  197. }
  198. }
  199. return rawPC, nil
  200. }
  201. func (pc PermissionConfig) IsRelaybotWhitelisted(userID id.UserID) bool {
  202. return pc.GetPermissionLevel(userID) >= PermissionLevelRelaybot
  203. }
  204. func (pc PermissionConfig) IsWhitelisted(userID id.UserID) bool {
  205. return pc.GetPermissionLevel(userID) >= PermissionLevelUser
  206. }
  207. func (pc PermissionConfig) IsAdmin(userID id.UserID) bool {
  208. return pc.GetPermissionLevel(userID) >= PermissionLevelAdmin
  209. }
  210. func (pc PermissionConfig) GetPermissionLevel(userID id.UserID) PermissionLevel {
  211. permissions, ok := pc[string(userID)]
  212. if ok {
  213. return permissions
  214. }
  215. _, homeserver, _ := userID.Parse()
  216. permissions, ok = pc[homeserver]
  217. if len(homeserver) > 0 && ok {
  218. return permissions
  219. }
  220. permissions, ok = pc["*"]
  221. if ok {
  222. return permissions
  223. }
  224. return PermissionLevelDefault
  225. }
  226. type RelaybotConfig struct {
  227. Enabled bool `yaml:"enabled"`
  228. ManagementRoom id.RoomID `yaml:"management"`
  229. InviteUsers []id.UserID `yaml:"invites"`
  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. }