bridge.go 9.9 KB

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