bridge.go 9.4 KB

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