bridge.go 9.2 KB

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