bridge.go 8.1 KB

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