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. "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. BridgeMatrixLeave bool `yaml:"bridge_matrix_leave"`
  55. SyncChatMaxAge uint64 `yaml:"sync_max_chat_age"`
  56. SyncWithCustomPuppets bool `yaml:"sync_with_custom_puppets"`
  57. SyncDirectChatList bool `yaml:"sync_direct_chat_list"`
  58. DefaultBridgeReceipts bool `yaml:"default_bridge_receipts"`
  59. DefaultBridgePresence bool `yaml:"default_bridge_presence"`
  60. LoginSharedSecret string `yaml:"login_shared_secret"`
  61. InviteOwnPuppetForBackfilling bool `yaml:"invite_own_puppet_for_backfilling"`
  62. PrivateChatPortalMeta bool `yaml:"private_chat_portal_meta"`
  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. }
  111. type umBridgeConfig BridgeConfig
  112. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  113. err := unmarshal((*umBridgeConfig)(bc))
  114. if err != nil {
  115. return err
  116. }
  117. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  118. if err != nil {
  119. return err
  120. }
  121. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  122. if err != nil {
  123. return err
  124. }
  125. if len(bc.CommunityTemplate) > 0 {
  126. bc.communityTemplate, err = template.New("community").Parse(bc.CommunityTemplate)
  127. if err != nil {
  128. return err
  129. }
  130. }
  131. return nil
  132. }
  133. type UsernameTemplateArgs struct {
  134. UserID id.UserID
  135. }
  136. func (bc BridgeConfig) FormatDisplayname(contact whatsapp.Contact) (string, int8) {
  137. var buf bytes.Buffer
  138. if index := strings.IndexRune(contact.Jid, '@'); index > 0 {
  139. contact.Jid = "+" + contact.Jid[:index]
  140. }
  141. bc.displaynameTemplate.Execute(&buf, contact)
  142. var quality int8
  143. switch {
  144. case len(contact.Notify) > 0:
  145. quality = 3
  146. case len(contact.Name) > 0 || len(contact.Short) > 0:
  147. quality = 2
  148. case len(contact.Jid) > 0:
  149. quality = 1
  150. default:
  151. quality = 0
  152. }
  153. return buf.String(), quality
  154. }
  155. func (bc BridgeConfig) FormatUsername(userID types.WhatsAppID) string {
  156. var buf bytes.Buffer
  157. bc.usernameTemplate.Execute(&buf, userID)
  158. return buf.String()
  159. }
  160. type CommunityTemplateArgs struct {
  161. Localpart string
  162. Server string
  163. }
  164. func (bc BridgeConfig) EnableCommunities() bool {
  165. return bc.communityTemplate != nil
  166. }
  167. func (bc BridgeConfig) FormatCommunity(localpart, server string) string {
  168. var buf bytes.Buffer
  169. bc.communityTemplate.Execute(&buf, CommunityTemplateArgs{localpart, server})
  170. return buf.String()
  171. }
  172. type PermissionConfig map[string]PermissionLevel
  173. type PermissionLevel int
  174. const (
  175. PermissionLevelDefault PermissionLevel = 0
  176. PermissionLevelRelaybot PermissionLevel = 5
  177. PermissionLevelUser PermissionLevel = 10
  178. PermissionLevelAdmin PermissionLevel = 100
  179. )
  180. func (pc *PermissionConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  181. rawPC := make(map[string]string)
  182. err := unmarshal(&rawPC)
  183. if err != nil {
  184. return err
  185. }
  186. if *pc == nil {
  187. *pc = make(map[string]PermissionLevel)
  188. }
  189. for key, value := range rawPC {
  190. switch strings.ToLower(value) {
  191. case "relaybot":
  192. (*pc)[key] = PermissionLevelRelaybot
  193. case "user":
  194. (*pc)[key] = PermissionLevelUser
  195. case "admin":
  196. (*pc)[key] = PermissionLevelAdmin
  197. default:
  198. val, err := strconv.Atoi(value)
  199. if err != nil {
  200. (*pc)[key] = PermissionLevelDefault
  201. } else {
  202. (*pc)[key] = PermissionLevel(val)
  203. }
  204. }
  205. }
  206. return nil
  207. }
  208. func (pc *PermissionConfig) MarshalYAML() (interface{}, error) {
  209. if *pc == nil {
  210. return nil, nil
  211. }
  212. rawPC := make(map[string]string)
  213. for key, value := range *pc {
  214. switch value {
  215. case PermissionLevelRelaybot:
  216. rawPC[key] = "relaybot"
  217. case PermissionLevelUser:
  218. rawPC[key] = "user"
  219. case PermissionLevelAdmin:
  220. rawPC[key] = "admin"
  221. default:
  222. rawPC[key] = strconv.Itoa(int(value))
  223. }
  224. }
  225. return rawPC, nil
  226. }
  227. func (pc PermissionConfig) IsRelaybotWhitelisted(userID id.UserID) bool {
  228. return pc.GetPermissionLevel(userID) >= PermissionLevelRelaybot
  229. }
  230. func (pc PermissionConfig) IsWhitelisted(userID id.UserID) bool {
  231. return pc.GetPermissionLevel(userID) >= PermissionLevelUser
  232. }
  233. func (pc PermissionConfig) IsAdmin(userID id.UserID) bool {
  234. return pc.GetPermissionLevel(userID) >= PermissionLevelAdmin
  235. }
  236. func (pc PermissionConfig) GetPermissionLevel(userID id.UserID) PermissionLevel {
  237. permissions, ok := pc[string(userID)]
  238. if ok {
  239. return permissions
  240. }
  241. _, homeserver, _ := userID.Parse()
  242. permissions, ok = pc[homeserver]
  243. if len(homeserver) > 0 && ok {
  244. return permissions
  245. }
  246. permissions, ok = pc["*"]
  247. if ok {
  248. return permissions
  249. }
  250. return PermissionLevelDefault
  251. }
  252. type RelaybotConfig struct {
  253. Enabled bool `yaml:"enabled"`
  254. ManagementRoom id.RoomID `yaml:"management"`
  255. InviteUsers []id.UserID `yaml:"invites"`
  256. MessageFormats map[event.MessageType]string `yaml:"message_formats"`
  257. messageTemplates *template.Template `yaml:"-"`
  258. }
  259. type umRelaybotConfig RelaybotConfig
  260. func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  261. err := unmarshal((*umRelaybotConfig)(rc))
  262. if err != nil {
  263. return err
  264. }
  265. rc.messageTemplates = template.New("messageTemplates")
  266. for key, format := range rc.MessageFormats {
  267. _, err := rc.messageTemplates.New(string(key)).Parse(format)
  268. if err != nil {
  269. return err
  270. }
  271. }
  272. return nil
  273. }
  274. type Sender struct {
  275. UserID id.UserID
  276. *event.MemberEventContent
  277. }
  278. type formatData struct {
  279. Sender Sender
  280. Message string
  281. Content *event.MessageEventContent
  282. }
  283. func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member *event.MemberEventContent) (string, error) {
  284. var output strings.Builder
  285. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  286. Sender: Sender{
  287. UserID: sender,
  288. MemberEventContent: member,
  289. },
  290. Content: content,
  291. Message: content.FormattedBody,
  292. })
  293. return output.String(), err
  294. }