bridge.go 8.8 KB

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