bridge.go 9.1 KB

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