bridge.go 8.3 KB

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