bridge.go 9.5 KB

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