bridge.go 8.9 KB

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