bridge.go 9.3 KB

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