bridge.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // mautrix-discord - A Matrix-Discord puppeting bridge.
  2. // Copyright (C) 2022 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. "github.com/bwmarrin/discordgo"
  23. "maunium.net/go/mautrix/bridge/bridgeconfig"
  24. "maunium.net/go/mautrix/id"
  25. )
  26. type BridgeConfig struct {
  27. UsernameTemplate string `yaml:"username_template"`
  28. DisplaynameTemplate string `yaml:"displayname_template"`
  29. ChannelNameTemplate string `yaml:"channel_name_template"`
  30. GuildNameTemplate string `yaml:"guild_name_template"`
  31. PrivateChatPortalMeta string `yaml:"private_chat_portal_meta"`
  32. PrivateChannelCreateLimit int `yaml:"startup_private_channel_create_limit"`
  33. PortalMessageBuffer int `yaml:"portal_message_buffer"`
  34. DeliveryReceipts bool `yaml:"delivery_receipts"`
  35. MessageStatusEvents bool `yaml:"message_status_events"`
  36. MessageErrorNotices bool `yaml:"message_error_notices"`
  37. RestrictedRooms bool `yaml:"restricted_rooms"`
  38. AutojoinThreadOnOpen bool `yaml:"autojoin_thread_on_open"`
  39. EmbedFieldsAsTables bool `yaml:"embed_fields_as_tables"`
  40. MuteChannelsOnCreate bool `yaml:"mute_channels_on_create"`
  41. SyncDirectChatList bool `yaml:"sync_direct_chat_list"`
  42. ResendBridgeInfo bool `yaml:"resend_bridge_info"`
  43. CustomEmojiReactions bool `yaml:"custom_emoji_reactions"`
  44. DeletePortalOnChannelDelete bool `yaml:"delete_portal_on_channel_delete"`
  45. DeleteGuildOnLeave bool `yaml:"delete_guild_on_leave"`
  46. FederateRooms bool `yaml:"federate_rooms"`
  47. PrefixWebhookMessages bool `yaml:"prefix_webhook_messages"`
  48. EnableWebhookAvatars bool `yaml:"enable_webhook_avatars"`
  49. UseDiscordCDNUpload bool `yaml:"use_discord_cdn_upload"`
  50. CacheMedia string `yaml:"cache_media"`
  51. MediaPatterns MediaPatterns `yaml:"media_patterns"`
  52. AnimatedSticker struct {
  53. Target string `yaml:"target"`
  54. Args struct {
  55. Width int `yaml:"width"`
  56. Height int `yaml:"height"`
  57. FPS int `yaml:"fps"`
  58. } `yaml:"args"`
  59. } `yaml:"animated_sticker"`
  60. DoublePuppetConfig bridgeconfig.DoublePuppetConfig `yaml:",inline"`
  61. CommandPrefix string `yaml:"command_prefix"`
  62. ManagementRoomText bridgeconfig.ManagementRoomTexts `yaml:"management_room_text"`
  63. Backfill struct {
  64. Limits struct {
  65. Initial BackfillLimitPart `yaml:"initial"`
  66. Missed BackfillLimitPart `yaml:"missed"`
  67. } `yaml:"forward_limits"`
  68. MaxGuildMembers int `yaml:"max_guild_members"`
  69. } `yaml:"backfill"`
  70. Encryption bridgeconfig.EncryptionConfig `yaml:"encryption"`
  71. Provisioning struct {
  72. Prefix string `yaml:"prefix"`
  73. SharedSecret string `yaml:"shared_secret"`
  74. } `yaml:"provisioning"`
  75. Permissions bridgeconfig.PermissionConfig `yaml:"permissions"`
  76. usernameTemplate *template.Template `yaml:"-"`
  77. displaynameTemplate *template.Template `yaml:"-"`
  78. channelNameTemplate *template.Template `yaml:"-"`
  79. guildNameTemplate *template.Template `yaml:"-"`
  80. }
  81. type MediaPatterns struct {
  82. Enabled bool `yaml:"enabled"`
  83. TplAttachments string `yaml:"attachments"`
  84. TplEmojis string `yaml:"emojis"`
  85. TplStickers string `yaml:"stickers"`
  86. TplAvatars string `yaml:"avatars"`
  87. attachments *template.Template `yaml:"-"`
  88. emojis *template.Template `yaml:"-"`
  89. stickers *template.Template `yaml:"-"`
  90. avatars *template.Template `yaml:"-"`
  91. }
  92. type umMediaPatterns MediaPatterns
  93. func (mp *MediaPatterns) UnmarshalYAML(unmarshal func(interface{}) error) error {
  94. err := unmarshal((*umMediaPatterns)(mp))
  95. if err != nil {
  96. return err
  97. }
  98. tpl := template.New("media_patterns")
  99. pairs := []struct {
  100. ptr **template.Template
  101. name string
  102. template string
  103. }{
  104. {&mp.attachments, "attachments", mp.TplAttachments},
  105. {&mp.emojis, "emojis", mp.TplEmojis},
  106. {&mp.stickers, "stickers", mp.TplStickers},
  107. {&mp.avatars, "avatars", mp.TplAvatars},
  108. }
  109. for _, pair := range pairs {
  110. if pair.template == "" {
  111. continue
  112. }
  113. *pair.ptr, err = tpl.New(pair.name).Parse(pair.template)
  114. if err != nil {
  115. return err
  116. }
  117. }
  118. return nil
  119. }
  120. type attachmentParams struct {
  121. ChannelID string
  122. AttachmentID string
  123. FileName string
  124. }
  125. type emojiStickerParams struct {
  126. ID string
  127. Ext string
  128. }
  129. type avatarParams struct {
  130. UserID string
  131. AvatarID string
  132. Ext string
  133. }
  134. func (mp *MediaPatterns) execute(tpl *template.Template, params any) id.ContentURI {
  135. if tpl == nil || !mp.Enabled {
  136. return id.ContentURI{}
  137. }
  138. var out strings.Builder
  139. err := tpl.Execute(&out, params)
  140. if err != nil {
  141. panic(err)
  142. }
  143. uri, err := id.ParseContentURI(out.String())
  144. if err != nil {
  145. panic(err)
  146. }
  147. return uri
  148. }
  149. func (mp *MediaPatterns) Attachment(channelID, attachmentID, filename string) id.ContentURI {
  150. return mp.execute(mp.attachments, attachmentParams{
  151. ChannelID: channelID,
  152. AttachmentID: attachmentID,
  153. FileName: filename,
  154. })
  155. }
  156. func (mp *MediaPatterns) Emoji(emojiID, ext string) id.ContentURI {
  157. return mp.execute(mp.emojis, emojiStickerParams{
  158. ID: emojiID,
  159. Ext: ext,
  160. })
  161. }
  162. func (mp *MediaPatterns) Sticker(stickerID, ext string) id.ContentURI {
  163. return mp.execute(mp.stickers, emojiStickerParams{
  164. ID: stickerID,
  165. Ext: ext,
  166. })
  167. }
  168. func (mp *MediaPatterns) Avatar(userID, avatarID, ext string) id.ContentURI {
  169. return mp.execute(mp.avatars, avatarParams{
  170. UserID: userID,
  171. AvatarID: avatarID,
  172. Ext: ext,
  173. })
  174. }
  175. type BackfillLimitPart struct {
  176. DM int `yaml:"dm"`
  177. Channel int `yaml:"channel"`
  178. Thread int `yaml:"thread"`
  179. }
  180. func (bc *BridgeConfig) GetResendBridgeInfo() bool {
  181. return bc.ResendBridgeInfo
  182. }
  183. func (bc *BridgeConfig) EnableMessageStatusEvents() bool {
  184. return bc.MessageStatusEvents
  185. }
  186. func (bc *BridgeConfig) EnableMessageErrorNotices() bool {
  187. return bc.MessageErrorNotices
  188. }
  189. func boolToInt(val bool) int {
  190. if val {
  191. return 1
  192. }
  193. return 0
  194. }
  195. func (bc *BridgeConfig) Validate() error {
  196. _, hasWildcard := bc.Permissions["*"]
  197. _, hasExampleDomain := bc.Permissions["example.com"]
  198. _, hasExampleUser := bc.Permissions["@admin:example.com"]
  199. exampleLen := boolToInt(hasWildcard) + boolToInt(hasExampleUser) + boolToInt(hasExampleDomain)
  200. if len(bc.Permissions) <= exampleLen {
  201. return errors.New("bridge.permissions not configured")
  202. }
  203. return nil
  204. }
  205. type umBridgeConfig BridgeConfig
  206. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  207. err := unmarshal((*umBridgeConfig)(bc))
  208. if err != nil {
  209. return err
  210. }
  211. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  212. if err != nil {
  213. return err
  214. } else if !strings.Contains(bc.FormatUsername("1234567890"), "1234567890") {
  215. return fmt.Errorf("username template is missing user ID placeholder")
  216. }
  217. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  218. if err != nil {
  219. return err
  220. }
  221. bc.channelNameTemplate, err = template.New("channel_name").Parse(bc.ChannelNameTemplate)
  222. if err != nil {
  223. return err
  224. }
  225. bc.guildNameTemplate, err = template.New("guild_name").Parse(bc.GuildNameTemplate)
  226. if err != nil {
  227. return err
  228. }
  229. return nil
  230. }
  231. var _ bridgeconfig.BridgeConfig = (*BridgeConfig)(nil)
  232. func (bc BridgeConfig) GetDoublePuppetConfig() bridgeconfig.DoublePuppetConfig {
  233. return bc.DoublePuppetConfig
  234. }
  235. func (bc BridgeConfig) GetEncryptionConfig() bridgeconfig.EncryptionConfig {
  236. return bc.Encryption
  237. }
  238. func (bc BridgeConfig) GetCommandPrefix() string {
  239. return bc.CommandPrefix
  240. }
  241. func (bc BridgeConfig) GetManagementRoomTexts() bridgeconfig.ManagementRoomTexts {
  242. return bc.ManagementRoomText
  243. }
  244. func (bc BridgeConfig) FormatUsername(userID string) string {
  245. var buffer strings.Builder
  246. _ = bc.usernameTemplate.Execute(&buffer, userID)
  247. return buffer.String()
  248. }
  249. type DisplaynameParams struct {
  250. *discordgo.User
  251. Webhook bool
  252. Application bool
  253. }
  254. func (bc BridgeConfig) FormatDisplayname(user *discordgo.User, webhook, application bool) string {
  255. var buffer strings.Builder
  256. _ = bc.displaynameTemplate.Execute(&buffer, &DisplaynameParams{
  257. User: user,
  258. Webhook: webhook,
  259. Application: application,
  260. })
  261. return buffer.String()
  262. }
  263. type ChannelNameParams struct {
  264. Name string
  265. ParentName string
  266. GuildName string
  267. NSFW bool
  268. Type discordgo.ChannelType
  269. }
  270. func (bc BridgeConfig) FormatChannelName(params ChannelNameParams) string {
  271. var buffer strings.Builder
  272. _ = bc.channelNameTemplate.Execute(&buffer, params)
  273. return buffer.String()
  274. }
  275. type GuildNameParams struct {
  276. Name string
  277. }
  278. func (bc BridgeConfig) FormatGuildName(params GuildNameParams) string {
  279. var buffer strings.Builder
  280. _ = bc.guildNameTemplate.Execute(&buffer, params)
  281. return buffer.String()
  282. }