bridge.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. CacheMedia string `yaml:"cache_media"`
  48. MediaPatterns MediaPatterns `yaml:"media_patterns"`
  49. AnimatedSticker struct {
  50. Target string `yaml:"target"`
  51. Args struct {
  52. Width int `yaml:"width"`
  53. Height int `yaml:"height"`
  54. FPS int `yaml:"fps"`
  55. } `yaml:"args"`
  56. } `yaml:"animated_sticker"`
  57. DoublePuppetServerMap map[string]string `yaml:"double_puppet_server_map"`
  58. DoublePuppetAllowDiscovery bool `yaml:"double_puppet_allow_discovery"`
  59. LoginSharedSecretMap map[string]string `yaml:"login_shared_secret_map"`
  60. CommandPrefix string `yaml:"command_prefix"`
  61. ManagementRoomText bridgeconfig.ManagementRoomTexts `yaml:"management_room_text"`
  62. Backfill struct {
  63. Limits struct {
  64. Initial BackfillLimitPart `yaml:"initial"`
  65. Missed BackfillLimitPart `yaml:"missed"`
  66. } `yaml:"forward_limits"`
  67. MaxGuildMembers int `yaml:"max_guild_members"`
  68. } `yaml:"backfill"`
  69. Encryption bridgeconfig.EncryptionConfig `yaml:"encryption"`
  70. Provisioning struct {
  71. Prefix string `yaml:"prefix"`
  72. SharedSecret string `yaml:"shared_secret"`
  73. } `yaml:"provisioning"`
  74. Permissions bridgeconfig.PermissionConfig `yaml:"permissions"`
  75. usernameTemplate *template.Template `yaml:"-"`
  76. displaynameTemplate *template.Template `yaml:"-"`
  77. channelNameTemplate *template.Template `yaml:"-"`
  78. guildNameTemplate *template.Template `yaml:"-"`
  79. }
  80. type MediaPatterns struct {
  81. Enabled bool `yaml:"enabled"`
  82. TplAttachments string `yaml:"attachments"`
  83. TplEmojis string `yaml:"emojis"`
  84. TplStickers string `yaml:"stickers"`
  85. TplAvatars string `yaml:"avatars"`
  86. attachments *template.Template `yaml:"-"`
  87. emojis *template.Template `yaml:"-"`
  88. stickers *template.Template `yaml:"-"`
  89. avatars *template.Template `yaml:"-"`
  90. }
  91. type umMediaPatterns MediaPatterns
  92. func (mp *MediaPatterns) UnmarshalYAML(unmarshal func(interface{}) error) error {
  93. err := unmarshal((*umMediaPatterns)(mp))
  94. if err != nil {
  95. return err
  96. }
  97. tpl := template.New("media_patterns")
  98. pairs := []struct {
  99. ptr **template.Template
  100. name string
  101. template string
  102. }{
  103. {&mp.attachments, "attachments", mp.TplAttachments},
  104. {&mp.emojis, "emojis", mp.TplEmojis},
  105. {&mp.stickers, "stickers", mp.TplStickers},
  106. {&mp.avatars, "avatars", mp.TplAvatars},
  107. }
  108. for _, pair := range pairs {
  109. if pair.template == "" {
  110. continue
  111. }
  112. *pair.ptr, err = tpl.New(pair.name).Parse(pair.template)
  113. if err != nil {
  114. return err
  115. }
  116. }
  117. return nil
  118. }
  119. type attachmentParams struct {
  120. ChannelID string
  121. AttachmentID string
  122. FileName string
  123. }
  124. type emojiStickerParams struct {
  125. ID string
  126. Ext string
  127. }
  128. type avatarParams struct {
  129. UserID string
  130. AvatarID string
  131. Ext string
  132. }
  133. func (mp *MediaPatterns) execute(tpl *template.Template, params any) id.ContentURI {
  134. if tpl == nil || !mp.Enabled {
  135. return id.ContentURI{}
  136. }
  137. var out strings.Builder
  138. err := tpl.Execute(&out, params)
  139. if err != nil {
  140. panic(err)
  141. }
  142. uri, err := id.ParseContentURI(out.String())
  143. if err != nil {
  144. panic(err)
  145. }
  146. return uri
  147. }
  148. func (mp *MediaPatterns) Attachment(channelID, attachmentID, filename string) id.ContentURI {
  149. return mp.execute(mp.attachments, attachmentParams{
  150. ChannelID: channelID,
  151. AttachmentID: attachmentID,
  152. FileName: filename,
  153. })
  154. }
  155. func (mp *MediaPatterns) Emoji(emojiID, ext string) id.ContentURI {
  156. return mp.execute(mp.emojis, emojiStickerParams{
  157. ID: emojiID,
  158. Ext: ext,
  159. })
  160. }
  161. func (mp *MediaPatterns) Sticker(stickerID, ext string) id.ContentURI {
  162. return mp.execute(mp.stickers, emojiStickerParams{
  163. ID: stickerID,
  164. Ext: ext,
  165. })
  166. }
  167. func (mp *MediaPatterns) Avatar(userID, avatarID, ext string) id.ContentURI {
  168. return mp.execute(mp.avatars, avatarParams{
  169. UserID: userID,
  170. AvatarID: avatarID,
  171. Ext: ext,
  172. })
  173. }
  174. type BackfillLimitPart struct {
  175. DM int `yaml:"dm"`
  176. Channel int `yaml:"channel"`
  177. }
  178. func (bc *BridgeConfig) GetResendBridgeInfo() bool {
  179. return bc.ResendBridgeInfo
  180. }
  181. func (bc *BridgeConfig) EnableMessageStatusEvents() bool {
  182. return bc.MessageStatusEvents
  183. }
  184. func (bc *BridgeConfig) EnableMessageErrorNotices() bool {
  185. return bc.MessageErrorNotices
  186. }
  187. func boolToInt(val bool) int {
  188. if val {
  189. return 1
  190. }
  191. return 0
  192. }
  193. func (bc *BridgeConfig) Validate() error {
  194. _, hasWildcard := bc.Permissions["*"]
  195. _, hasExampleDomain := bc.Permissions["example.com"]
  196. _, hasExampleUser := bc.Permissions["@admin:example.com"]
  197. exampleLen := boolToInt(hasWildcard) + boolToInt(hasExampleUser) + boolToInt(hasExampleDomain)
  198. if len(bc.Permissions) <= exampleLen {
  199. return errors.New("bridge.permissions not configured")
  200. }
  201. return nil
  202. }
  203. type umBridgeConfig BridgeConfig
  204. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  205. err := unmarshal((*umBridgeConfig)(bc))
  206. if err != nil {
  207. return err
  208. }
  209. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  210. if err != nil {
  211. return err
  212. } else if !strings.Contains(bc.FormatUsername("1234567890"), "1234567890") {
  213. return fmt.Errorf("username template is missing user ID placeholder")
  214. }
  215. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  216. if err != nil {
  217. return err
  218. }
  219. bc.channelNameTemplate, err = template.New("channel_name").Parse(bc.ChannelNameTemplate)
  220. if err != nil {
  221. return err
  222. }
  223. bc.guildNameTemplate, err = template.New("guild_name").Parse(bc.GuildNameTemplate)
  224. if err != nil {
  225. return err
  226. }
  227. return nil
  228. }
  229. var _ bridgeconfig.BridgeConfig = (*BridgeConfig)(nil)
  230. func (bc BridgeConfig) GetEncryptionConfig() bridgeconfig.EncryptionConfig {
  231. return bc.Encryption
  232. }
  233. func (bc BridgeConfig) GetCommandPrefix() string {
  234. return bc.CommandPrefix
  235. }
  236. func (bc BridgeConfig) GetManagementRoomTexts() bridgeconfig.ManagementRoomTexts {
  237. return bc.ManagementRoomText
  238. }
  239. func (bc BridgeConfig) FormatUsername(userID string) string {
  240. var buffer strings.Builder
  241. _ = bc.usernameTemplate.Execute(&buffer, userID)
  242. return buffer.String()
  243. }
  244. func (bc BridgeConfig) FormatDisplayname(user *discordgo.User) string {
  245. var buffer strings.Builder
  246. _ = bc.displaynameTemplate.Execute(&buffer, user)
  247. return buffer.String()
  248. }
  249. type ChannelNameParams struct {
  250. Name string
  251. ParentName string
  252. GuildName string
  253. NSFW bool
  254. Type discordgo.ChannelType
  255. }
  256. func (bc BridgeConfig) FormatChannelName(params ChannelNameParams) string {
  257. var buffer strings.Builder
  258. _ = bc.channelNameTemplate.Execute(&buffer, params)
  259. return buffer.String()
  260. }
  261. type GuildNameParams struct {
  262. Name string
  263. }
  264. func (bc BridgeConfig) FormatGuildName(params GuildNameParams) string {
  265. var buffer strings.Builder
  266. _ = bc.guildNameTemplate.Execute(&buffer, params)
  267. return buffer.String()
  268. }