bridge.go 9.9 KB

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