bridge.go 9.5 KB

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