bridge.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "strconv"
  19. "strings"
  20. "text/template"
  21. "go.mau.fi/whatsmeow/types"
  22. "maunium.net/go/mautrix/event"
  23. "maunium.net/go/mautrix/id"
  24. )
  25. type BridgeConfig struct {
  26. UsernameTemplate string `yaml:"username_template"`
  27. DisplaynameTemplate string `yaml:"displayname_template"`
  28. DeliveryReceipts bool `yaml:"delivery_receipts"`
  29. PortalMessageBuffer int `yaml:"portal_message_buffer"`
  30. CallNotices struct {
  31. Start bool `yaml:"start"`
  32. End bool `yaml:"end"`
  33. } `yaml:"call_notices"`
  34. HistorySync struct {
  35. CreatePortals bool `yaml:"create_portals"`
  36. Backfill bool `yaml:"backfill"`
  37. DoublePuppetBackfill bool `yaml:"double_puppet_backfill"`
  38. } `yaml:"history_sync"`
  39. UserAvatarSync bool `yaml:"user_avatar_sync"`
  40. BridgeMatrixLeave bool `yaml:"bridge_matrix_leave"`
  41. SyncWithCustomPuppets bool `yaml:"sync_with_custom_puppets"`
  42. SyncDirectChatList bool `yaml:"sync_direct_chat_list"`
  43. DefaultBridgeReceipts bool `yaml:"default_bridge_receipts"`
  44. DefaultBridgePresence bool `yaml:"default_bridge_presence"`
  45. LoginSharedSecret string `yaml:"login_shared_secret"`
  46. PrivateChatPortalMeta bool `yaml:"private_chat_portal_meta"`
  47. BridgeNotices bool `yaml:"bridge_notices"`
  48. ResendBridgeInfo bool `yaml:"resend_bridge_info"`
  49. MuteBridging bool `yaml:"mute_bridging"`
  50. ArchiveTag string `yaml:"archive_tag"`
  51. PinnedTag string `yaml:"pinned_tag"`
  52. TagOnlyOnCreate bool `yaml:"tag_only_on_create"`
  53. MarkReadOnlyOnCreate bool `yaml:"mark_read_only_on_create"`
  54. EnableStatusBroadcast bool `yaml:"enable_status_broadcast"`
  55. WhatsappThumbnail bool `yaml:"whatsapp_thumbnail"`
  56. AllowUserInvite bool `yaml:"allow_user_invite"`
  57. CommandPrefix string `yaml:"command_prefix"`
  58. ManagementRoomText struct {
  59. Welcome string `yaml:"welcome"`
  60. WelcomeConnected string `yaml:"welcome_connected"`
  61. WelcomeUnconnected string `yaml:"welcome_unconnected"`
  62. AdditionalHelp string `yaml:"additional_help"`
  63. } `yaml:"management_room_text"`
  64. Encryption struct {
  65. Allow bool `yaml:"allow"`
  66. Default bool `yaml:"default"`
  67. KeySharing struct {
  68. Allow bool `yaml:"allow"`
  69. RequireCrossSigning bool `yaml:"require_cross_signing"`
  70. RequireVerification bool `yaml:"require_verification"`
  71. } `yaml:"key_sharing"`
  72. } `yaml:"encryption"`
  73. Permissions PermissionConfig `yaml:"permissions"`
  74. Relay RelaybotConfig `yaml:"relay"`
  75. usernameTemplate *template.Template `yaml:"-"`
  76. displaynameTemplate *template.Template `yaml:"-"`
  77. }
  78. func (bc *BridgeConfig) setDefaults() {
  79. bc.PortalMessageBuffer = 128
  80. bc.CallNotices.Start = true
  81. bc.CallNotices.End = true
  82. bc.HistorySync.CreatePortals = true
  83. bc.UserAvatarSync = true
  84. bc.BridgeMatrixLeave = true
  85. bc.SyncWithCustomPuppets = true
  86. bc.DefaultBridgePresence = true
  87. bc.DefaultBridgeReceipts = true
  88. bc.BridgeNotices = true
  89. bc.EnableStatusBroadcast = true
  90. bc.ManagementRoomText.Welcome = "Hello, I'm a WhatsApp bridge bot."
  91. bc.ManagementRoomText.WelcomeConnected = "Use `help` for help."
  92. bc.ManagementRoomText.WelcomeUnconnected = "Use `help` for help or `login` to log in."
  93. }
  94. type umBridgeConfig BridgeConfig
  95. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  96. err := unmarshal((*umBridgeConfig)(bc))
  97. if err != nil {
  98. return err
  99. }
  100. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  101. if err != nil {
  102. return err
  103. }
  104. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  105. if err != nil {
  106. return err
  107. }
  108. return nil
  109. }
  110. type UsernameTemplateArgs struct {
  111. UserID id.UserID
  112. }
  113. type legacyContactInfo struct {
  114. types.ContactInfo
  115. Phone string
  116. Notify string
  117. VName string
  118. Name string
  119. Short string
  120. JID string
  121. }
  122. func (bc BridgeConfig) FormatDisplayname(jid types.JID, contact types.ContactInfo) (string, int8) {
  123. var buf strings.Builder
  124. _ = bc.displaynameTemplate.Execute(&buf, legacyContactInfo{
  125. ContactInfo: contact,
  126. Notify: contact.PushName,
  127. VName: contact.BusinessName,
  128. Name: contact.FullName,
  129. Short: contact.FirstName,
  130. Phone: "+" + jid.User,
  131. JID: "+" + jid.User,
  132. })
  133. var quality int8
  134. switch {
  135. case len(contact.PushName) > 0 || len(contact.BusinessName) > 0:
  136. quality = 3
  137. case len(contact.FullName) > 0 || len(contact.FirstName) > 0:
  138. quality = 2
  139. default:
  140. quality = 1
  141. }
  142. return buf.String(), quality
  143. }
  144. func (bc BridgeConfig) FormatUsername(username string) string {
  145. var buf strings.Builder
  146. _ = bc.usernameTemplate.Execute(&buf, username)
  147. return buf.String()
  148. }
  149. type PermissionConfig map[string]PermissionLevel
  150. type PermissionLevel int
  151. const (
  152. PermissionLevelDefault PermissionLevel = 0
  153. PermissionLevelRelay PermissionLevel = 5
  154. PermissionLevelUser PermissionLevel = 10
  155. PermissionLevelAdmin PermissionLevel = 100
  156. )
  157. func (pc *PermissionConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  158. rawPC := make(map[string]string)
  159. err := unmarshal(&rawPC)
  160. if err != nil {
  161. return err
  162. }
  163. if *pc == nil {
  164. *pc = make(map[string]PermissionLevel)
  165. }
  166. for key, value := range rawPC {
  167. switch strings.ToLower(value) {
  168. case "relaybot", "relay":
  169. (*pc)[key] = PermissionLevelRelay
  170. case "user":
  171. (*pc)[key] = PermissionLevelUser
  172. case "admin":
  173. (*pc)[key] = PermissionLevelAdmin
  174. default:
  175. val, err := strconv.Atoi(value)
  176. if err != nil {
  177. (*pc)[key] = PermissionLevelDefault
  178. } else {
  179. (*pc)[key] = PermissionLevel(val)
  180. }
  181. }
  182. }
  183. return nil
  184. }
  185. func (pc *PermissionConfig) MarshalYAML() (interface{}, error) {
  186. if *pc == nil {
  187. return nil, nil
  188. }
  189. rawPC := make(map[string]string)
  190. for key, value := range *pc {
  191. switch value {
  192. case PermissionLevelRelay:
  193. rawPC[key] = "relay"
  194. case PermissionLevelUser:
  195. rawPC[key] = "user"
  196. case PermissionLevelAdmin:
  197. rawPC[key] = "admin"
  198. default:
  199. rawPC[key] = strconv.Itoa(int(value))
  200. }
  201. }
  202. return rawPC, nil
  203. }
  204. func (pc PermissionConfig) IsRelayWhitelisted(userID id.UserID) bool {
  205. return pc.GetPermissionLevel(userID) >= PermissionLevelRelay
  206. }
  207. func (pc PermissionConfig) IsWhitelisted(userID id.UserID) bool {
  208. return pc.GetPermissionLevel(userID) >= PermissionLevelUser
  209. }
  210. func (pc PermissionConfig) IsAdmin(userID id.UserID) bool {
  211. return pc.GetPermissionLevel(userID) >= PermissionLevelAdmin
  212. }
  213. func (pc PermissionConfig) GetPermissionLevel(userID id.UserID) PermissionLevel {
  214. permissions, ok := pc[string(userID)]
  215. if ok {
  216. return permissions
  217. }
  218. _, homeserver, _ := userID.Parse()
  219. permissions, ok = pc[homeserver]
  220. if len(homeserver) > 0 && ok {
  221. return permissions
  222. }
  223. permissions, ok = pc["*"]
  224. if ok {
  225. return permissions
  226. }
  227. return PermissionLevelDefault
  228. }
  229. type RelaybotConfig struct {
  230. Enabled bool `yaml:"enabled"`
  231. AdminOnly bool `yaml:"admin_only"`
  232. MessageFormats map[event.MessageType]string `yaml:"message_formats"`
  233. messageTemplates *template.Template `yaml:"-"`
  234. }
  235. type umRelaybotConfig RelaybotConfig
  236. func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  237. err := unmarshal((*umRelaybotConfig)(rc))
  238. if err != nil {
  239. return err
  240. }
  241. rc.messageTemplates = template.New("messageTemplates")
  242. for key, format := range rc.MessageFormats {
  243. _, err := rc.messageTemplates.New(string(key)).Parse(format)
  244. if err != nil {
  245. return err
  246. }
  247. }
  248. return nil
  249. }
  250. type Sender struct {
  251. UserID id.UserID
  252. *event.MemberEventContent
  253. }
  254. type formatData struct {
  255. Sender Sender
  256. Message string
  257. Content *event.MessageEventContent
  258. }
  259. func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member *event.MemberEventContent) (string, error) {
  260. var output strings.Builder
  261. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  262. Sender: Sender{
  263. UserID: sender,
  264. MemberEventContent: member,
  265. },
  266. Content: content,
  267. Message: content.FormattedBody,
  268. })
  269. return output.String(), err
  270. }