package store import ( "context" "database/sql" "encoding/json" "errors" "fmt" "git.stinnesbeck.com/nils/allmende/internal/jcs" "git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/message" ) // Directions of an InboxMessage. const ( InboxIn = "in" // from a buyer InboxOut = "out" // our reply ) // InboxMessage is one decrypted message in the owner's conversations. type InboxMessage struct { Hash string // hash of the envelope that carried it Listing message.Ref Thread string Dir string Plain *message.Plain Hidden bool // a buyer message that broke the first-message rules ReceivedAt int64 } // ThreadSummary describes one conversation. type ThreadSummary struct { Listing message.Ref Thread string Messages int Hidden int Replied bool // we have answered at least once FirstAt int64 LastAt int64 } // Address is the exact location and contact data of a listing. It is stored // only here and used only to prefill an address grant. type Address struct { Address string `json:"address"` Phone string `json:"phone,omitempty"` Email string `json:"email,omitempty"` } // Region returns the gossip region of a listing, even if it is deleted or // expired but not yet purged, so replies can still be routed. func (s *Store) Region(ctx context.Context, author, id string) (string, error) { var geohash string err := s.db.QueryRowContext(ctx, `SELECT geohash FROM listings WHERE author = ? AND id = ?`, author, id).Scan(&geohash) if errors.Is(err, sql.ErrNoRows) { return "", ErrNotFound } if err != nil { return "", err } return listing.Region(geohash), nil } // SeenEnvelopes returns which of the given envelope hashes the owner's node // has already processed. func (s *Store) SeenEnvelopes(ctx context.Context, hashes []string) (map[string]bool, error) { seen := map[string]bool{} for _, h := range hashes { var n int if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM inbox_seen WHERE hash = ?`, h).Scan(&n); err != nil { return nil, err } seen[h] = n > 0 } return seen, nil } // MarkSeen records an envelope as processed until expiresAt. func (s *Store) MarkSeen(ctx context.Context, hash string, expiresAt int64) error { _, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`, hash, expiresAt) return err } // AddInbox stores a decrypted message and marks its envelope as seen, in one // transaction. Adding the same hash twice is a no-op. func (s *Store) AddInbox(ctx context.Context, m InboxMessage, seenUntil int64) error { data, err := jcs.Marshal(m.Plain) if err != nil { return err } tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() if _, err := tx.ExecContext(ctx, ` INSERT OR IGNORE INTO inbox (hash, author, listing_id, thread, dir, n, sent_at, received_at, hidden, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, m.Hash, m.Listing.Author, m.Listing.ID, m.Thread, m.Dir, m.Plain.N, m.Plain.SentAt, m.ReceivedAt, boolInt(m.Hidden), data); err != nil { return err } if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`, m.Hash, seenUntil); err != nil { return err } return tx.Commit() } // HasThread reports whether a conversation exists. func (s *Store) HasThread(ctx context.Context, ref message.Ref, thread string) (bool, error) { var n int err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`, ref.Author, ref.ID, thread).Scan(&n) return n > 0, err } // Replied reports whether we have sent anything in the conversation. func (s *Store) Replied(ctx context.Context, ref message.Ref, thread string) (bool, error) { var n int err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`, ref.Author, ref.ID, thread).Scan(&n) return n > 0, err } // NewThreadsSince counts conversations of a listing that began (were first // received) at or after since. func (s *Store) NewThreadsSince(ctx context.Context, ref message.Ref, since int64) (int, error) { var n int err := s.db.QueryRowContext(ctx, ` SELECT COUNT(*) FROM ( SELECT MIN(received_at) AS first FROM inbox WHERE author = ? AND listing_id = ? GROUP BY thread ) WHERE first >= ?`, ref.Author, ref.ID, since).Scan(&n) return n, err } // NextOut returns the counter for our next message in a conversation. func (s *Store) NextOut(ctx context.Context, ref message.Ref, thread string) (int64, error) { var max sql.NullInt64 err := s.db.QueryRowContext(ctx, `SELECT MAX(n) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`, ref.Author, ref.ID, thread).Scan(&max) return max.Int64 + 1, err } // Threads lists the author's conversations, most recently active first. func (s *Store) Threads(ctx context.Context, author string) ([]ThreadSummary, error) { rows, err := s.db.QueryContext(ctx, ` SELECT listing_id, thread, COUNT(*), SUM(hidden), SUM(dir = 'out'), MIN(received_at), MAX(sent_at) FROM inbox WHERE author = ? GROUP BY listing_id, thread ORDER BY MAX(sent_at) DESC, thread`, author) if err != nil { return nil, err } defer rows.Close() var out []ThreadSummary for rows.Next() { t := ThreadSummary{Listing: message.Ref{Author: author}} var replies int if err := rows.Scan(&t.Listing.ID, &t.Thread, &t.Messages, &t.Hidden, &replies, &t.FirstAt, &t.LastAt); err != nil { return nil, err } t.Replied = replies > 0 out = append(out, t) } return out, rows.Err() } // ThreadMessages returns a conversation in order. func (s *Store) ThreadMessages(ctx context.Context, ref message.Ref, thread string) ([]InboxMessage, error) { rows, err := s.db.QueryContext(ctx, ` SELECT hash, dir, hidden, received_at, data FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? ORDER BY sent_at, dir, n, hash`, ref.Author, ref.ID, thread) if err != nil { return nil, err } defer rows.Close() var out []InboxMessage for rows.Next() { m := InboxMessage{Listing: ref, Thread: thread} var hidden int var data []byte if err := rows.Scan(&m.Hash, &m.Dir, &hidden, &m.ReceivedAt, &data); err != nil { return nil, err } m.Hidden = hidden != 0 m.Plain = &message.Plain{} if err := json.Unmarshal(data, m.Plain); err != nil { return nil, fmt.Errorf("store: corrupt inbox row: %w", err) } out = append(out, m) } return out, rows.Err() } // DeleteThread erases a conversation from this node. func (s *Store) DeleteThread(ctx context.Context, ref message.Ref, thread string) (bool, error) { res, err := s.db.ExecContext(ctx, `DELETE FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`, ref.Author, ref.ID, thread) if err != nil { return false, err } n, _ := res.RowsAffected() return n > 0, nil } // SetAddress stores the exact address of one of the author's listings. func (s *Store) SetAddress(ctx context.Context, ref message.Ref, a Address) error { _, err := s.db.ExecContext(ctx, ` INSERT OR REPLACE INTO addresses (author, listing_id, address, phone, email) VALUES (?, ?, ?, ?, ?)`, ref.Author, ref.ID, a.Address, a.Phone, a.Email) return err } // GetAddress returns the stored address, or ErrNotFound. func (s *Store) GetAddress(ctx context.Context, ref message.Ref) (Address, error) { var a Address err := s.db.QueryRowContext(ctx, `SELECT address, phone, email FROM addresses WHERE author = ? AND listing_id = ?`, ref.Author, ref.ID).Scan(&a.Address, &a.Phone, &a.Email) if errors.Is(err, sql.ErrNoRows) { return a, ErrNotFound } return a, err } // DeleteAddress erases the stored address. func (s *Store) DeleteAddress(ctx context.Context, ref message.Ref) error { _, err := s.db.ExecContext(ctx, `DELETE FROM addresses WHERE author = ? AND listing_id = ?`, ref.Author, ref.ID) return err } // BlockThread erases a conversation and remembers its thread key, so the // envelopes the buyer keeps sending are dropped unread. It reports whether the // conversation existed; blocking an unknown thread does nothing. func (s *Store) BlockThread(ctx context.Context, ref message.Ref, thread string, now int64) (bool, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return false, err } defer tx.Rollback() res, err := tx.ExecContext(ctx, `DELETE FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`, ref.Author, ref.ID, thread) if err != nil { return false, err } n, _ := res.RowsAffected() if n == 0 { return false, nil } if _, err := tx.ExecContext(ctx, ` INSERT OR IGNORE INTO inbox_blocked (author, listing_id, thread, blocked_at) VALUES (?, ?, ?, ?)`, ref.Author, ref.ID, thread, now); err != nil { return false, err } return true, tx.Commit() } // UnblockThread lifts a block. What was sent while blocked is gone. func (s *Store) UnblockThread(ctx context.Context, ref message.Ref, thread string) (bool, error) { res, err := s.db.ExecContext(ctx, `DELETE FROM inbox_blocked WHERE author = ? AND listing_id = ? AND thread = ?`, ref.Author, ref.ID, thread) if err != nil { return false, err } n, _ := res.RowsAffected() return n > 0, nil } // Blocked is one blocked conversation. type Blocked struct { Listing message.Ref Thread string BlockedAt int64 } // BlockedThreads lists the author's blocked conversations, newest first. func (s *Store) BlockedThreads(ctx context.Context, author string) ([]Blocked, error) { rows, err := s.db.QueryContext(ctx, ` SELECT listing_id, thread, blocked_at FROM inbox_blocked WHERE author = ? ORDER BY blocked_at DESC, thread`, author) if err != nil { return nil, err } defer rows.Close() var out []Blocked for rows.Next() { b := Blocked{Listing: message.Ref{Author: author}} if err := rows.Scan(&b.Listing.ID, &b.Thread, &b.BlockedAt); err != nil { return nil, err } out = append(out, b) } return out, rows.Err() }