portal.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package database
  2. import (
  3. "database/sql"
  4. "github.com/bwmarrin/discordgo"
  5. log "maunium.net/go/maulogger/v2"
  6. "maunium.net/go/mautrix/id"
  7. )
  8. type Portal struct {
  9. db *Database
  10. log log.Logger
  11. Key PortalKey
  12. MXID id.RoomID
  13. Name string
  14. Topic string
  15. Encrypted bool
  16. Avatar string
  17. AvatarURL id.ContentURI
  18. Type discordgo.ChannelType
  19. DMUser string
  20. FirstEventID id.EventID
  21. }
  22. func (p *Portal) Scan(row Scannable) *Portal {
  23. var mxid, avatarURL, firstEventID sql.NullString
  24. var typ sql.NullInt32
  25. err := row.Scan(&p.Key.ChannelID, &p.Key.Receiver, &mxid, &p.Name,
  26. &p.Topic, &p.Avatar, &avatarURL, &typ, &p.DMUser, &firstEventID,
  27. &p.Encrypted)
  28. if err != nil {
  29. if err != sql.ErrNoRows {
  30. p.log.Errorln("Database scan failed:", err)
  31. }
  32. return nil
  33. }
  34. p.MXID = id.RoomID(mxid.String)
  35. p.AvatarURL, _ = id.ParseContentURI(avatarURL.String)
  36. p.Type = discordgo.ChannelType(typ.Int32)
  37. p.FirstEventID = id.EventID(firstEventID.String)
  38. return p
  39. }
  40. func (p *Portal) mxidPtr() *id.RoomID {
  41. if p.MXID != "" {
  42. return &p.MXID
  43. }
  44. return nil
  45. }
  46. func (p *Portal) Insert() {
  47. query := "INSERT INTO portal" +
  48. " (channel_id, receiver, mxid, name, topic, avatar, avatar_url," +
  49. " type, dmuser, first_event_id, encrypted)" +
  50. " VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)"
  51. _, err := p.db.Exec(query, p.Key.ChannelID, p.Key.Receiver, p.mxidPtr(),
  52. p.Name, p.Topic, p.Avatar, p.AvatarURL.String(), p.Type, p.DMUser,
  53. p.FirstEventID.String(), p.Encrypted)
  54. if err != nil {
  55. p.log.Warnfln("Failed to insert %s: %v", p.Key, err)
  56. }
  57. }
  58. func (p *Portal) Update() {
  59. query := "UPDATE portal SET" +
  60. " mxid=$1, name=$2, topic=$3, avatar=$4, avatar_url=$5, type=$6," +
  61. " dmuser=$7, first_event_id=$8, encrypted=$9" +
  62. " WHERE channel_id=$10 AND receiver=$11"
  63. _, err := p.db.Exec(query, p.mxidPtr(), p.Name, p.Topic, p.Avatar,
  64. p.AvatarURL.String(), p.Type, p.DMUser, p.FirstEventID.String(),
  65. p.Encrypted,
  66. p.Key.ChannelID, p.Key.Receiver)
  67. if err != nil {
  68. p.log.Warnfln("Failed to update %s: %v", p.Key, err)
  69. }
  70. }
  71. func (p *Portal) Delete() {
  72. query := "DELETE FROM portal WHERE channel_id=$1 AND receiver=$2"
  73. _, err := p.db.Exec(query, p.Key.ChannelID, p.Key.Receiver)
  74. if err != nil {
  75. p.log.Warnfln("Failed to delete %s: %v", p.Key, err)
  76. }
  77. }