bridge.go 10 KB

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