bridge.go 9.5 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. )
  26. type BridgeConfig struct {
  27. UsernameTemplate string `yaml:"username_template"`
  28. DisplaynameTemplate string `yaml:"displayname_template"`
  29. CommunityTemplate string `yaml:"community_template"`
  30. ConnectionTimeout int `yaml:"connection_timeout"`
  31. FetchMessageOnTimeout bool `yaml:"fetch_message_on_timeout"`
  32. DeliveryReceipts bool `yaml:"delivery_receipts"`
  33. LoginQRRegenCount int `yaml:"login_qr_regen_count"`
  34. MaxConnectionAttempts int `yaml:"max_connection_attempts"`
  35. ConnectionRetryDelay int `yaml:"connection_retry_delay"`
  36. ReportConnectionRetry bool `yaml:"report_connection_retry"`
  37. AggressiveReconnect bool `yaml:"aggressive_reconnect"`
  38. ChatListWait int `yaml:"chat_list_wait"`
  39. PortalSyncWait int `yaml:"portal_sync_wait"`
  40. UserMessageBuffer int `yaml:"user_message_buffer"`
  41. PortalMessageBuffer int `yaml:"portal_message_buffer"`
  42. CallNotices struct {
  43. Start bool `yaml:"start"`
  44. End bool `yaml:"end"`
  45. } `yaml:"call_notices"`
  46. InitialChatSync int `yaml:"initial_chat_sync_count"`
  47. InitialHistoryFill int `yaml:"initial_history_fill_count"`
  48. HistoryDisableNotifs bool `yaml:"initial_history_disable_notifications"`
  49. RecoverChatSync int `yaml:"recovery_chat_sync_count"`
  50. RecoverHistory bool `yaml:"recovery_history_backfill"`
  51. ChatMetaSync bool `yaml:"chat_meta_sync"`
  52. UserAvatarSync bool `yaml:"user_avatar_sync"`
  53. BridgeMatrixLeave bool `yaml:"bridge_matrix_leave"`
  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.BridgeMatrixLeave = true
  102. bc.SyncChatMaxAge = 259200
  103. bc.SyncWithCustomPuppets = true
  104. bc.DefaultBridgePresence = true
  105. bc.DefaultBridgeReceipts = true
  106. bc.LoginSharedSecret = ""
  107. bc.InviteOwnPuppetForBackfilling = true
  108. bc.PrivateChatPortalMeta = false
  109. }
  110. type umBridgeConfig BridgeConfig
  111. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  112. err := unmarshal((*umBridgeConfig)(bc))
  113. if err != nil {
  114. return err
  115. }
  116. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  117. if err != nil {
  118. return err
  119. }
  120. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  121. if err != nil {
  122. return err
  123. }
  124. if len(bc.CommunityTemplate) > 0 {
  125. bc.communityTemplate, err = template.New("community").Parse(bc.CommunityTemplate)
  126. if err != nil {
  127. return err
  128. }
  129. }
  130. return nil
  131. }
  132. type UsernameTemplateArgs struct {
  133. UserID id.UserID
  134. }
  135. func (bc BridgeConfig) FormatDisplayname(contact whatsapp.Contact) (string, int8) {
  136. var buf bytes.Buffer
  137. if index := strings.IndexRune(contact.JID, '@'); index > 0 {
  138. contact.JID = "+" + contact.JID[:index]
  139. }
  140. bc.displaynameTemplate.Execute(&buf, contact)
  141. var quality int8
  142. switch {
  143. case len(contact.Notify) > 0:
  144. quality = 3
  145. case len(contact.Name) > 0 || len(contact.Short) > 0:
  146. quality = 2
  147. case len(contact.JID) > 0:
  148. quality = 1
  149. default:
  150. quality = 0
  151. }
  152. return buf.String(), quality
  153. }
  154. func (bc BridgeConfig) FormatUsername(userID whatsapp.JID) string {
  155. var buf bytes.Buffer
  156. bc.usernameTemplate.Execute(&buf, userID)
  157. return buf.String()
  158. }
  159. type CommunityTemplateArgs struct {
  160. Localpart string
  161. Server string
  162. }
  163. func (bc BridgeConfig) EnableCommunities() bool {
  164. return bc.communityTemplate != nil
  165. }
  166. func (bc BridgeConfig) FormatCommunity(localpart, server string) string {
  167. var buf bytes.Buffer
  168. bc.communityTemplate.Execute(&buf, CommunityTemplateArgs{localpart, server})
  169. return buf.String()
  170. }
  171. type PermissionConfig map[string]PermissionLevel
  172. type PermissionLevel int
  173. const (
  174. PermissionLevelDefault PermissionLevel = 0
  175. PermissionLevelRelaybot PermissionLevel = 5
  176. PermissionLevelUser PermissionLevel = 10
  177. PermissionLevelAdmin PermissionLevel = 100
  178. )
  179. func (pc *PermissionConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  180. rawPC := make(map[string]string)
  181. err := unmarshal(&rawPC)
  182. if err != nil {
  183. return err
  184. }
  185. if *pc == nil {
  186. *pc = make(map[string]PermissionLevel)
  187. }
  188. for key, value := range rawPC {
  189. switch strings.ToLower(value) {
  190. case "relaybot":
  191. (*pc)[key] = PermissionLevelRelaybot
  192. case "user":
  193. (*pc)[key] = PermissionLevelUser
  194. case "admin":
  195. (*pc)[key] = PermissionLevelAdmin
  196. default:
  197. val, err := strconv.Atoi(value)
  198. if err != nil {
  199. (*pc)[key] = PermissionLevelDefault
  200. } else {
  201. (*pc)[key] = PermissionLevel(val)
  202. }
  203. }
  204. }
  205. return nil
  206. }
  207. func (pc *PermissionConfig) MarshalYAML() (interface{}, error) {
  208. if *pc == nil {
  209. return nil, nil
  210. }
  211. rawPC := make(map[string]string)
  212. for key, value := range *pc {
  213. switch value {
  214. case PermissionLevelRelaybot:
  215. rawPC[key] = "relaybot"
  216. case PermissionLevelUser:
  217. rawPC[key] = "user"
  218. case PermissionLevelAdmin:
  219. rawPC[key] = "admin"
  220. default:
  221. rawPC[key] = strconv.Itoa(int(value))
  222. }
  223. }
  224. return rawPC, nil
  225. }
  226. func (pc PermissionConfig) IsRelaybotWhitelisted(userID id.UserID) bool {
  227. return pc.GetPermissionLevel(userID) >= PermissionLevelRelaybot
  228. }
  229. func (pc PermissionConfig) IsWhitelisted(userID id.UserID) bool {
  230. return pc.GetPermissionLevel(userID) >= PermissionLevelUser
  231. }
  232. func (pc PermissionConfig) IsAdmin(userID id.UserID) bool {
  233. return pc.GetPermissionLevel(userID) >= PermissionLevelAdmin
  234. }
  235. func (pc PermissionConfig) GetPermissionLevel(userID id.UserID) PermissionLevel {
  236. permissions, ok := pc[string(userID)]
  237. if ok {
  238. return permissions
  239. }
  240. _, homeserver, _ := userID.Parse()
  241. permissions, ok = pc[homeserver]
  242. if len(homeserver) > 0 && ok {
  243. return permissions
  244. }
  245. permissions, ok = pc["*"]
  246. if ok {
  247. return permissions
  248. }
  249. return PermissionLevelDefault
  250. }
  251. type RelaybotConfig struct {
  252. Enabled bool `yaml:"enabled"`
  253. ManagementRoom id.RoomID `yaml:"management"`
  254. InviteUsers []id.UserID `yaml:"invites"`
  255. MessageFormats map[event.MessageType]string `yaml:"message_formats"`
  256. messageTemplates *template.Template `yaml:"-"`
  257. }
  258. type umRelaybotConfig RelaybotConfig
  259. func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  260. err := unmarshal((*umRelaybotConfig)(rc))
  261. if err != nil {
  262. return err
  263. }
  264. rc.messageTemplates = template.New("messageTemplates")
  265. for key, format := range rc.MessageFormats {
  266. _, err := rc.messageTemplates.New(string(key)).Parse(format)
  267. if err != nil {
  268. return err
  269. }
  270. }
  271. return nil
  272. }
  273. type Sender struct {
  274. UserID id.UserID
  275. *event.MemberEventContent
  276. }
  277. type formatData struct {
  278. Sender Sender
  279. Message string
  280. Content *event.MessageEventContent
  281. }
  282. func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member *event.MemberEventContent) (string, error) {
  283. var output strings.Builder
  284. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  285. Sender: Sender{
  286. UserID: sender,
  287. MemberEventContent: member,
  288. },
  289. Content: content,
  290. Message: content.FormattedBody,
  291. })
  292. return output.String(), err
  293. }