bridge.go 10 KB

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