portal.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. "fmt"
  20. "time"
  21. log "maunium.net/go/maulogger/v2"
  22. "maunium.net/go/mautrix/id"
  23. "maunium.net/go/mautrix/util/dbutil"
  24. "go.mau.fi/whatsmeow/types"
  25. )
  26. type PortalKey struct {
  27. JID types.JID
  28. Receiver types.JID
  29. }
  30. func NewPortalKey(jid, receiver types.JID) PortalKey {
  31. if jid.Server == types.GroupServer {
  32. receiver = jid
  33. } else if jid.Server == types.LegacyUserServer {
  34. jid.Server = types.DefaultUserServer
  35. }
  36. return PortalKey{
  37. JID: jid.ToNonAD(),
  38. Receiver: receiver.ToNonAD(),
  39. }
  40. }
  41. func (key PortalKey) String() string {
  42. if key.Receiver == key.JID {
  43. return key.JID.String()
  44. }
  45. return key.JID.String() + "-" + key.Receiver.String()
  46. }
  47. type PortalQuery struct {
  48. db *Database
  49. log log.Logger
  50. }
  51. func (pq *PortalQuery) New() *Portal {
  52. return &Portal{
  53. db: pq.db,
  54. log: pq.log,
  55. }
  56. }
  57. const portalColumns = "jid, receiver, mxid, name, name_set, topic, topic_set, avatar, avatar_url, avatar_set, encrypted, last_sync, is_parent, parent_group, in_space, first_event_id, next_batch_id, relay_user_id, expiration_time"
  58. func (pq *PortalQuery) GetAll() []*Portal {
  59. return pq.getAll(fmt.Sprintf("SELECT %s FROM portal", portalColumns))
  60. }
  61. func (pq *PortalQuery) GetByJID(key PortalKey) *Portal {
  62. return pq.get(fmt.Sprintf("SELECT %s FROM portal WHERE jid=$1 AND receiver=$2", portalColumns), key.JID, key.Receiver)
  63. }
  64. func (pq *PortalQuery) GetByMXID(mxid id.RoomID) *Portal {
  65. return pq.get(fmt.Sprintf("SELECT %s FROM portal WHERE mxid=$1", portalColumns), mxid)
  66. }
  67. func (pq *PortalQuery) GetAllByJID(jid types.JID) []*Portal {
  68. return pq.getAll(fmt.Sprintf("SELECT %s FROM portal WHERE jid=$1", portalColumns), jid.ToNonAD())
  69. }
  70. func (pq *PortalQuery) GetAllByParentGroup(jid types.JID) []*Portal {
  71. return pq.getAll(fmt.Sprintf("SELECT %s FROM portal WHERE parent_group=$1", portalColumns), jid)
  72. }
  73. func (pq *PortalQuery) FindPrivateChats(receiver types.JID) []*Portal {
  74. return pq.getAll(fmt.Sprintf("SELECT %s FROM portal WHERE receiver=$1 AND jid LIKE '%%@s.whatsapp.net'", portalColumns), 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. NameSet bool
  121. Topic string
  122. TopicSet bool
  123. Avatar string
  124. AvatarURL id.ContentURI
  125. AvatarSet bool
  126. Encrypted bool
  127. LastSync time.Time
  128. IsParent bool
  129. ParentGroup types.JID
  130. InSpace bool
  131. FirstEventID id.EventID
  132. NextBatchID id.BatchID
  133. RelayUserID id.UserID
  134. ExpirationTime uint32
  135. }
  136. func (portal *Portal) Scan(row dbutil.Scannable) *Portal {
  137. var mxid, avatarURL, firstEventID, nextBatchID, relayUserID, parentGroupJID sql.NullString
  138. var lastSyncTs int64
  139. err := row.Scan(&portal.Key.JID, &portal.Key.Receiver, &mxid, &portal.Name, &portal.NameSet, &portal.Topic, &portal.TopicSet, &portal.Avatar, &avatarURL, &portal.AvatarSet, &portal.Encrypted, &lastSyncTs, &portal.IsParent, &parentGroupJID, &portal.InSpace, &firstEventID, &nextBatchID, &relayUserID, &portal.ExpirationTime)
  140. if err != nil {
  141. if err != sql.ErrNoRows {
  142. portal.log.Errorln("Database scan failed:", err)
  143. }
  144. return nil
  145. }
  146. if lastSyncTs > 0 {
  147. portal.LastSync = time.Unix(lastSyncTs, 0)
  148. }
  149. portal.MXID = id.RoomID(mxid.String)
  150. portal.AvatarURL, _ = id.ParseContentURI(avatarURL.String)
  151. if parentGroupJID.Valid {
  152. portal.ParentGroup, _ = types.ParseJID(parentGroupJID.String)
  153. }
  154. portal.FirstEventID = id.EventID(firstEventID.String)
  155. portal.NextBatchID = id.BatchID(nextBatchID.String)
  156. portal.RelayUserID = id.UserID(relayUserID.String)
  157. return portal
  158. }
  159. func (portal *Portal) mxidPtr() *id.RoomID {
  160. if len(portal.MXID) > 0 {
  161. return &portal.MXID
  162. }
  163. return nil
  164. }
  165. func (portal *Portal) relayUserPtr() *id.UserID {
  166. if len(portal.RelayUserID) > 0 {
  167. return &portal.RelayUserID
  168. }
  169. return nil
  170. }
  171. func (portal *Portal) parentGroupPtr() *string {
  172. if !portal.ParentGroup.IsEmpty() {
  173. val := portal.ParentGroup.String()
  174. return &val
  175. }
  176. return nil
  177. }
  178. func (portal *Portal) lastSyncTs() int64 {
  179. if portal.LastSync.IsZero() {
  180. return 0
  181. }
  182. return portal.LastSync.Unix()
  183. }
  184. func (portal *Portal) Insert() {
  185. _, err := portal.db.Exec(`
  186. INSERT INTO portal (jid, receiver, mxid, name, name_set, topic, topic_set, avatar, avatar_url, avatar_set,
  187. encrypted, last_sync, is_parent, parent_group, in_space, first_event_id, next_batch_id,
  188. relay_user_id, expiration_time)
  189. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
  190. `,
  191. portal.Key.JID, portal.Key.Receiver, portal.mxidPtr(), portal.Name, portal.NameSet, portal.Topic, portal.TopicSet,
  192. portal.Avatar, portal.AvatarURL.String(), portal.AvatarSet, portal.Encrypted, portal.lastSyncTs(),
  193. portal.IsParent, portal.parentGroupPtr(), portal.InSpace, portal.FirstEventID.String(), portal.NextBatchID.String(),
  194. portal.relayUserPtr(), portal.ExpirationTime)
  195. if err != nil {
  196. portal.log.Warnfln("Failed to insert %s: %v", portal.Key, err)
  197. }
  198. }
  199. func (portal *Portal) Update(txn dbutil.Execable) {
  200. if txn == nil {
  201. txn = portal.db
  202. }
  203. _, err := txn.Exec(`
  204. UPDATE portal
  205. SET mxid=$1, name=$2, name_set=$3, topic=$4, topic_set=$5, avatar=$6, avatar_url=$7, avatar_set=$8,
  206. encrypted=$9, last_sync=$10, is_parent=$11, parent_group=$12, in_space=$13,
  207. first_event_id=$14, next_batch_id=$15, relay_user_id=$16, expiration_time=$17
  208. WHERE jid=$18 AND receiver=$19
  209. `, portal.mxidPtr(), portal.Name, portal.NameSet, portal.Topic, portal.TopicSet, portal.Avatar, portal.AvatarURL.String(),
  210. portal.AvatarSet, portal.Encrypted, portal.lastSyncTs(), portal.IsParent, portal.parentGroupPtr(), portal.InSpace,
  211. portal.FirstEventID.String(), portal.NextBatchID.String(), portal.relayUserPtr(), portal.ExpirationTime,
  212. portal.Key.JID, portal.Key.Receiver)
  213. if err != nil {
  214. portal.log.Warnfln("Failed to update %s: %v", portal.Key, err)
  215. }
  216. }
  217. func (portal *Portal) Delete() {
  218. txn, err := portal.db.Begin()
  219. if err != nil {
  220. portal.log.Errorfln("Failed to begin transaction to delete portal %v: %v", portal.Key, err)
  221. return
  222. }
  223. defer func() {
  224. if err != nil {
  225. err = txn.Rollback()
  226. if err != nil {
  227. portal.log.Warnfln("Failed to rollback failed portal delete transaction: %v", err)
  228. }
  229. } else if err = txn.Commit(); err != nil {
  230. portal.log.Warnfln("Failed to commit portal delete transaction: %v", err)
  231. }
  232. }()
  233. _, err = portal.db.Exec("UPDATE portal SET in_space=false WHERE parent_group=$1", portal.Key.JID)
  234. if err != nil {
  235. portal.log.Warnfln("Failed to mark child groups of %v as not in space: %v", portal.Key.JID, err)
  236. return
  237. }
  238. _, err = portal.db.Exec("DELETE FROM portal WHERE jid=$1 AND receiver=$2", portal.Key.JID, portal.Key.Receiver)
  239. if err != nil {
  240. portal.log.Warnfln("Failed to delete %v: %v", portal.Key, err)
  241. }
  242. }