bridge.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. "errors"
  19. "fmt"
  20. "strings"
  21. "text/template"
  22. "go.mau.fi/whatsmeow/types"
  23. "maunium.net/go/mautrix/bridge/bridgeconfig"
  24. "maunium.net/go/mautrix/event"
  25. "maunium.net/go/mautrix/id"
  26. )
  27. type DeferredConfig struct {
  28. StartDaysAgo int `yaml:"start_days_ago"`
  29. MaxBatchEvents int `yaml:"max_batch_events"`
  30. BatchDelay int `yaml:"batch_delay"`
  31. }
  32. type MediaRequestMethod string
  33. const (
  34. MediaRequestMethodImmediate MediaRequestMethod = "immediate"
  35. MediaRequestMethodLocalTime = "local_time"
  36. )
  37. type BridgeConfig struct {
  38. UsernameTemplate string `yaml:"username_template"`
  39. DisplaynameTemplate string `yaml:"displayname_template"`
  40. PersonalFilteringSpaces bool `yaml:"personal_filtering_spaces"`
  41. DeliveryReceipts bool `yaml:"delivery_receipts"`
  42. MessageStatusEvents bool `yaml:"message_status_events"`
  43. MessageErrorNotices bool `yaml:"message_error_notices"`
  44. PortalMessageBuffer int `yaml:"portal_message_buffer"`
  45. CallStartNotices bool `yaml:"call_start_notices"`
  46. IdentityChangeNotices bool `yaml:"identity_change_notices"`
  47. HistorySync struct {
  48. CreatePortals bool `yaml:"create_portals"`
  49. Backfill bool `yaml:"backfill"`
  50. DoublePuppetBackfill bool `yaml:"double_puppet_backfill"`
  51. RequestFullSync bool `yaml:"request_full_sync"`
  52. MaxInitialConversations int `yaml:"max_initial_conversations"`
  53. Immediate struct {
  54. WorkerCount int `yaml:"worker_count"`
  55. MaxEvents int `yaml:"max_events"`
  56. } `yaml:"immediate"`
  57. MediaRequests struct {
  58. AutoRequestMedia bool `yaml:"auto_request_media"`
  59. RequestMethod MediaRequestMethod `yaml:"request_method"`
  60. RequestLocalTime int `yaml:"request_local_time"`
  61. } `yaml:"media_requests"`
  62. Deferred []DeferredConfig `yaml:"deferred"`
  63. } `yaml:"history_sync"`
  64. UserAvatarSync bool `yaml:"user_avatar_sync"`
  65. BridgeMatrixLeave bool `yaml:"bridge_matrix_leave"`
  66. SyncWithCustomPuppets bool `yaml:"sync_with_custom_puppets"`
  67. SyncDirectChatList bool `yaml:"sync_direct_chat_list"`
  68. SyncManualMarkedUnread bool `yaml:"sync_manual_marked_unread"`
  69. DefaultBridgeReceipts bool `yaml:"default_bridge_receipts"`
  70. DefaultBridgePresence bool `yaml:"default_bridge_presence"`
  71. SendPresenceOnTyping bool `yaml:"send_presence_on_typing"`
  72. ForceActiveDeliveryReceipts bool `yaml:"force_active_delivery_receipts"`
  73. DoublePuppetServerMap map[string]string `yaml:"double_puppet_server_map"`
  74. DoublePuppetAllowDiscovery bool `yaml:"double_puppet_allow_discovery"`
  75. LoginSharedSecretMap map[string]string `yaml:"login_shared_secret_map"`
  76. PrivateChatPortalMeta bool `yaml:"private_chat_portal_meta"`
  77. BridgeNotices bool `yaml:"bridge_notices"`
  78. ResendBridgeInfo bool `yaml:"resend_bridge_info"`
  79. MuteBridging bool `yaml:"mute_bridging"`
  80. ArchiveTag string `yaml:"archive_tag"`
  81. PinnedTag string `yaml:"pinned_tag"`
  82. TagOnlyOnCreate bool `yaml:"tag_only_on_create"`
  83. MarkReadOnlyOnCreate bool `yaml:"mark_read_only_on_create"`
  84. EnableStatusBroadcast bool `yaml:"enable_status_broadcast"`
  85. MuteStatusBroadcast bool `yaml:"mute_status_broadcast"`
  86. StatusBroadcastTag string `yaml:"status_broadcast_tag"`
  87. WhatsappThumbnail bool `yaml:"whatsapp_thumbnail"`
  88. AllowUserInvite bool `yaml:"allow_user_invite"`
  89. FederateRooms bool `yaml:"federate_rooms"`
  90. URLPreviews bool `yaml:"url_previews"`
  91. CaptionInMessage bool `yaml:"caption_in_message"`
  92. DisableStatusBroadcastSend bool `yaml:"disable_status_broadcast_send"`
  93. DisappearingMessagesInGroups bool `yaml:"disappearing_messages_in_groups"`
  94. DisableBridgeAlerts bool `yaml:"disable_bridge_alerts"`
  95. CommandPrefix string `yaml:"command_prefix"`
  96. ManagementRoomText bridgeconfig.ManagementRoomTexts `yaml:"management_room_text"`
  97. Encryption bridgeconfig.EncryptionConfig `yaml:"encryption"`
  98. Provisioning struct {
  99. Prefix string `yaml:"prefix"`
  100. SharedSecret string `yaml:"shared_secret"`
  101. } `yaml:"provisioning"`
  102. Permissions bridgeconfig.PermissionConfig `yaml:"permissions"`
  103. Relay RelaybotConfig `yaml:"relay"`
  104. ParsedUsernameTemplate *template.Template `yaml:"-"`
  105. displaynameTemplate *template.Template `yaml:"-"`
  106. }
  107. func (bc BridgeConfig) GetEncryptionConfig() bridgeconfig.EncryptionConfig {
  108. return bc.Encryption
  109. }
  110. func (bc BridgeConfig) EnableMessageStatusEvents() bool {
  111. return bc.MessageStatusEvents
  112. }
  113. func (bc BridgeConfig) EnableMessageErrorNotices() bool {
  114. return bc.MessageErrorNotices
  115. }
  116. func (bc BridgeConfig) GetCommandPrefix() string {
  117. return bc.CommandPrefix
  118. }
  119. func (bc BridgeConfig) GetManagementRoomTexts() bridgeconfig.ManagementRoomTexts {
  120. return bc.ManagementRoomText
  121. }
  122. func boolToInt(val bool) int {
  123. if val {
  124. return 1
  125. }
  126. return 0
  127. }
  128. func (bc BridgeConfig) Validate() error {
  129. _, hasWildcard := bc.Permissions["*"]
  130. _, hasExampleDomain := bc.Permissions["example.com"]
  131. _, hasExampleUser := bc.Permissions["@admin:example.com"]
  132. exampleLen := boolToInt(hasWildcard) + boolToInt(hasExampleUser) + boolToInt(hasExampleDomain)
  133. if len(bc.Permissions) <= exampleLen {
  134. return errors.New("bridge.permissions not configured")
  135. }
  136. return nil
  137. }
  138. type umBridgeConfig BridgeConfig
  139. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  140. err := unmarshal((*umBridgeConfig)(bc))
  141. if err != nil {
  142. return err
  143. }
  144. bc.ParsedUsernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  145. if err != nil {
  146. return err
  147. } else if !strings.Contains(bc.FormatUsername("1234567890"), "1234567890") {
  148. return fmt.Errorf("username template is missing user ID placeholder")
  149. }
  150. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  151. if err != nil {
  152. return err
  153. }
  154. return nil
  155. }
  156. type UsernameTemplateArgs struct {
  157. UserID id.UserID
  158. }
  159. type legacyContactInfo struct {
  160. types.ContactInfo
  161. Phone string
  162. Notify string
  163. VName string
  164. Name string
  165. Short string
  166. JID string
  167. }
  168. const (
  169. NameQualityPush = 3
  170. NameQualityContact = 2
  171. NameQualityPhone = 1
  172. )
  173. func (bc BridgeConfig) FormatDisplayname(jid types.JID, contact types.ContactInfo) (string, int8) {
  174. var buf strings.Builder
  175. _ = bc.displaynameTemplate.Execute(&buf, legacyContactInfo{
  176. ContactInfo: contact,
  177. Notify: contact.PushName,
  178. VName: contact.BusinessName,
  179. Name: contact.FullName,
  180. Short: contact.FirstName,
  181. Phone: "+" + jid.User,
  182. JID: "+" + jid.User,
  183. })
  184. var quality int8
  185. switch {
  186. case len(contact.PushName) > 0 || len(contact.BusinessName) > 0:
  187. quality = NameQualityPush
  188. case len(contact.FullName) > 0 || len(contact.FirstName) > 0:
  189. quality = NameQualityContact
  190. default:
  191. quality = NameQualityPhone
  192. }
  193. return buf.String(), quality
  194. }
  195. func (bc BridgeConfig) FormatUsername(username string) string {
  196. var buf strings.Builder
  197. _ = bc.ParsedUsernameTemplate.Execute(&buf, username)
  198. return buf.String()
  199. }
  200. type RelaybotConfig struct {
  201. Enabled bool `yaml:"enabled"`
  202. AdminOnly bool `yaml:"admin_only"`
  203. MessageFormats map[event.MessageType]string `yaml:"message_formats"`
  204. messageTemplates *template.Template `yaml:"-"`
  205. }
  206. type umRelaybotConfig RelaybotConfig
  207. func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  208. err := unmarshal((*umRelaybotConfig)(rc))
  209. if err != nil {
  210. return err
  211. }
  212. rc.messageTemplates = template.New("messageTemplates")
  213. for key, format := range rc.MessageFormats {
  214. _, err := rc.messageTemplates.New(string(key)).Parse(format)
  215. if err != nil {
  216. return err
  217. }
  218. }
  219. return nil
  220. }
  221. type Sender struct {
  222. UserID string
  223. event.MemberEventContent
  224. }
  225. type formatData struct {
  226. Sender Sender
  227. Message string
  228. Content *event.MessageEventContent
  229. }
  230. func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member event.MemberEventContent) (string, error) {
  231. if len(member.Displayname) == 0 {
  232. member.Displayname = sender.String()
  233. }
  234. member.Displayname = template.HTMLEscapeString(member.Displayname)
  235. var output strings.Builder
  236. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  237. Sender: Sender{
  238. UserID: template.HTMLEscapeString(sender.String()),
  239. MemberEventContent: member,
  240. },
  241. Content: content,
  242. Message: content.FormattedBody,
  243. })
  244. return output.String(), err
  245. }