package delivery import ( "context" "errors" "github.com/jackc/pgx/v5" ) func (s *Store) Unread(ctx context.Context, recipient string) (map[string]int64, error) { rows, err := s.db.Query(ctx, ` SELECT sender.user_id, count(*) FROM device_envelopes e JOIN devices sender ON sender.id=e.sender_device AND sender.revoked_at IS NULL JOIN devices recipient ON recipient.id=e.recipient_device AND recipient.revoked_at IS NULL JOIN contact_relationships r ON r.first_user=LEAST(sender.user_id,recipient.user_id) AND r.second_user=GREATEST(sender.user_id,recipient.user_id) AND r.status='accepted' LEFT JOIN device_contact_seen seen ON seen.recipient_device=e.recipient_device AND seen.sender_device=e.sender_device WHERE e.recipient_device=$1 AND e.counts_as_unread AND e.sequence>COALESCE(seen.sequence,0) AND e.created_at>=r.updated_at GROUP BY sender.user_id `, recipient) if err != nil { return nil, err } defer rows.Close() counts := make(map[string]int64) for rows.Next() { var user string var count int64 if err := rows.Scan(&user, &count); err != nil { return nil, err } counts[user] = count } return counts, rows.Err() } func (s *Store) MarkSeen(ctx context.Context, recipient, sender string, sequence int64) error { tx, err := s.db.Begin(ctx) if err != nil { return err } defer tx.Rollback(ctx) if err := authorizeDelivery(ctx, tx, sender, recipient); err != nil { return err } var stored int64 err = tx.QueryRow(ctx, ` INSERT INTO device_contact_seen(recipient_device,sender_device,sequence) SELECT recipient_device,sender_device,sequence FROM device_envelopes WHERE recipient_device=$1 AND sender_device=$2 AND sequence=$3 ON CONFLICT (recipient_device,sender_device) DO UPDATE SET sequence=GREATEST(device_contact_seen.sequence,EXCLUDED.sequence) RETURNING sequence `, recipient, sender, sequence).Scan(&stored) if errors.Is(err, pgx.ErrNoRows) { return ErrUnavailable } if err != nil { return err } return tx.Commit(ctx) }