portal.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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 database
  17. import (
  18. "database/sql"
  19. log "maunium.net/go/maulogger/v2"
  20. "maunium.net/go/mautrix/id"
  21. "go.mau.fi/whatsmeow/types"
  22. )
  23. type PortalKey struct {
  24. JID types.JID
  25. Receiver types.JID
  26. }
  27. func NewPortalKey(jid, receiver types.JID) PortalKey {
  28. if jid.Server == types.GroupServer {
  29. receiver = jid
  30. } else if jid.Server == types.LegacyUserServer {
  31. jid.Server = types.DefaultUserServer
  32. }
  33. return PortalKey{
  34. JID: jid.ToNonAD(),
  35. Receiver: receiver.ToNonAD(),
  36. }
  37. }
  38. func (key PortalKey) String() string {
  39. if key.Receiver == key.JID {
  40. return key.JID.String()
  41. }
  42. return key.JID.String() + "-" + key.Receiver.String()
  43. }
  44. type PortalQuery struct {
  45. db *Database
  46. log log.Logger
  47. }
  48. func (pq *PortalQuery) New() *Portal {
  49. return &Portal{
  50. db: pq.db,
  51. log: pq.log,
  52. }
  53. }
  54. func (pq *PortalQuery) GetAll() []*Portal {
  55. return pq.getAll("SELECT * FROM portal")
  56. }
  57. func (pq *PortalQuery) GetAllForUser(userID id.UserID) []*Portal {
  58. return pq.getAll(`
  59. SELECT p.* FROM portal p
  60. LEFT JOIN user_portal up ON p.jid=up.portal_jid AND p.receiver=up.portal_receiver
  61. WHERE mxid<>'' AND up.user_mxid=$1
  62. `, userID)
  63. }
  64. func (pq *PortalQuery) GetByJID(key PortalKey) *Portal {
  65. return pq.get("SELECT * FROM portal WHERE jid=$1 AND receiver=$2", key.JID, key.Receiver)
  66. }
  67. func (pq *PortalQuery) GetByMXID(mxid id.RoomID) *Portal {
  68. return pq.get("SELECT * FROM portal WHERE mxid=$1", mxid)
  69. }
  70. func (pq *PortalQuery) GetAllByJID(jid types.JID) []*Portal {
  71. return pq.getAll("SELECT * FROM portal WHERE jid=$1", jid.ToNonAD())
  72. }
  73. func (pq *PortalQuery) FindPrivateChats(receiver types.JID) []*Portal {
  74. return pq.getAll("SELECT * FROM portal WHERE receiver=$1 AND jid LIKE '%@s.whatsapp.net'", receiver.ToNonAD())
  75. }
  76. func (pq *PortalQuery) FindPrivateChatsNotInSpace(receiver types.JID) (keys []PortalKey) {
  77. receiver = receiver.ToNonAD()
  78. rows, err := pq.db.Query(`
  79. SELECT jid FROM portal
  80. LEFT JOIN user_portal ON portal.jid=user_portal.portal_jid AND portal.receiver=user_portal.portal_receiver
  81. WHERE mxid<>'' AND receiver=$1 AND (in_space=false OR in_space IS NULL)
  82. `, receiver)
  83. if err != nil || rows == nil {
  84. return
  85. }
  86. for rows.Next() {
  87. var key PortalKey
  88. key.Receiver = receiver
  89. err = rows.Scan(&key.JID)
  90. if err == nil {
  91. keys = append(keys, key)
  92. }
  93. }
  94. return
  95. }
  96. func (pq *PortalQuery) getAll(query string, args ...interface{}) (portals []*Portal) {
  97. rows, err := pq.db.Query(query, args...)
  98. if err != nil || rows == nil {
  99. return nil
  100. }
  101. defer rows.Close()
  102. for rows.Next() {
  103. portals = append(portals, pq.New().Scan(rows))
  104. }
  105. return
  106. }
  107. func (pq *PortalQuery) get(query string, args ...interface{}) *Portal {
  108. row := pq.db.QueryRow(query, args...)
  109. if row == nil {
  110. return nil
  111. }
  112. return pq.New().Scan(row)
  113. }
  114. type Portal struct {
  115. db *Database
  116. log log.Logger
  117. Key PortalKey
  118. MXID id.RoomID
  119. Name string
  120. Topic string
  121. Avatar string
  122. AvatarURL id.ContentURI
  123. Encrypted bool
  124. FirstEventID id.EventID
  125. NextBatchID id.BatchID
  126. RelayUserID id.UserID
  127. ExpirationTime uint32
  128. }
  129. func (portal *Portal) Scan(row Scannable) *Portal {
  130. var mxid, avatarURL, firstEventID, nextBatchID, relayUserID sql.NullString
  131. err := row.Scan(&portal.Key.JID, &portal.Key.Receiver, &mxid, &portal.Name, &portal.Topic, &portal.Avatar, &avatarURL, &portal.Encrypted, &firstEventID, &nextBatchID, &relayUserID, &portal.ExpirationTime)
  132. if err != nil {
  133. if err != sql.ErrNoRows {
  134. portal.log.Errorln("Database scan failed:", err)
  135. }
  136. return nil
  137. }
  138. portal.MXID = id.RoomID(mxid.String)
  139. portal.AvatarURL, _ = id.ParseContentURI(avatarURL.String)
  140. portal.FirstEventID = id.EventID(firstEventID.String)
  141. portal.NextBatchID = id.BatchID(nextBatchID.String)
  142. portal.RelayUserID = id.UserID(relayUserID.String)
  143. return portal
  144. }
  145. func (portal *Portal) mxidPtr() *id.RoomID {
  146. if len(portal.MXID) > 0 {
  147. return &portal.MXID
  148. }
  149. return nil
  150. }
  151. func (portal *Portal) relayUserPtr() *id.UserID {
  152. if len(portal.RelayUserID) > 0 {
  153. return &portal.RelayUserID
  154. }
  155. return nil
  156. }
  157. func (portal *Portal) Insert() {
  158. _, err := portal.db.Exec("INSERT INTO portal (jid, receiver, mxid, name, topic, avatar, avatar_url, encrypted, first_event_id, next_batch_id, relay_user_id, expiration_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
  159. portal.Key.JID, portal.Key.Receiver, portal.mxidPtr(), portal.Name, portal.Topic, portal.Avatar, portal.AvatarURL.String(), portal.Encrypted, portal.FirstEventID.String(), portal.NextBatchID.String(), portal.relayUserPtr(), portal.ExpirationTime)
  160. if err != nil {
  161. portal.log.Warnfln("Failed to insert %s: %v", portal.Key, err)
  162. }
  163. }
  164. func (portal *Portal) Update(txn *sql.Tx) {
  165. query := `
  166. UPDATE portal
  167. SET mxid=$1, name=$2, topic=$3, avatar=$4, avatar_url=$5, encrypted=$6, first_event_id=$7, next_batch_id=$8, relay_user_id=$9, expiration_time=$10
  168. WHERE jid=$11 AND receiver=$12
  169. `
  170. args := []interface{}{
  171. portal.mxidPtr(), portal.Name, portal.Topic, portal.Avatar, portal.AvatarURL.String(), portal.Encrypted, portal.FirstEventID.String(), portal.NextBatchID.String(), portal.relayUserPtr(), portal.ExpirationTime, portal.Key.JID, portal.Key.Receiver,
  172. }
  173. var err error
  174. if txn != nil {
  175. _, err = txn.Exec(query, args...)
  176. } else {
  177. _, err = portal.db.Exec(query, args...)
  178. }
  179. if err != nil {
  180. portal.log.Warnfln("Failed to update %s: %v", portal.Key, err)
  181. }
  182. }
  183. func (portal *Portal) Delete() {
  184. _, err := portal.db.Exec("DELETE FROM portal WHERE jid=$1 AND receiver=$2", portal.Key.JID, portal.Key.Receiver)
  185. if err != nil {
  186. portal.log.Warnfln("Failed to delete %s: %v", portal.Key, err)
  187. }
  188. }