bridge.go 8.5 KB

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