portal.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2018 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 main
  17. import (
  18. "maunium.net/go/mautrix-whatsapp/database"
  19. log "maunium.net/go/maulogger"
  20. "fmt"
  21. )
  22. func (user *User) GetPortalByMXID(mxid string) *Portal {
  23. portal, ok := user.portalsByMXID[mxid]
  24. if !ok {
  25. dbPortal := user.bridge.DB.Portal.GetByMXID(mxid)
  26. if dbPortal == nil || dbPortal.Owner != user.UserID {
  27. return nil
  28. }
  29. portal = user.NewPortal(dbPortal)
  30. user.portalsByJID[portal.JID] = portal
  31. if len(portal.MXID) > 0 {
  32. user.portalsByMXID[portal.MXID] = portal
  33. }
  34. }
  35. return portal
  36. }
  37. func (user *User) GetPortalByJID(jid string) *Portal {
  38. portal, ok := user.portalsByJID[jid]
  39. if !ok {
  40. dbPortal := user.bridge.DB.Portal.GetByJID(user.UserID, jid)
  41. if dbPortal == nil {
  42. return nil
  43. }
  44. portal = user.NewPortal(dbPortal)
  45. user.portalsByJID[portal.JID] = portal
  46. if len(portal.MXID) > 0 {
  47. user.portalsByMXID[portal.MXID] = portal
  48. }
  49. }
  50. return portal
  51. }
  52. func (user *User) GetAllPortals() []*Portal {
  53. dbPortals := user.bridge.DB.Portal.GetAll(user.UserID)
  54. output := make([]*Portal, len(dbPortals))
  55. for index, dbPortal := range dbPortals {
  56. portal, ok := user.portalsByJID[dbPortal.JID]
  57. if !ok {
  58. portal = user.NewPortal(dbPortal)
  59. user.portalsByJID[dbPortal.JID] = portal
  60. if len(dbPortal.MXID) > 0 {
  61. user.portalsByMXID[dbPortal.MXID] = portal
  62. }
  63. }
  64. output[index] = portal
  65. }
  66. return output
  67. }
  68. func (user *User) NewPortal(dbPortal *database.Portal) *Portal {
  69. return &Portal{
  70. Portal: dbPortal,
  71. user: user,
  72. bridge: user.bridge,
  73. log: user.log.Sub(fmt.Sprintf("Portal/%s", dbPortal.JID)),
  74. }
  75. }
  76. type Portal struct {
  77. *database.Portal
  78. user *User
  79. bridge *Bridge
  80. log log.Logger
  81. }