portal.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "time"
  9. "maunium.net/go/mautrix/util/variationselector"
  10. "github.com/bwmarrin/discordgo"
  11. log "maunium.net/go/maulogger/v2"
  12. "maunium.net/go/mautrix"
  13. "maunium.net/go/mautrix/appservice"
  14. "maunium.net/go/mautrix/bridge"
  15. "maunium.net/go/mautrix/bridge/bridgeconfig"
  16. "maunium.net/go/mautrix/event"
  17. "maunium.net/go/mautrix/id"
  18. "go.mau.fi/mautrix-discord/database"
  19. )
  20. type portalDiscordMessage struct {
  21. msg interface{}
  22. user *User
  23. thread *Thread
  24. }
  25. type portalMatrixMessage struct {
  26. evt *event.Event
  27. user *User
  28. }
  29. type Portal struct {
  30. *database.Portal
  31. Parent *Portal
  32. Guild *Guild
  33. bridge *DiscordBridge
  34. log log.Logger
  35. roomCreateLock sync.Mutex
  36. encryptLock sync.Mutex
  37. discordMessages chan portalDiscordMessage
  38. matrixMessages chan portalMatrixMessage
  39. }
  40. func (portal *Portal) IsEncrypted() bool {
  41. return portal.Encrypted
  42. }
  43. func (portal *Portal) MarkEncrypted() {
  44. portal.Encrypted = true
  45. portal.Update()
  46. }
  47. func (portal *Portal) ReceiveMatrixEvent(user bridge.User, evt *event.Event) {
  48. if user.GetPermissionLevel() >= bridgeconfig.PermissionLevelUser /*|| portal.HasRelaybot()*/ {
  49. portal.matrixMessages <- portalMatrixMessage{user: user.(*User), evt: evt}
  50. }
  51. }
  52. var _ bridge.Portal = (*Portal)(nil)
  53. var (
  54. portalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  55. )
  56. func (br *DiscordBridge) loadPortal(dbPortal *database.Portal, key *database.PortalKey, chanType discordgo.ChannelType) *Portal {
  57. if dbPortal == nil {
  58. if key == nil || chanType < 0 {
  59. return nil
  60. }
  61. dbPortal = br.DB.Portal.New()
  62. dbPortal.Key = *key
  63. dbPortal.Type = chanType
  64. dbPortal.Insert()
  65. }
  66. portal := br.NewPortal(dbPortal)
  67. br.portalsByID[portal.Key] = portal
  68. if portal.MXID != "" {
  69. br.portalsByMXID[portal.MXID] = portal
  70. }
  71. if portal.GuildID != "" {
  72. portal.Guild = portal.bridge.GetGuildByID(portal.GuildID, true)
  73. }
  74. if portal.ParentID != "" {
  75. parentKey := database.NewPortalKey(portal.ParentID, "")
  76. var ok bool
  77. portal.Parent, ok = br.portalsByID[parentKey]
  78. if !ok {
  79. portal.Parent = br.loadPortal(br.DB.Portal.GetByID(parentKey), nil, -1)
  80. }
  81. }
  82. return portal
  83. }
  84. func (br *DiscordBridge) GetPortalByMXID(mxid id.RoomID) *Portal {
  85. br.portalsLock.Lock()
  86. defer br.portalsLock.Unlock()
  87. portal, ok := br.portalsByMXID[mxid]
  88. if !ok {
  89. return br.loadPortal(br.DB.Portal.GetByMXID(mxid), nil, -1)
  90. }
  91. return portal
  92. }
  93. func (user *User) GetPortalByMeta(meta *discordgo.Channel) *Portal {
  94. return user.GetPortalByID(meta.ID, meta.Type)
  95. }
  96. func (user *User) GetExistingPortalByID(id string) *Portal {
  97. return user.bridge.GetExistingPortalByID(database.NewPortalKey(id, user.DiscordID))
  98. }
  99. func (user *User) GetPortalByID(id string, chanType discordgo.ChannelType) *Portal {
  100. return user.bridge.GetPortalByID(database.NewPortalKey(id, user.DiscordID), chanType)
  101. }
  102. func (br *DiscordBridge) GetExistingPortalByID(key database.PortalKey) *Portal {
  103. br.portalsLock.Lock()
  104. defer br.portalsLock.Unlock()
  105. portal, ok := br.portalsByID[key]
  106. if !ok {
  107. portal, ok = br.portalsByID[database.NewPortalKey(key.ChannelID, "")]
  108. if !ok {
  109. return br.loadPortal(br.DB.Portal.GetByID(key), nil, -1)
  110. }
  111. }
  112. return portal
  113. }
  114. func (br *DiscordBridge) GetPortalByID(key database.PortalKey, chanType discordgo.ChannelType) *Portal {
  115. br.portalsLock.Lock()
  116. defer br.portalsLock.Unlock()
  117. if chanType != discordgo.ChannelTypeDM {
  118. key.Receiver = ""
  119. }
  120. portal, ok := br.portalsByID[key]
  121. if !ok {
  122. return br.loadPortal(br.DB.Portal.GetByID(key), &key, chanType)
  123. }
  124. return portal
  125. }
  126. func (br *DiscordBridge) GetAllPortals() []*Portal {
  127. return br.dbPortalsToPortals(br.DB.Portal.GetAll())
  128. }
  129. func (br *DiscordBridge) GetDMPortalsWith(otherUserID string) []*Portal {
  130. return br.dbPortalsToPortals(br.DB.Portal.FindPrivateChatsWith(otherUserID))
  131. }
  132. func (br *DiscordBridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
  133. br.portalsLock.Lock()
  134. defer br.portalsLock.Unlock()
  135. output := make([]*Portal, len(dbPortals))
  136. for index, dbPortal := range dbPortals {
  137. if dbPortal == nil {
  138. continue
  139. }
  140. portal, ok := br.portalsByID[dbPortal.Key]
  141. if !ok {
  142. portal = br.loadPortal(dbPortal, nil, -1)
  143. }
  144. output[index] = portal
  145. }
  146. return output
  147. }
  148. func (br *DiscordBridge) NewPortal(dbPortal *database.Portal) *Portal {
  149. portal := &Portal{
  150. Portal: dbPortal,
  151. bridge: br,
  152. log: br.Log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
  153. discordMessages: make(chan portalDiscordMessage, br.Config.Bridge.PortalMessageBuffer),
  154. matrixMessages: make(chan portalMatrixMessage, br.Config.Bridge.PortalMessageBuffer),
  155. }
  156. go portal.messageLoop()
  157. return portal
  158. }
  159. func (portal *Portal) messageLoop() {
  160. for {
  161. select {
  162. case msg := <-portal.matrixMessages:
  163. portal.handleMatrixMessages(msg)
  164. case msg := <-portal.discordMessages:
  165. portal.handleDiscordMessages(msg)
  166. }
  167. }
  168. }
  169. func (portal *Portal) IsPrivateChat() bool {
  170. return portal.Type == discordgo.ChannelTypeDM
  171. }
  172. func (portal *Portal) MainIntent() *appservice.IntentAPI {
  173. if portal.IsPrivateChat() && portal.OtherUserID != "" {
  174. return portal.bridge.GetPuppetByID(portal.OtherUserID).DefaultIntent()
  175. }
  176. return portal.bridge.Bot
  177. }
  178. func (portal *Portal) getBridgeInfo() (string, event.BridgeEventContent) {
  179. bridgeInfo := event.BridgeEventContent{
  180. BridgeBot: portal.bridge.Bot.UserID,
  181. Creator: portal.MainIntent().UserID,
  182. Protocol: event.BridgeInfoSection{
  183. ID: "discord",
  184. DisplayName: "Discord",
  185. AvatarURL: portal.bridge.Config.AppService.Bot.ParsedAvatar.CUString(),
  186. ExternalURL: "https://discord.com/",
  187. },
  188. Channel: event.BridgeInfoSection{
  189. ID: portal.Key.ChannelID,
  190. DisplayName: portal.Name,
  191. },
  192. }
  193. var bridgeInfoStateKey string
  194. if portal.GuildID == "" {
  195. bridgeInfoStateKey = fmt.Sprintf("fi.mau.discord://discord/dm/%s", portal.Key.ChannelID)
  196. } else {
  197. bridgeInfo.Network = &event.BridgeInfoSection{
  198. ID: portal.GuildID,
  199. }
  200. if portal.Guild != nil {
  201. bridgeInfo.Network.DisplayName = portal.Guild.Name
  202. bridgeInfo.Network.AvatarURL = portal.Guild.AvatarURL.CUString()
  203. // TODO is it possible to find the URL?
  204. }
  205. bridgeInfoStateKey = fmt.Sprintf("fi.mau.discord://discord/%s/%s", portal.GuildID, portal.Key.ChannelID)
  206. }
  207. return bridgeInfoStateKey, bridgeInfo
  208. }
  209. func (portal *Portal) UpdateBridgeInfo() {
  210. if len(portal.MXID) == 0 {
  211. portal.log.Debugln("Not updating bridge info: no Matrix room created")
  212. return
  213. }
  214. portal.log.Debugln("Updating bridge info...")
  215. stateKey, content := portal.getBridgeInfo()
  216. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateBridge, stateKey, content)
  217. if err != nil {
  218. portal.log.Warnln("Failed to update m.bridge:", err)
  219. }
  220. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  221. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateHalfShotBridge, stateKey, content)
  222. if err != nil {
  223. portal.log.Warnln("Failed to update uk.half-shot.bridge:", err)
  224. }
  225. }
  226. func (portal *Portal) CreateMatrixRoom(user *User, channel *discordgo.Channel) error {
  227. portal.roomCreateLock.Lock()
  228. defer portal.roomCreateLock.Unlock()
  229. if portal.MXID != "" {
  230. return nil
  231. }
  232. portal.log.Infoln("Creating Matrix room for channel")
  233. channel = portal.UpdateInfo(user, channel)
  234. intent := portal.MainIntent()
  235. if err := intent.EnsureRegistered(); err != nil {
  236. return err
  237. }
  238. bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo()
  239. initialState := []*event.Event{{
  240. Type: event.StateBridge,
  241. Content: event.Content{Parsed: bridgeInfo},
  242. StateKey: &bridgeInfoStateKey,
  243. }, {
  244. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  245. Type: event.StateHalfShotBridge,
  246. Content: event.Content{Parsed: bridgeInfo},
  247. StateKey: &bridgeInfoStateKey,
  248. }}
  249. if !portal.AvatarURL.IsEmpty() {
  250. initialState = append(initialState, &event.Event{
  251. Type: event.StateRoomAvatar,
  252. Content: event.Content{Parsed: &event.RoomAvatarEventContent{
  253. URL: portal.AvatarURL,
  254. }},
  255. })
  256. }
  257. creationContent := make(map[string]interface{})
  258. if portal.Type == discordgo.ChannelTypeGuildCategory {
  259. creationContent["type"] = event.RoomTypeSpace
  260. }
  261. if !portal.bridge.Config.Bridge.FederateRooms {
  262. creationContent["m.federate"] = false
  263. }
  264. spaceID := portal.ExpectedSpaceID()
  265. if spaceID != "" {
  266. spaceIDStr := spaceID.String()
  267. initialState = append(initialState, &event.Event{
  268. Type: event.StateSpaceParent,
  269. StateKey: &spaceIDStr,
  270. Content: event.Content{Parsed: &event.SpaceParentEventContent{
  271. Via: []string{portal.bridge.AS.HomeserverDomain},
  272. Canonical: true,
  273. }},
  274. })
  275. }
  276. if portal.Guild != nil && portal.Guild.MXID != "" {
  277. // TODO don't do this for private channels in guilds
  278. initialState = append(initialState, &event.Event{
  279. Type: event.StateJoinRules,
  280. Content: event.Content{Parsed: &event.JoinRulesEventContent{
  281. JoinRule: event.JoinRuleRestricted,
  282. Allow: []event.JoinRuleAllow{{
  283. RoomID: spaceID,
  284. Type: event.JoinRuleAllowRoomMembership,
  285. }},
  286. }},
  287. })
  288. }
  289. // TODO set restricted join rule based on guild
  290. var invite []id.UserID
  291. if portal.bridge.Config.Bridge.Encryption.Default {
  292. initialState = append(initialState, &event.Event{
  293. Type: event.StateEncryption,
  294. Content: event.Content{
  295. Parsed: event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1},
  296. },
  297. })
  298. portal.Encrypted = true
  299. if portal.IsPrivateChat() {
  300. invite = append(invite, portal.bridge.Bot.UserID)
  301. }
  302. }
  303. resp, err := intent.CreateRoom(&mautrix.ReqCreateRoom{
  304. Visibility: "private",
  305. Name: portal.Name,
  306. Topic: portal.Topic,
  307. Invite: invite,
  308. Preset: "private_chat",
  309. IsDirect: portal.IsPrivateChat(),
  310. InitialState: initialState,
  311. CreationContent: creationContent,
  312. })
  313. if err != nil {
  314. portal.log.Warnln("Failed to create room:", err)
  315. return err
  316. }
  317. portal.NameSet = true
  318. portal.TopicSet = true
  319. portal.AvatarSet = !portal.AvatarURL.IsEmpty()
  320. portal.MXID = resp.RoomID
  321. portal.bridge.portalsLock.Lock()
  322. portal.bridge.portalsByMXID[portal.MXID] = portal
  323. portal.bridge.portalsLock.Unlock()
  324. portal.Update()
  325. portal.log.Infoln("Matrix room created:", portal.MXID)
  326. portal.updateSpace()
  327. portal.ensureUserInvited(user)
  328. user.syncChatDoublePuppetDetails(portal, true)
  329. portal.syncParticipants(user, channel.Recipients)
  330. if portal.IsPrivateChat() {
  331. puppet := user.bridge.GetPuppetByID(portal.Key.Receiver)
  332. chats := map[id.UserID][]id.RoomID{puppet.MXID: {portal.MXID}}
  333. user.updateDirectChats(chats)
  334. }
  335. firstEventResp, err := portal.MainIntent().SendMessageEvent(portal.MXID, portalCreationDummyEvent, struct{}{})
  336. if err != nil {
  337. portal.log.Errorln("Failed to send dummy event to mark portal creation:", err)
  338. } else {
  339. portal.FirstEventID = firstEventResp.EventID
  340. portal.Update()
  341. }
  342. return nil
  343. }
  344. func (portal *Portal) handleDiscordMessages(msg portalDiscordMessage) {
  345. if portal.MXID == "" {
  346. _, ok := msg.msg.(*discordgo.MessageCreate)
  347. if !ok {
  348. portal.log.Warnln("Can't create Matrix room from non new message event")
  349. return
  350. }
  351. portal.log.Debugln("Creating Matrix room from incoming message")
  352. if err := portal.CreateMatrixRoom(msg.user, nil); err != nil {
  353. portal.log.Errorln("Failed to create portal room:", err)
  354. return
  355. }
  356. }
  357. switch convertedMsg := msg.msg.(type) {
  358. case *discordgo.MessageCreate:
  359. portal.handleDiscordMessageCreate(msg.user, convertedMsg.Message, msg.thread)
  360. case *discordgo.MessageUpdate:
  361. portal.handleDiscordMessageUpdate(msg.user, convertedMsg.Message)
  362. case *discordgo.MessageDelete:
  363. portal.handleDiscordMessageDelete(msg.user, convertedMsg.Message)
  364. case *discordgo.MessageReactionAdd:
  365. portal.handleDiscordReaction(msg.user, convertedMsg.MessageReaction, true, msg.thread)
  366. case *discordgo.MessageReactionRemove:
  367. portal.handleDiscordReaction(msg.user, convertedMsg.MessageReaction, false, msg.thread)
  368. default:
  369. portal.log.Warnln("unknown message type")
  370. }
  371. }
  372. func (portal *Portal) ensureUserInvited(user *User) bool {
  373. return user.ensureInvited(portal.MainIntent(), portal.MXID, portal.IsPrivateChat())
  374. }
  375. func (portal *Portal) markMessageHandled(discordID string, mxid id.EventID, authorID string, timestamp time.Time, threadID string) *database.Message {
  376. msg := portal.bridge.DB.Message.New()
  377. msg.Channel = portal.Key
  378. msg.DiscordID = discordID
  379. msg.MXID = mxid
  380. msg.SenderID = authorID
  381. msg.Timestamp = timestamp
  382. msg.ThreadID = threadID
  383. msg.Insert()
  384. return msg
  385. }
  386. func (portal *Portal) sendMediaFailedMessage(intent *appservice.IntentAPI, bridgeErr error) {
  387. content := &event.MessageEventContent{
  388. Body: fmt.Sprintf("Failed to bridge media: %v", bridgeErr),
  389. MsgType: event.MsgNotice,
  390. }
  391. _, err := portal.sendMatrixMessage(intent, event.EventMessage, content, nil, 0)
  392. if err != nil {
  393. portal.log.Warnfln("Failed to send media error message to matrix: %v", err)
  394. }
  395. }
  396. func (portal *Portal) handleDiscordAttachment(intent *appservice.IntentAPI, msgID string, attachment *discordgo.MessageAttachment, ts time.Time, threadRelation *event.RelatesTo, threadID string) {
  397. // var captionContent *event.MessageEventContent
  398. // if attachment.Description != "" {
  399. // captionContent = &event.MessageEventContent{
  400. // Body: attachment.Description,
  401. // MsgType: event.MsgNotice,
  402. // }
  403. // }
  404. // portal.Log.Debugfln("captionContent: %#v", captionContent)
  405. content := &event.MessageEventContent{
  406. Body: attachment.Filename,
  407. Info: &event.FileInfo{
  408. Height: attachment.Height,
  409. MimeType: attachment.ContentType,
  410. Width: attachment.Width,
  411. // This gets overwritten later after the file is uploaded to the homeserver
  412. Size: attachment.Size,
  413. },
  414. RelatesTo: threadRelation,
  415. }
  416. switch strings.ToLower(strings.Split(attachment.ContentType, "/")[0]) {
  417. case "audio":
  418. content.MsgType = event.MsgAudio
  419. case "image":
  420. content.MsgType = event.MsgImage
  421. case "video":
  422. content.MsgType = event.MsgVideo
  423. default:
  424. content.MsgType = event.MsgFile
  425. }
  426. data, err := portal.downloadDiscordAttachment(attachment.URL)
  427. if err != nil {
  428. portal.sendMediaFailedMessage(intent, err)
  429. return
  430. }
  431. err = portal.uploadMatrixAttachment(intent, data, content)
  432. if err != nil {
  433. portal.sendMediaFailedMessage(intent, err)
  434. return
  435. }
  436. resp, err := portal.sendMatrixMessage(intent, event.EventMessage, content, nil, ts.UnixMilli())
  437. if err != nil {
  438. portal.log.Warnfln("failed to send media message to matrix: %v", err)
  439. }
  440. dbAttachment := portal.bridge.DB.Attachment.New()
  441. dbAttachment.Channel = portal.Key
  442. dbAttachment.MessageID = msgID
  443. dbAttachment.ID = attachment.ID
  444. dbAttachment.MXID = resp.EventID
  445. dbAttachment.ThreadID = threadID
  446. dbAttachment.Insert()
  447. // Update the fallback reply event for the next attachment
  448. if threadRelation != nil {
  449. threadRelation.InReplyTo.EventID = resp.EventID
  450. }
  451. }
  452. func (portal *Portal) handleDiscordMessageCreate(user *User, msg *discordgo.Message, thread *Thread) {
  453. if portal.MXID == "" {
  454. portal.log.Warnln("handle message called without a valid portal")
  455. return
  456. }
  457. // Handle room name changes
  458. if msg.Type == discordgo.MessageTypeChannelNameChange {
  459. //channel, err := user.Session.Channel(msg.ChannelID)
  460. //if err != nil {
  461. // portal.log.Errorf("Failed to find the channel for portal %s", portal.Key)
  462. // return
  463. //}
  464. //
  465. //name, err := portal.bridge.Config.Bridge.FormatChannelname(channel, user.Session)
  466. //if err != nil {
  467. // portal.log.Errorf("Failed to format name for portal %s", portal.Key)
  468. // return
  469. //}
  470. //
  471. //portal.Name = name
  472. //portal.Update()
  473. //
  474. //portal.MainIntent().SetRoomName(portal.MXID, name)
  475. return
  476. }
  477. // Handle normal message
  478. existing := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.ID)
  479. if existing != nil {
  480. portal.log.Debugln("Dropping duplicate message", msg.ID)
  481. return
  482. }
  483. portal.log.Debugfln("Starting handling of %s by %s", msg.ID, msg.Author.ID)
  484. puppet := portal.bridge.GetPuppetByID(msg.Author.ID)
  485. puppet.UpdateInfo(user, msg.Author)
  486. intent := puppet.IntentFor(portal)
  487. var threadRelation *event.RelatesTo
  488. var threadID string
  489. if thread != nil {
  490. threadID = thread.ID
  491. lastEventID := thread.RootMXID
  492. lastInThread := portal.bridge.DB.Message.GetLastInThread(portal.Key, thread.ID)
  493. if lastInThread != nil {
  494. lastEventID = lastInThread.MXID
  495. }
  496. threadRelation = (&event.RelatesTo{}).SetThread(thread.RootMXID, lastEventID)
  497. }
  498. ts, _ := discordgo.SnowflakeTimestamp(msg.ID)
  499. if msg.Content != "" {
  500. content := &event.MessageEventContent{
  501. Body: msg.Content,
  502. MsgType: event.MsgText,
  503. RelatesTo: threadRelation.Copy(),
  504. }
  505. if msg.MessageReference != nil {
  506. //key := database.PortalKey{msg.MessageReference.ChannelID, user.ID}
  507. replyTo := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.MessageReference.MessageID)
  508. if replyTo != nil {
  509. if content.RelatesTo == nil {
  510. content.RelatesTo = &event.RelatesTo{}
  511. }
  512. content.RelatesTo.SetReplyTo(replyTo.MXID)
  513. }
  514. }
  515. resp, err := portal.sendMatrixMessage(intent, event.EventMessage, content, nil, ts.UnixMilli())
  516. if err != nil {
  517. portal.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  518. return
  519. }
  520. portal.markMessageHandled(msg.ID, resp.EventID, msg.Author.ID, ts, threadID)
  521. // Update the fallback reply event for attachments
  522. if threadRelation != nil {
  523. threadRelation.InReplyTo.EventID = resp.EventID
  524. }
  525. }
  526. for _, attachment := range msg.Attachments {
  527. portal.handleDiscordAttachment(intent, msg.ID, attachment, ts, threadRelation, threadID)
  528. }
  529. }
  530. func (portal *Portal) handleDiscordMessageUpdate(user *User, msg *discordgo.Message) {
  531. if portal.MXID == "" {
  532. portal.log.Warnln("handle message called without a valid portal")
  533. return
  534. }
  535. existing := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.ID)
  536. if existing == nil {
  537. portal.log.Warnfln("Dropping update of unknown message %s", msg.ID)
  538. return
  539. }
  540. if msg.Flags == discordgo.MessageFlagsHasThread {
  541. portal.bridge.GetThreadByID(msg.ID, existing)
  542. portal.log.Debugfln("Marked %s as a thread root", msg.ID)
  543. // TODO make autojoining configurable
  544. //err := user.Session.ThreadJoinWithLocation(msg.ID, discordgo.ThreadJoinLocationContextMenu)
  545. //if err != nil {
  546. // user.log.Warnfln("Error autojoining thread %s@%s: %v", msg.ChannelID, portal.Key.ChannelID, err)
  547. //}
  548. }
  549. // There's a few scenarios where the author is nil but I haven't figured
  550. // them all out yet.
  551. if msg.Author == nil {
  552. // If the server has to lookup opengraph previews it'll send the
  553. // message through without the preview and then add the preview later
  554. // via a message update. However, when it does this there is no author
  555. // as it's just the server, so for the moment we'll ignore this to
  556. // avoid a crash.
  557. if len(msg.Embeds) > 0 {
  558. portal.log.Debugln("ignoring update for opengraph attachment")
  559. return
  560. }
  561. //portal.log.Errorfln("author is nil: %#v", msg)
  562. return
  563. }
  564. intent := portal.bridge.GetPuppetByID(msg.Author.ID).IntentFor(portal)
  565. if existing == nil {
  566. // Due to the differences in Discord and Matrix attachment handling,
  567. // existing will return nil if the original message was empty as we
  568. // don't store/save those messages so we can determine when we're
  569. // working against an attachment and do the attachment lookup instead.
  570. // Find all the existing attachments and drop them in a map so we can
  571. // figure out which, if any have been deleted and clean them up on the
  572. // matrix side.
  573. attachmentMap := map[string]*database.Attachment{}
  574. attachments := portal.bridge.DB.Attachment.GetAllByDiscordMessageID(portal.Key, msg.ID)
  575. for _, attachment := range attachments {
  576. attachmentMap[attachment.ID] = attachment
  577. }
  578. // Now run through the list of attachments on this message and remove
  579. // them from the map.
  580. for _, attachment := range msg.Attachments {
  581. if _, found := attachmentMap[attachment.ID]; found {
  582. delete(attachmentMap, attachment.ID)
  583. }
  584. }
  585. // Finally run through any attachments still in the map and delete them
  586. // on the matrix side and our database.
  587. for _, attachment := range attachmentMap {
  588. _, err := intent.RedactEvent(portal.MXID, attachment.MXID)
  589. if err != nil {
  590. portal.log.Warnfln("Failed to remove attachment %s: %v", attachment.MXID, err)
  591. }
  592. attachment.Delete()
  593. }
  594. return
  595. }
  596. content := &event.MessageEventContent{
  597. Body: msg.Content,
  598. MsgType: event.MsgText,
  599. }
  600. content.SetEdit(existing.MXID)
  601. var editTS int64
  602. if msg.EditedTimestamp != nil {
  603. editTS = msg.EditedTimestamp.UnixMilli()
  604. }
  605. // TODO figure out some way to deduplicate outgoing edits
  606. _, err := portal.sendMatrixMessage(intent, event.EventMessage, content, nil, editTS)
  607. if err != nil {
  608. portal.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  609. return
  610. }
  611. //ts, _ := msg.Timestamp.Parse()
  612. //portal.markMessageHandled(existing, msg.ID, resp.EventID, msg.Author.ID, ts)
  613. }
  614. func (portal *Portal) handleDiscordMessageDelete(user *User, msg *discordgo.Message) {
  615. // The discord delete message object is pretty empty and doesn't include
  616. // the author so we have to use the DMUser from the portal that was added
  617. // at creation time if we're a DM. We'll might have similar issues when we
  618. // add guild message support, but we'll cross that bridge when we get
  619. // there.
  620. // Find the message that we're working with. This could correctly return
  621. // nil if the message was just one or more attachments.
  622. existing := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.ID)
  623. intent := portal.MainIntent()
  624. if existing != nil {
  625. attachments := portal.bridge.DB.Attachment.GetAllByDiscordMessageID(portal.Key, msg.ID)
  626. for _, attachment := range attachments {
  627. _, err := intent.RedactEvent(portal.MXID, attachment.MXID)
  628. if err != nil {
  629. portal.log.Warnfln("Failed to redact attachment %s: %v", attachment.MXID, err)
  630. }
  631. attachment.Delete()
  632. }
  633. _, err := intent.RedactEvent(portal.MXID, existing.MXID)
  634. if err != nil {
  635. portal.log.Warnfln("Failed to redact message %s: %v", existing.MXID, err)
  636. }
  637. existing.Delete()
  638. }
  639. }
  640. func (portal *Portal) syncParticipants(source *User, participants []*discordgo.User) {
  641. for _, participant := range participants {
  642. puppet := portal.bridge.GetPuppetByID(participant.ID)
  643. puppet.UpdateInfo(source, participant)
  644. user := portal.bridge.GetUserByID(participant.ID)
  645. if user != nil {
  646. portal.ensureUserInvited(user)
  647. }
  648. if user == nil || !puppet.IntentFor(portal).IsCustomPuppet {
  649. if err := puppet.IntentFor(portal).EnsureJoined(portal.MXID); err != nil {
  650. portal.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.ID, portal.MXID, err)
  651. }
  652. }
  653. }
  654. }
  655. func (portal *Portal) encrypt(content *event.Content, eventType event.Type) (event.Type, error) {
  656. if portal.Encrypted && portal.bridge.Crypto != nil {
  657. // TODO maybe the locking should be inside mautrix-go?
  658. portal.encryptLock.Lock()
  659. encrypted, err := portal.bridge.Crypto.Encrypt(portal.MXID, eventType, *content)
  660. portal.encryptLock.Unlock()
  661. if err != nil {
  662. return eventType, fmt.Errorf("failed to encrypt event: %w", err)
  663. }
  664. eventType = event.EventEncrypted
  665. content.Parsed = encrypted
  666. }
  667. return eventType, nil
  668. }
  669. const doublePuppetValue = "mautrix-discord"
  670. func (portal *Portal) sendMatrixMessage(intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, timestamp int64) (*mautrix.RespSendEvent, error) {
  671. wrappedContent := event.Content{Parsed: content, Raw: extraContent}
  672. if timestamp != 0 && intent.IsCustomPuppet {
  673. if wrappedContent.Raw == nil {
  674. wrappedContent.Raw = map[string]interface{}{}
  675. }
  676. if intent.IsCustomPuppet {
  677. wrappedContent.Raw[bridge.DoublePuppetKey] = doublePuppetValue
  678. }
  679. }
  680. var err error
  681. eventType, err = portal.encrypt(&wrappedContent, eventType)
  682. if err != nil {
  683. return nil, err
  684. }
  685. if eventType == event.EventEncrypted {
  686. // Clear other custom keys if the event was encrypted, but keep the double puppet identifier
  687. if intent.IsCustomPuppet {
  688. wrappedContent.Raw = map[string]interface{}{bridge.DoublePuppetKey: doublePuppetValue}
  689. } else {
  690. wrappedContent.Raw = nil
  691. }
  692. }
  693. _, _ = intent.UserTyping(portal.MXID, false, 0)
  694. if timestamp == 0 {
  695. return intent.SendMessageEvent(portal.MXID, eventType, &wrappedContent)
  696. } else {
  697. return intent.SendMassagedMessageEvent(portal.MXID, eventType, &wrappedContent, timestamp)
  698. }
  699. }
  700. func (portal *Portal) handleMatrixMessages(msg portalMatrixMessage) {
  701. switch msg.evt.Type {
  702. case event.EventMessage:
  703. portal.handleMatrixMessage(msg.user, msg.evt)
  704. case event.EventRedaction:
  705. portal.handleMatrixRedaction(msg.user, msg.evt)
  706. case event.EventReaction:
  707. portal.handleMatrixReaction(msg.user, msg.evt)
  708. default:
  709. portal.log.Debugln("unknown event type", msg.evt.Type)
  710. }
  711. }
  712. const discordEpoch = 1420070400000
  713. func generateNonce() string {
  714. snowflake := (time.Now().UnixMilli() - discordEpoch) << 22
  715. // Nonce snowflakes don't have internal IDs or increments
  716. return strconv.FormatInt(snowflake, 10)
  717. }
  718. func (portal *Portal) getEvent(mxid id.EventID) (*event.Event, error) {
  719. evt, err := portal.MainIntent().GetEvent(portal.MXID, mxid)
  720. if err != nil {
  721. return nil, err
  722. }
  723. _ = evt.Content.ParseRaw(evt.Type)
  724. if evt.Type == event.EventEncrypted {
  725. decryptedEvt, err := portal.bridge.Crypto.Decrypt(evt)
  726. if err != nil {
  727. return nil, err
  728. } else {
  729. evt = decryptedEvt
  730. }
  731. }
  732. return evt, nil
  733. }
  734. func genThreadName(evt *event.Event) string {
  735. body := evt.Content.AsMessage().Body
  736. if len(body) == 0 {
  737. return "thread"
  738. }
  739. fields := strings.Fields(body)
  740. var title string
  741. for _, field := range fields {
  742. if len(title)+len(field) < 40 {
  743. title += field
  744. title += " "
  745. continue
  746. }
  747. if len(title) == 0 {
  748. title = field[:40]
  749. }
  750. break
  751. }
  752. return title
  753. }
  754. func (portal *Portal) startThreadFromMatrix(sender *User, threadRoot id.EventID) (string, error) {
  755. rootEvt, err := portal.getEvent(threadRoot)
  756. if err != nil {
  757. return "", fmt.Errorf("failed to get root event: %w", err)
  758. }
  759. threadName := genThreadName(rootEvt)
  760. existingMsg := portal.bridge.DB.Message.GetByMXID(portal.Key, threadRoot)
  761. if existingMsg == nil {
  762. return "", fmt.Errorf("unknown root event")
  763. } else if existingMsg.ThreadID != "" {
  764. return "", fmt.Errorf("root event is already in a thread")
  765. } else {
  766. var ch *discordgo.Channel
  767. ch, err = sender.Session.MessageThreadStartComplex(portal.Key.ChannelID, existingMsg.DiscordID, &discordgo.ThreadStart{
  768. Name: threadName,
  769. AutoArchiveDuration: 24 * 60,
  770. Type: discordgo.ChannelTypeGuildPublicThread,
  771. Location: "Message",
  772. })
  773. if err != nil {
  774. return "", fmt.Errorf("error starting thread: %v", err)
  775. }
  776. portal.log.Debugfln("Created Discord thread from %s/%s", threadRoot, ch.ID)
  777. fmt.Printf("Created thread %+v\n", ch)
  778. portal.bridge.GetThreadByID(existingMsg.DiscordID, existingMsg)
  779. return ch.ID, nil
  780. }
  781. }
  782. func (portal *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
  783. if portal.IsPrivateChat() && sender.DiscordID != portal.Key.Receiver {
  784. return
  785. }
  786. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  787. if !ok {
  788. portal.log.Debugfln("Failed to handle event %s: unexpected parsed content type %T", evt.ID, evt.Content.Parsed)
  789. return
  790. }
  791. channelID := portal.Key.ChannelID
  792. var threadID string
  793. if editMXID := content.GetRelatesTo().GetReplaceID(); editMXID != "" && content.NewContent != nil {
  794. edits := portal.bridge.DB.Message.GetByMXID(portal.Key, editMXID)
  795. if edits != nil {
  796. // we don't have anything to save for the update message right now
  797. // as we're not tracking edited timestamps.
  798. _, err := sender.Session.ChannelMessageEdit(edits.DiscordProtoChannelID(), edits.DiscordID, content.NewContent.Body)
  799. if err != nil {
  800. portal.log.Errorln("Failed to update message %s: %v", edits.DiscordID, err)
  801. }
  802. }
  803. return
  804. } else if threadRoot := content.GetRelatesTo().GetThreadParent(); threadRoot != "" {
  805. existingThread := portal.bridge.DB.Thread.GetByMatrixRootMsg(threadRoot)
  806. if existingThread != nil {
  807. threadID = existingThread.ID
  808. } else {
  809. var err error
  810. threadID, err = portal.startThreadFromMatrix(sender, threadRoot)
  811. if err != nil {
  812. portal.log.Warnfln("Failed to start thread from %s: %v", threadRoot, err)
  813. }
  814. }
  815. }
  816. if threadID != "" {
  817. channelID = threadID
  818. }
  819. var sendReq discordgo.MessageSend
  820. switch content.MsgType {
  821. case event.MsgText, event.MsgEmote, event.MsgNotice:
  822. if replyToMXID := content.GetReplyTo(); replyToMXID != "" {
  823. replyTo := portal.bridge.DB.Message.GetByMXID(portal.Key, replyToMXID)
  824. if replyTo != nil && replyTo.ThreadID == threadID {
  825. sendReq.Reference = &discordgo.MessageReference{
  826. ChannelID: channelID,
  827. MessageID: replyTo.DiscordID,
  828. }
  829. }
  830. }
  831. sendReq.Content = content.Body
  832. case event.MsgAudio, event.MsgFile, event.MsgImage, event.MsgVideo:
  833. data, err := portal.downloadMatrixAttachment(evt.ID, content)
  834. if err != nil {
  835. portal.log.Errorfln("Failed to download matrix attachment: %v", err)
  836. return
  837. }
  838. sendReq.Files = []*discordgo.File{{
  839. Name: content.Body,
  840. ContentType: content.Info.MimeType,
  841. Reader: bytes.NewReader(data),
  842. }}
  843. default:
  844. portal.log.Warnln("Unknown message type", content.MsgType)
  845. return
  846. }
  847. sendReq.Nonce = generateNonce()
  848. msg, err := sender.Session.ChannelMessageSendComplex(channelID, &sendReq)
  849. if err != nil {
  850. portal.log.Errorfln("Failed to send message: %v", err)
  851. return
  852. }
  853. if msg != nil {
  854. dbMsg := portal.bridge.DB.Message.New()
  855. dbMsg.Channel = portal.Key
  856. dbMsg.DiscordID = msg.ID
  857. dbMsg.MXID = evt.ID
  858. dbMsg.SenderID = sender.DiscordID
  859. dbMsg.Timestamp, _ = discordgo.SnowflakeTimestamp(msg.ID)
  860. dbMsg.ThreadID = threadID
  861. dbMsg.Insert()
  862. }
  863. }
  864. func (portal *Portal) HandleMatrixLeave(brSender bridge.User) {
  865. portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
  866. portal.Delete()
  867. portal.cleanup(false)
  868. // TODO: figure out how to close a dm from the API.
  869. portal.cleanupIfEmpty()
  870. }
  871. func (portal *Portal) leave(sender *User) {
  872. if portal.MXID == "" {
  873. return
  874. }
  875. intent := portal.bridge.GetPuppetByID(sender.DiscordID).IntentFor(portal)
  876. intent.LeaveRoom(portal.MXID)
  877. }
  878. func (portal *Portal) Delete() {
  879. portal.Portal.Delete()
  880. portal.bridge.portalsLock.Lock()
  881. delete(portal.bridge.portalsByID, portal.Key)
  882. if portal.MXID != "" {
  883. delete(portal.bridge.portalsByMXID, portal.MXID)
  884. }
  885. portal.bridge.portalsLock.Unlock()
  886. }
  887. func (portal *Portal) cleanupIfEmpty() {
  888. if portal.MXID == "" {
  889. return
  890. }
  891. users, err := portal.getMatrixUsers()
  892. if err != nil {
  893. portal.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
  894. return
  895. }
  896. if len(users) == 0 {
  897. portal.log.Infoln("Room seems to be empty, cleaning up...")
  898. portal.Delete()
  899. portal.cleanup(false)
  900. }
  901. }
  902. func (portal *Portal) cleanup(puppetsOnly bool) {
  903. if portal.MXID == "" {
  904. return
  905. }
  906. if portal.IsPrivateChat() {
  907. _, err := portal.MainIntent().LeaveRoom(portal.MXID)
  908. if err != nil {
  909. portal.log.Warnln("Failed to leave private chat portal with main intent:", err)
  910. }
  911. return
  912. }
  913. intent := portal.MainIntent()
  914. members, err := intent.JoinedMembers(portal.MXID)
  915. if err != nil {
  916. portal.log.Errorln("Failed to get portal members for cleanup:", err)
  917. return
  918. }
  919. for member := range members.Joined {
  920. if member == intent.UserID {
  921. continue
  922. }
  923. puppet := portal.bridge.GetPuppetByMXID(member)
  924. if portal != nil {
  925. _, err = puppet.DefaultIntent().LeaveRoom(portal.MXID)
  926. if err != nil {
  927. portal.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  928. }
  929. } else if !puppetsOnly {
  930. _, err = intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  931. if err != nil {
  932. portal.log.Errorln("Error kicking user while cleaning up portal:", err)
  933. }
  934. }
  935. }
  936. _, err = intent.LeaveRoom(portal.MXID)
  937. if err != nil {
  938. portal.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  939. }
  940. }
  941. func (portal *Portal) getMatrixUsers() ([]id.UserID, error) {
  942. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  943. if err != nil {
  944. return nil, fmt.Errorf("failed to get member list: %w", err)
  945. }
  946. var users []id.UserID
  947. for userID := range members.Joined {
  948. _, isPuppet := portal.bridge.ParsePuppetMXID(userID)
  949. if !isPuppet && userID != portal.bridge.Bot.UserID {
  950. users = append(users, userID)
  951. }
  952. }
  953. return users, nil
  954. }
  955. func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) {
  956. if portal.IsPrivateChat() && sender.DiscordID != portal.Key.Receiver {
  957. return
  958. }
  959. reaction := evt.Content.AsReaction()
  960. if reaction.RelatesTo.Type != event.RelAnnotation {
  961. portal.log.Errorfln("Ignoring reaction %s due to unknown m.relates_to data", evt.ID)
  962. return
  963. }
  964. var discordID, threadID string
  965. channelID := portal.Key.ChannelID
  966. msg := portal.bridge.DB.Message.GetByMXID(portal.Key, reaction.RelatesTo.EventID)
  967. // Due to the differences in attachments between Discord and Matrix, if a
  968. // user reacts to a media message on discord our lookup above will fail
  969. // because the relation of matrix media messages to attachments in handled
  970. // in the attachments table instead of messages so we need to check that
  971. // before continuing.
  972. //
  973. // This also leads to interesting problems when a Discord message comes in
  974. // with multiple attachments. A user can react to each one individually on
  975. // Matrix, which will cause us to send it twice. Discord tends to ignore
  976. // this, but if the user removes one of them, discord removes it and now
  977. // they're out of sync. Perhaps we should add a counter to the reactions
  978. // table to keep them in sync and to avoid sending duplicates to Discord.
  979. if msg == nil {
  980. attachment := portal.bridge.DB.Attachment.GetByMatrixID(portal.Key, reaction.RelatesTo.EventID)
  981. if attachment == nil {
  982. return
  983. }
  984. discordID = attachment.MessageID
  985. threadID = attachment.ThreadID
  986. } else {
  987. discordID = msg.DiscordID
  988. threadID = msg.ThreadID
  989. }
  990. // Figure out if this is a custom emoji or not.
  991. emojiID := reaction.RelatesTo.Key
  992. if strings.HasPrefix(emojiID, "mxc://") {
  993. uri, _ := id.ParseContentURI(emojiID)
  994. emoji := portal.bridge.DB.Emoji.GetByMatrixURL(uri)
  995. if emoji == nil {
  996. portal.log.Errorfln("Couldn't find emoji corresponding to %s", emojiID)
  997. return
  998. }
  999. emojiID = emoji.APIName()
  1000. } else {
  1001. emojiID = variationselector.Remove(emojiID)
  1002. }
  1003. if threadID != "" {
  1004. channelID = threadID
  1005. }
  1006. err := sender.Session.MessageReactionAdd(channelID, discordID, emojiID)
  1007. if err != nil {
  1008. portal.log.Debugf("Failed to send reaction to %s: %v", discordID, err)
  1009. return
  1010. }
  1011. dbReaction := portal.bridge.DB.Reaction.New()
  1012. dbReaction.Channel = portal.Key
  1013. dbReaction.MessageID = discordID
  1014. dbReaction.Sender = sender.DiscordID
  1015. dbReaction.EmojiName = emojiID
  1016. dbReaction.ThreadID = threadID
  1017. dbReaction.MXID = evt.ID
  1018. dbReaction.Insert()
  1019. }
  1020. func (portal *Portal) handleDiscordReaction(user *User, reaction *discordgo.MessageReaction, add bool, thread *Thread) {
  1021. intent := portal.bridge.GetPuppetByID(reaction.UserID).IntentFor(portal)
  1022. var discordID string
  1023. var matrixReaction string
  1024. if reaction.Emoji.ID != "" {
  1025. dbEmoji := portal.bridge.DB.Emoji.GetByDiscordID(reaction.Emoji.ID)
  1026. if dbEmoji == nil {
  1027. data, mimeType, err := portal.downloadDiscordEmoji(reaction.Emoji.ID, reaction.Emoji.Animated)
  1028. if err != nil {
  1029. portal.log.Warnfln("Failed to download emoji %s from discord: %v", reaction.Emoji.ID, err)
  1030. return
  1031. }
  1032. uri, err := portal.uploadMatrixEmoji(intent, data, mimeType)
  1033. if err != nil {
  1034. portal.log.Warnfln("Failed to upload discord emoji %s to homeserver: %v", reaction.Emoji.ID, err)
  1035. return
  1036. }
  1037. dbEmoji = portal.bridge.DB.Emoji.New()
  1038. dbEmoji.DiscordID = reaction.Emoji.ID
  1039. dbEmoji.DiscordName = reaction.Emoji.Name
  1040. dbEmoji.MatrixURL = uri
  1041. dbEmoji.Insert()
  1042. }
  1043. discordID = dbEmoji.DiscordID
  1044. matrixReaction = dbEmoji.MatrixURL.String()
  1045. } else {
  1046. discordID = reaction.Emoji.Name
  1047. matrixReaction = variationselector.Add(reaction.Emoji.Name)
  1048. }
  1049. // Find the message that we're working with.
  1050. message := portal.bridge.DB.Message.GetByDiscordID(portal.Key, reaction.MessageID)
  1051. if message == nil {
  1052. portal.log.Debugfln("failed to add reaction to message %s: message not found", reaction.MessageID)
  1053. return
  1054. }
  1055. // Lookup an existing reaction
  1056. existing := portal.bridge.DB.Reaction.GetByDiscordID(portal.Key, message.DiscordID, reaction.UserID, discordID)
  1057. if !add {
  1058. if existing == nil {
  1059. portal.log.Debugln("Failed to remove reaction for unknown message", reaction.MessageID)
  1060. return
  1061. }
  1062. _, err := intent.RedactEvent(portal.MXID, existing.MXID)
  1063. if err != nil {
  1064. portal.log.Warnfln("Failed to remove reaction from %s: %v", portal.MXID, err)
  1065. }
  1066. existing.Delete()
  1067. return
  1068. } else if existing != nil {
  1069. portal.log.Debugfln("Ignoring duplicate reaction %s from %s to %s", discordID, reaction.UserID, message.DiscordID)
  1070. return
  1071. }
  1072. content := event.Content{Parsed: &event.ReactionEventContent{
  1073. RelatesTo: event.RelatesTo{
  1074. EventID: message.MXID,
  1075. Type: event.RelAnnotation,
  1076. Key: matrixReaction,
  1077. },
  1078. }}
  1079. if intent.IsCustomPuppet {
  1080. content.Raw = map[string]interface{}{
  1081. bridge.DoublePuppetKey: doublePuppetValue,
  1082. }
  1083. }
  1084. resp, err := intent.SendMessageEvent(portal.MXID, event.EventReaction, &content)
  1085. if err != nil {
  1086. portal.log.Errorfln("failed to send reaction from %s: %v", reaction.MessageID, err)
  1087. return
  1088. }
  1089. if existing == nil {
  1090. dbReaction := portal.bridge.DB.Reaction.New()
  1091. dbReaction.Channel = portal.Key
  1092. dbReaction.MessageID = message.DiscordID
  1093. dbReaction.Sender = reaction.UserID
  1094. dbReaction.EmojiName = discordID
  1095. dbReaction.MXID = resp.EventID
  1096. if thread != nil {
  1097. dbReaction.ThreadID = thread.ID
  1098. }
  1099. dbReaction.Insert()
  1100. }
  1101. }
  1102. func (portal *Portal) handleMatrixRedaction(user *User, evt *event.Event) {
  1103. if user.DiscordID != portal.Key.Receiver {
  1104. return
  1105. }
  1106. // First look if we're redacting a message
  1107. message := portal.bridge.DB.Message.GetByMXID(portal.Key, evt.Redacts)
  1108. if message != nil {
  1109. err := user.Session.ChannelMessageDelete(message.DiscordProtoChannelID(), message.DiscordID)
  1110. if err != nil {
  1111. portal.log.Debugfln("Failed to delete discord message %s: %v", message.DiscordID, err)
  1112. } else {
  1113. message.Delete()
  1114. }
  1115. return
  1116. }
  1117. // Now check if it's a reaction.
  1118. reaction := portal.bridge.DB.Reaction.GetByMXID(evt.Redacts)
  1119. if reaction != nil && reaction.Channel == portal.Key {
  1120. err := user.Session.MessageReactionRemove(reaction.DiscordProtoChannelID(), reaction.MessageID, reaction.EmojiName, reaction.Sender)
  1121. if err != nil {
  1122. portal.log.Debugfln("Failed to delete reaction %s from %s: %v", reaction.EmojiName, reaction.MessageID, err)
  1123. } else {
  1124. reaction.Delete()
  1125. }
  1126. return
  1127. }
  1128. portal.log.Warnfln("Failed to redact %s: no event found", evt.Redacts)
  1129. }
  1130. func (portal *Portal) UpdateName(name string) bool {
  1131. if portal.Name == name && portal.NameSet {
  1132. return false
  1133. } else if !portal.Encrypted && portal.IsPrivateChat() {
  1134. // TODO custom config option for always setting private chat portal meta?
  1135. return false
  1136. }
  1137. portal.Name = name
  1138. portal.NameSet = false
  1139. if portal.MXID != "" {
  1140. _, err := portal.MainIntent().SetRoomName(portal.MXID, portal.Name)
  1141. if err != nil {
  1142. portal.log.Warnln("Failed to update room name:", err)
  1143. } else {
  1144. portal.NameSet = true
  1145. }
  1146. }
  1147. return true
  1148. }
  1149. func (portal *Portal) UpdateAvatarFromPuppet(puppet *Puppet) bool {
  1150. if portal.Avatar == puppet.Avatar && portal.AvatarSet {
  1151. return false
  1152. }
  1153. portal.Avatar = puppet.Avatar
  1154. portal.AvatarURL = puppet.AvatarURL
  1155. portal.AvatarSet = false
  1156. portal.updateRoomAvatar()
  1157. return true
  1158. }
  1159. func (portal *Portal) UpdateGroupDMAvatar(iconID string) bool {
  1160. if portal.Avatar == iconID && portal.AvatarSet {
  1161. return false
  1162. }
  1163. portal.Avatar = iconID
  1164. portal.AvatarSet = false
  1165. if portal.Avatar != "" {
  1166. uri, err := uploadAvatar(portal.MainIntent(), discordgo.EndpointGroupIcon(portal.Key.ChannelID, portal.Avatar))
  1167. if err != nil {
  1168. portal.log.Warnln("Failed to reupload avatar:", err)
  1169. return true
  1170. } else {
  1171. portal.AvatarURL = uri
  1172. }
  1173. } else {
  1174. portal.AvatarURL = id.ContentURI{}
  1175. }
  1176. portal.updateRoomAvatar()
  1177. return true
  1178. }
  1179. func (portal *Portal) updateRoomAvatar() {
  1180. if portal.MXID == "" {
  1181. return
  1182. }
  1183. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL)
  1184. if err != nil {
  1185. portal.log.Warnln("Failed to update room avatar:", err)
  1186. } else {
  1187. portal.AvatarSet = true
  1188. }
  1189. }
  1190. func (portal *Portal) UpdateTopic(topic string) bool {
  1191. if portal.Topic == topic && portal.TopicSet {
  1192. return false
  1193. }
  1194. portal.Topic = topic
  1195. portal.TopicSet = false
  1196. if portal.MXID != "" {
  1197. _, err := portal.MainIntent().SetRoomTopic(portal.MXID, portal.Topic)
  1198. if err != nil {
  1199. portal.log.Warnln("Failed to update room topic:", err)
  1200. }
  1201. }
  1202. return true
  1203. }
  1204. func (portal *Portal) removeFromSpace() {
  1205. if portal.InSpace == "" {
  1206. return
  1207. }
  1208. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, portal.InSpace.String(), struct{}{})
  1209. if err != nil {
  1210. portal.log.Warnfln("Failed to unset canonical space %s: %v", portal.InSpace, err)
  1211. }
  1212. _, err = portal.bridge.Bot.SendStateEvent(portal.InSpace, event.StateSpaceChild, portal.MXID.String(), struct{}{})
  1213. if err != nil {
  1214. portal.log.Warnfln("Failed to add room to space %s: %v", portal.InSpace, err)
  1215. }
  1216. portal.InSpace = ""
  1217. }
  1218. func (portal *Portal) addToSpace(mxid id.RoomID) bool {
  1219. if portal.InSpace == mxid {
  1220. return false
  1221. }
  1222. portal.removeFromSpace()
  1223. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, mxid.String(), &event.SpaceParentEventContent{
  1224. Via: []string{portal.bridge.AS.HomeserverDomain},
  1225. Canonical: true,
  1226. })
  1227. if err != nil {
  1228. portal.log.Warnfln("Failed to set canonical space %s: %v", mxid, err)
  1229. }
  1230. _, err = portal.bridge.Bot.SendStateEvent(mxid, event.StateSpaceChild, portal.MXID.String(), &event.SpaceChildEventContent{
  1231. Via: []string{portal.bridge.AS.HomeserverDomain},
  1232. // TODO order
  1233. })
  1234. if err != nil {
  1235. portal.log.Warnfln("Failed to add room to space %s: %v", mxid, err)
  1236. } else {
  1237. portal.InSpace = mxid
  1238. }
  1239. return true
  1240. }
  1241. func (portal *Portal) UpdateParent(parentID string) bool {
  1242. if portal.ParentID == parentID {
  1243. return false
  1244. }
  1245. portal.ParentID = parentID
  1246. if portal.ParentID != "" {
  1247. portal.Parent = portal.bridge.GetExistingPortalByID(database.NewPortalKey(parentID, ""))
  1248. } else {
  1249. portal.Parent = nil
  1250. }
  1251. return true
  1252. }
  1253. func (portal *Portal) ExpectedSpaceID() id.RoomID {
  1254. if portal.Parent != nil {
  1255. return portal.Parent.MXID
  1256. } else if portal.Guild != nil {
  1257. return portal.Guild.MXID
  1258. }
  1259. return ""
  1260. }
  1261. func (portal *Portal) updateSpace() bool {
  1262. if portal.MXID == "" {
  1263. return false
  1264. }
  1265. if portal.Parent != nil {
  1266. return portal.addToSpace(portal.Parent.MXID)
  1267. } else if portal.Guild != nil {
  1268. return portal.addToSpace(portal.Guild.MXID)
  1269. }
  1270. return false
  1271. }
  1272. func (portal *Portal) UpdateInfo(source *User, meta *discordgo.Channel) *discordgo.Channel {
  1273. changed := false
  1274. if portal.Type != meta.Type {
  1275. portal.log.Warnfln("Portal type changed from %d to %d", portal.Type, meta.Type)
  1276. portal.Type = meta.Type
  1277. changed = true
  1278. }
  1279. if portal.OtherUserID == "" && portal.IsPrivateChat() {
  1280. if len(meta.Recipients) == 0 {
  1281. var err error
  1282. meta, err = source.Session.Channel(meta.ID)
  1283. if err != nil {
  1284. portal.log.Errorfln("Failed to get DM channel info:", err)
  1285. }
  1286. }
  1287. portal.OtherUserID = meta.Recipients[0].ID
  1288. portal.log.Infoln("Found other user ID:", portal.OtherUserID)
  1289. changed = true
  1290. }
  1291. if meta.GuildID != "" && portal.GuildID == "" {
  1292. portal.GuildID = meta.GuildID
  1293. portal.Guild = portal.bridge.GetGuildByID(portal.GuildID, true)
  1294. changed = true
  1295. }
  1296. // FIXME
  1297. //name, err := portal.bridge.Config.Bridge.FormatChannelname(meta, source.Session)
  1298. //if err != nil {
  1299. // portal.log.Errorln("Failed to format channel name:", err)
  1300. // return
  1301. //}
  1302. switch portal.Type {
  1303. case discordgo.ChannelTypeDM:
  1304. if portal.OtherUserID != "" {
  1305. puppet := portal.bridge.GetPuppetByID(portal.OtherUserID)
  1306. changed = portal.UpdateAvatarFromPuppet(puppet) || changed
  1307. changed = portal.UpdateName(puppet.Name) || changed
  1308. }
  1309. case discordgo.ChannelTypeGroupDM:
  1310. changed = portal.UpdateGroupDMAvatar(meta.Icon) || changed
  1311. fallthrough
  1312. default:
  1313. changed = portal.UpdateName(meta.Name) || changed
  1314. }
  1315. changed = portal.UpdateTopic(meta.Topic) || changed
  1316. changed = portal.UpdateParent(meta.ParentID) || changed
  1317. if portal.MXID != "" && portal.ExpectedSpaceID() != portal.InSpace {
  1318. changed = portal.updateSpace() || changed
  1319. }
  1320. if changed {
  1321. portal.UpdateBridgeInfo()
  1322. portal.Update()
  1323. }
  1324. return meta
  1325. }