bridge.go 9.7 KB

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