bridge.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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) GetCommandPrefix() string {
  111. return bc.CommandPrefix
  112. }
  113. func (bc BridgeConfig) GetManagementRoomTexts() bridgeconfig.ManagementRoomTexts {
  114. return bc.ManagementRoomText
  115. }
  116. func boolToInt(val bool) int {
  117. if val {
  118. return 1
  119. }
  120. return 0
  121. }
  122. func (bc BridgeConfig) Validate() error {
  123. _, hasWildcard := bc.Permissions["*"]
  124. _, hasExampleDomain := bc.Permissions["example.com"]
  125. _, hasExampleUser := bc.Permissions["@admin:example.com"]
  126. exampleLen := boolToInt(hasWildcard) + boolToInt(hasExampleUser) + boolToInt(hasExampleDomain)
  127. if len(bc.Permissions) <= exampleLen {
  128. return errors.New("bridge.permissions not configured")
  129. }
  130. return nil
  131. }
  132. type umBridgeConfig BridgeConfig
  133. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  134. err := unmarshal((*umBridgeConfig)(bc))
  135. if err != nil {
  136. return err
  137. }
  138. bc.ParsedUsernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  139. if err != nil {
  140. return err
  141. } else if !strings.Contains(bc.FormatUsername("1234567890"), "1234567890") {
  142. return fmt.Errorf("username template is missing user ID placeholder")
  143. }
  144. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  145. if err != nil {
  146. return err
  147. }
  148. return nil
  149. }
  150. type UsernameTemplateArgs struct {
  151. UserID id.UserID
  152. }
  153. type legacyContactInfo struct {
  154. types.ContactInfo
  155. Phone string
  156. Notify string
  157. VName string
  158. Name string
  159. Short string
  160. JID string
  161. }
  162. const (
  163. NameQualityPush = 3
  164. NameQualityContact = 2
  165. NameQualityPhone = 1
  166. )
  167. func (bc BridgeConfig) FormatDisplayname(jid types.JID, contact types.ContactInfo) (string, int8) {
  168. var buf strings.Builder
  169. _ = bc.displaynameTemplate.Execute(&buf, legacyContactInfo{
  170. ContactInfo: contact,
  171. Notify: contact.PushName,
  172. VName: contact.BusinessName,
  173. Name: contact.FullName,
  174. Short: contact.FirstName,
  175. Phone: "+" + jid.User,
  176. JID: "+" + jid.User,
  177. })
  178. var quality int8
  179. switch {
  180. case len(contact.PushName) > 0 || len(contact.BusinessName) > 0:
  181. quality = NameQualityPush
  182. case len(contact.FullName) > 0 || len(contact.FirstName) > 0:
  183. quality = NameQualityContact
  184. default:
  185. quality = NameQualityPhone
  186. }
  187. return buf.String(), quality
  188. }
  189. func (bc BridgeConfig) FormatUsername(username string) string {
  190. var buf strings.Builder
  191. _ = bc.ParsedUsernameTemplate.Execute(&buf, username)
  192. return buf.String()
  193. }
  194. type RelaybotConfig struct {
  195. Enabled bool `yaml:"enabled"`
  196. AdminOnly bool `yaml:"admin_only"`
  197. MessageFormats map[event.MessageType]string `yaml:"message_formats"`
  198. messageTemplates *template.Template `yaml:"-"`
  199. }
  200. type umRelaybotConfig RelaybotConfig
  201. func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  202. err := unmarshal((*umRelaybotConfig)(rc))
  203. if err != nil {
  204. return err
  205. }
  206. rc.messageTemplates = template.New("messageTemplates")
  207. for key, format := range rc.MessageFormats {
  208. _, err := rc.messageTemplates.New(string(key)).Parse(format)
  209. if err != nil {
  210. return err
  211. }
  212. }
  213. return nil
  214. }
  215. type Sender struct {
  216. UserID string
  217. event.MemberEventContent
  218. }
  219. type formatData struct {
  220. Sender Sender
  221. Message string
  222. Content *event.MessageEventContent
  223. }
  224. func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member event.MemberEventContent) (string, error) {
  225. if len(member.Displayname) == 0 {
  226. member.Displayname = sender.String()
  227. }
  228. member.Displayname = template.HTMLEscapeString(member.Displayname)
  229. var output strings.Builder
  230. err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
  231. Sender: Sender{
  232. UserID: template.HTMLEscapeString(sender.String()),
  233. MemberEventContent: member,
  234. },
  235. Content: content,
  236. Message: content.FormattedBody,
  237. })
  238. return output.String(), err
  239. }