bridge.go 8.0 KB

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