bridge.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. InitialChatSync int `yaml:"initial_chat_sync_count"`
  38. InitialHistoryFill int `yaml:"initial_history_fill_count"`
  39. HistoryDisableNotifs bool `yaml:"initial_history_disable_notifications"`
  40. RecoverChatSync int `yaml:"recovery_chat_sync_count"`
  41. RecoverHistory bool `yaml:"recovery_history_backfill"`
  42. ChatMetaSync bool `yaml:"chat_meta_sync"`
  43. UserAvatarSync bool `yaml:"user_avatar_sync"`
  44. BridgeMatrixLeave bool `yaml:"bridge_matrix_leave"`
  45. SyncChatMaxAge int64 `yaml:"sync_max_chat_age"`
  46. SyncWithCustomPuppets bool `yaml:"sync_with_custom_puppets"`
  47. SyncDirectChatList bool `yaml:"sync_direct_chat_list"`
  48. DefaultBridgeReceipts bool `yaml:"default_bridge_receipts"`
  49. DefaultBridgePresence bool `yaml:"default_bridge_presence"`
  50. LoginSharedSecret string `yaml:"login_shared_secret"`
  51. InviteOwnPuppetForBackfilling bool `yaml:"invite_own_puppet_for_backfilling"`
  52. PrivateChatPortalMeta bool `yaml:"private_chat_portal_meta"`
  53. BridgeNotices bool `yaml:"bridge_notices"`
  54. ResendBridgeInfo bool `yaml:"resend_bridge_info"`
  55. MuteBridging bool `yaml:"mute_bridging"`
  56. ArchiveTag string `yaml:"archive_tag"`
  57. PinnedTag string `yaml:"pinned_tag"`
  58. TagOnlyOnCreate bool `yaml:"tag_only_on_create"`
  59. MarkReadOnlyOnCreate bool `yaml:"mark_read_only_on_create"`
  60. EnableStatusBroadcast bool `yaml:"enable_status_broadcast"`
  61. WhatsappThumbnail bool `yaml:"whatsapp_thumbnail"`
  62. AllowUserInvite bool `yaml:"allow_user_invite"`
  63. CommandPrefix string `yaml:"command_prefix"`
  64. Encryption struct {
  65. Allow bool `yaml:"allow"`
  66. Default bool `yaml:"default"`
  67. KeySharing struct {
  68. Allow bool `yaml:"allow"`
  69. RequireCrossSigning bool `yaml:"require_cross_signing"`
  70. RequireVerification bool `yaml:"require_verification"`
  71. } `yaml:"key_sharing"`
  72. } `yaml:"encryption"`
  73. Permissions PermissionConfig `yaml:"permissions"`
  74. Relaybot RelaybotConfig `yaml:"relaybot"`
  75. usernameTemplate *template.Template `yaml:"-"`
  76. displaynameTemplate *template.Template `yaml:"-"`
  77. }
  78. func (bc *BridgeConfig) setDefaults() {
  79. bc.DeliveryReceipts = false
  80. bc.MaxConnectionAttempts = 3
  81. bc.ConnectionRetryDelay = -1
  82. bc.ReportConnectionRetry = true
  83. bc.PortalMessageBuffer = 128
  84. bc.CallNotices.Start = true
  85. bc.CallNotices.End = true
  86. bc.InitialChatSync = 10
  87. bc.InitialHistoryFill = 20
  88. bc.RecoverChatSync = -1
  89. bc.RecoverHistory = true
  90. bc.ChatMetaSync = true
  91. bc.UserAvatarSync = true
  92. bc.BridgeMatrixLeave = true
  93. bc.SyncChatMaxAge = 259200
  94. bc.SyncWithCustomPuppets = true
  95. bc.DefaultBridgePresence = true
  96. bc.DefaultBridgeReceipts = true
  97. bc.LoginSharedSecret = ""
  98. bc.InviteOwnPuppetForBackfilling = true
  99. bc.PrivateChatPortalMeta = false
  100. bc.BridgeNotices = true
  101. bc.EnableStatusBroadcast = true
  102. }
  103. type umBridgeConfig BridgeConfig
  104. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  105. err := unmarshal((*umBridgeConfig)(bc))
  106. if err != nil {
  107. return err
  108. }
  109. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  110. if err != nil {
  111. return err
  112. }
  113. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  114. if err != nil {
  115. return err
  116. }
  117. return nil
  118. }
  119. type UsernameTemplateArgs struct {
  120. UserID id.UserID
  121. }
  122. type legacyContactInfo struct {
  123. types.ContactInfo
  124. Phone string
  125. Notify string
  126. VName string
  127. Name string
  128. Short string
  129. JID string
  130. }
  131. func (bc BridgeConfig) FormatDisplayname(jid types.JID, contact types.ContactInfo) (string, int8) {
  132. var buf strings.Builder
  133. _ = bc.displaynameTemplate.Execute(&buf, legacyContactInfo{
  134. ContactInfo: contact,
  135. Notify: contact.PushName,
  136. VName: contact.BusinessName,
  137. Name: contact.FullName,
  138. Short: contact.FirstName,
  139. Phone: "+" + jid.User,
  140. JID: "+" + jid.User,
  141. })
  142. var quality int8
  143. switch {
  144. case len(contact.PushName) > 0 || len(contact.BusinessName) > 0:
  145. quality = 3
  146. case len(contact.FullName) > 0 || len(contact.FirstName) > 0:
  147. quality = 2
  148. default:
  149. quality = 1
  150. }
  151. return buf.String(), quality
  152. }
  153. func (bc BridgeConfig) FormatUsername(username string) string {
  154. var buf strings.Builder
  155. _ = bc.usernameTemplate.Execute(&buf, username)
  156. return buf.String()
  157. }
  158. type PermissionConfig map[string]PermissionLevel
  159. type PermissionLevel int
  160. const (
  161. PermissionLevelDefault PermissionLevel = 0
  162. PermissionLevelRelaybot PermissionLevel = 5
  163. PermissionLevelUser PermissionLevel = 10
  164. PermissionLevelAdmin PermissionLevel = 100
  165. )
  166. func (pc *PermissionConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  167. rawPC := make(map[string]string)
  168. err := unmarshal(&rawPC)
  169. if err != nil {
  170. return err
  171. }
  172. if *pc == nil {
  173. *pc = make(map[string]PermissionLevel)
  174. }
  175. for key, value := range rawPC {
  176. switch strings.ToLower(value) {
  177. case "relaybot":
  178. (*pc)[key] = PermissionLevelRelaybot
  179. case "user":
  180. (*pc)[key] = PermissionLevelUser
  181. case "admin":
  182. (*pc)[key] = PermissionLevelAdmin
  183. default:
  184. val, err := strconv.Atoi(value)
  185. if err != nil {
  186. (*pc)[key] = PermissionLevelDefault
  187. } else {
  188. (*pc)[key] = PermissionLevel(val)
  189. }
  190. }
  191. }
  192. return nil
  193. }
  194. func (pc *PermissionConfig) MarshalYAML() (interface{}, error) {
  195. if *pc == nil {
  196. return nil, nil
  197. }
  198. rawPC := make(map[string]string)
  199. for key, value := range *pc {
  200. switch value {
  201. case PermissionLevelRelaybot:
  202. rawPC[key] = "relaybot"
  203. case PermissionLevelUser:
  204. rawPC[key] = "user"
  205. case PermissionLevelAdmin:
  206. rawPC[key] = "admin"
  207. default:
  208. rawPC[key] = strconv.Itoa(int(value))
  209. }
  210. }
  211. return rawPC, nil
  212. }
  213. func (pc PermissionConfig) IsRelaybotWhitelisted(userID id.UserID) bool {
  214. return pc.GetPermissionLevel(userID) >= PermissionLevelRelaybot
  215. }
  216. func (pc PermissionConfig) IsWhitelisted(userID id.UserID) bool {
  217. return pc.GetPermissionLevel(userID) >= PermissionLevelUser
  218. }
  219. func (pc PermissionConfig) IsAdmin(userID id.UserID) bool {
  220. return pc.GetPermissionLevel(userID) >= PermissionLevelAdmin
  221. }
  222. func (pc PermissionConfig) GetPermissionLevel(userID id.UserID) PermissionLevel {
  223. permissions, ok := pc[string(userID)]
  224. if ok {
  225. return permissions
  226. }
  227. _, homeserver, _ := userID.Parse()
  228. permissions, ok = pc[homeserver]
  229. if len(homeserver) > 0 && ok {
  230. return permissions
  231. }
  232. permissions, ok = pc["*"]
  233. if ok {
  234. return permissions
  235. }
  236. return PermissionLevelDefault
  237. }
  238. type RelaybotConfig struct {
  239. Enabled bool `yaml:"enabled"`
  240. ManagementRoom id.RoomID `yaml:"management"`
  241. InviteUsers []id.UserID `yaml:"invites"`
  242. MessageFormats map[event.MessageType]string `yaml:"message_formats"`
  243. messageTemplates *template.Template `yaml:"-"`
  244. }
  245. type umRelaybotConfig RelaybotConfig
  246. func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  247. err := unmarshal((*umRelaybotConfig)(rc))
  248. if err != nil {
  249. return err
  250. }
  251. rc.messageTemplates = template.New("messageTemplates")
  252. for key, format := range rc.MessageFormats {
  253. _, err := rc.messageTemplates.New(string(key)).Parse(format)
  254. if err != nil {
  255. return err
  256. }
  257. }
  258. return nil
  259. }
  260. type Sender struct {
  261. UserID id.UserID
  262. *event.MemberEventContent
  263. }
  264. type formatData struct {
  265. Sender Sender
  266. Message string
  267. Content *event.MessageEventContent
  268. }
  269. func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member *event.MemberEventContent) (string, error) {
  270. var output strings.Builder
  271. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  272. Sender: Sender{
  273. UserID: sender,
  274. MemberEventContent: member,
  275. },
  276. Content: content,
  277. Message: content.FormattedBody,
  278. })
  279. return output.String(), err
  280. }