448 lines
15 KiB
Go
448 lines
15 KiB
Go
// Package store persists gateway sessions in Postgres.
|
|
package store
|
|
|
|
import (
|
|
"context"
|
|
_ "embed"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
//go:embed schema.sql
|
|
var schema string
|
|
|
|
// ErrNotFound is returned when a token does not match a live session.
|
|
var ErrNotFound = errors.New("store: session not found")
|
|
|
|
func isNoRows(err error) bool { return errors.Is(err, pgx.ErrNoRows) }
|
|
|
|
type Session struct {
|
|
TokenHash []byte
|
|
EmbyUserID string
|
|
EmbyToken string
|
|
Username string
|
|
ServerID string
|
|
DeviceID string
|
|
DeviceName string
|
|
ClientVersion string
|
|
ClientProtocol string
|
|
ClientCapabilities []string
|
|
LastSeenAt time.Time
|
|
}
|
|
|
|
type KnownUser struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
LastSeen time.Time `json:"lastSeen"`
|
|
}
|
|
|
|
type KnownClient struct {
|
|
DeviceName string `json:"deviceName"`
|
|
Username string `json:"username"`
|
|
Version string `json:"version"`
|
|
Protocol string `json:"protocol"`
|
|
Capabilities []string `json:"capabilities"`
|
|
LastSeen time.Time `json:"lastSeen"`
|
|
}
|
|
|
|
// MembyAccount is an account known to Memby, as opposed to an arbitrary user that
|
|
// exists only in Emby. An account exists here once it has at least one gateway session.
|
|
// Devices deliberately omit both gateway and upstream credentials.
|
|
type MembyAccount struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
LastSeen time.Time `json:"lastSeen"`
|
|
Devices []MembyDevice `json:"devices"`
|
|
RecommendationPreferences json.RawMessage `json:"-"`
|
|
}
|
|
|
|
type MembyDevice struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Version string `json:"version"`
|
|
Protocol string `json:"protocol"`
|
|
Capabilities []string `json:"capabilities"`
|
|
SignedInAt time.Time `json:"signedInAt"`
|
|
LastSeen time.Time `json:"lastSeen"`
|
|
}
|
|
|
|
// MembyAccounts returns only people who have signed in through Memby. It must not be
|
|
// confused with an Emby user directory: users that exist solely in Emby are absent.
|
|
func (s *Store) MembyAccounts(ctx context.Context) ([]MembyAccount, error) {
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT s.emby_user_id, s.username, s.device_id, s.device_name,
|
|
s.client_version, s.client_protocol, s.client_capabilities,
|
|
s.created_at, s.last_seen_at, COALESCE(o.preferences, '{}'::jsonb)
|
|
FROM sessions s
|
|
LEFT JOIN recommendation_onboarding o ON o.emby_user_id = s.emby_user_id
|
|
ORDER BY s.last_seen_at DESC, s.emby_user_id, s.device_name`)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: list Memby accounts: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
accounts := []MembyAccount{}
|
|
byID := map[string]int{}
|
|
for rows.Next() {
|
|
var userID, username string
|
|
var device MembyDevice
|
|
var preferences []byte
|
|
if err := rows.Scan(
|
|
&userID, &username, &device.ID, &device.Name, &device.Version,
|
|
&device.Protocol, &device.Capabilities, &device.SignedInAt,
|
|
&device.LastSeen, &preferences,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("store: scan Memby account: %w", err)
|
|
}
|
|
index, ok := byID[userID]
|
|
if !ok {
|
|
index = len(accounts)
|
|
byID[userID] = index
|
|
accounts = append(accounts, MembyAccount{
|
|
ID: userID, Username: username, CreatedAt: device.SignedInAt,
|
|
LastSeen: device.LastSeen, Devices: []MembyDevice{},
|
|
RecommendationPreferences: json.RawMessage(preferences),
|
|
})
|
|
}
|
|
account := &accounts[index]
|
|
if device.SignedInAt.Before(account.CreatedAt) {
|
|
account.CreatedAt = device.SignedInAt
|
|
}
|
|
if device.LastSeen.After(account.LastSeen) {
|
|
account.LastSeen = device.LastSeen
|
|
account.Username = username
|
|
}
|
|
account.Devices = append(account.Devices, device)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("store: read Memby accounts: %w", err)
|
|
}
|
|
return accounts, nil
|
|
}
|
|
|
|
// KnownClients gives the feature console compatibility evidence without exposing
|
|
// gateway or Emby credentials. Stale sessions remain useful rollout information.
|
|
func (s *Store) KnownClients(ctx context.Context) ([]KnownClient, error) {
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT device_name, username, client_version, client_protocol,
|
|
client_capabilities, last_seen_at
|
|
FROM sessions ORDER BY last_seen_at DESC LIMIT 100`)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: list known clients: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
clients := []KnownClient{}
|
|
for rows.Next() {
|
|
var client KnownClient
|
|
if err := rows.Scan(&client.DeviceName, &client.Username, &client.Version,
|
|
&client.Protocol, &client.Capabilities, &client.LastSeen); err != nil {
|
|
return nil, fmt.Errorf("store: scan known client: %w", err)
|
|
}
|
|
clients = append(clients, client)
|
|
}
|
|
return clients, rows.Err()
|
|
}
|
|
|
|
// KnownUsers returns one entry per Emby user that has signed in to the gateway.
|
|
func (s *Store) KnownUsers(ctx context.Context) ([]KnownUser, error) {
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT DISTINCT ON (emby_user_id) emby_user_id, username, last_seen_at
|
|
FROM sessions
|
|
ORDER BY emby_user_id, last_seen_at DESC`)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: list known users: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
users := []KnownUser{}
|
|
for rows.Next() {
|
|
var user KnownUser
|
|
if err := rows.Scan(&user.ID, &user.Username, &user.LastSeen); err != nil {
|
|
return nil, fmt.Errorf("store: scan known user: %w", err)
|
|
}
|
|
users = append(users, user)
|
|
}
|
|
return users, rows.Err()
|
|
}
|
|
|
|
type Store struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func Open(ctx context.Context, databaseURL string) (*Store, error) {
|
|
pool, err := pgxpool.New(ctx, databaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: connect: %w", err)
|
|
}
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("store: ping: %w", err)
|
|
}
|
|
return &Store{pool: pool}, nil
|
|
}
|
|
|
|
func (s *Store) Close() { s.pool.Close() }
|
|
|
|
func (s *Store) Ping(ctx context.Context) error { return s.pool.Ping(ctx) }
|
|
|
|
// RecordSearch stores a normalized query for future per-user ranking analysis.
|
|
func (s *Store) RecordSearch(ctx context.Context, userID, query string) error {
|
|
_, err := s.pool.Exec(ctx,
|
|
`WITH inserted AS (
|
|
INSERT INTO search_history (emby_user_id, query) VALUES ($1, $2)
|
|
RETURNING id
|
|
)
|
|
DELETE FROM search_history
|
|
WHERE emby_user_id = $1
|
|
AND occurred_at < now() - interval '30 days'`,
|
|
userID, query)
|
|
return err
|
|
}
|
|
|
|
// RecentSearches returns a user's distinct queries in most-recently-used order.
|
|
// Case-only duplicates collapse to the spelling used most recently.
|
|
func (s *Store) RecentSearches(
|
|
ctx context.Context,
|
|
userID string,
|
|
since time.Time,
|
|
limit int,
|
|
) ([]string, error) {
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT query
|
|
FROM (
|
|
SELECT DISTINCT ON (lower(query)) query, occurred_at
|
|
FROM search_history
|
|
WHERE emby_user_id = $1 AND occurred_at >= $2
|
|
ORDER BY lower(query), occurred_at DESC
|
|
) AS latest
|
|
ORDER BY occurred_at DESC
|
|
LIMIT $3`,
|
|
userID, since, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: recent searches: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
queries := make([]string, 0, limit)
|
|
for rows.Next() {
|
|
var query string
|
|
if err := rows.Scan(&query); err != nil {
|
|
return nil, fmt.Errorf("store: scan recent search: %w", err)
|
|
}
|
|
queries = append(queries, query)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("store: read recent searches: %w", err)
|
|
}
|
|
return queries, nil
|
|
}
|
|
|
|
// Migrate applies the schema. It is idempotent, so it runs on every boot.
|
|
func (s *Store) Migrate(ctx context.Context) error {
|
|
if _, err := s.pool.Exec(ctx, schema); err != nil {
|
|
return fmt.Errorf("store: migrate: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CreateSession records every signed-in TV without an account-level device cap.
|
|
// Re-authenticating the same stable device replaces its token.
|
|
// The replaced hash is returned so its Redis entry can be invalidated immediately.
|
|
func (s *Store) CreateSession(ctx context.Context, sess Session) ([]byte, error) {
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: begin session: %w", err)
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
|
|
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, sess.EmbyUserID); err != nil {
|
|
return nil, fmt.Errorf("store: lock user sessions: %w", err)
|
|
}
|
|
|
|
var previousHash []byte
|
|
err = tx.QueryRow(ctx, `
|
|
SELECT token_hash FROM sessions
|
|
WHERE emby_user_id = $1 AND device_id = $2`,
|
|
sess.EmbyUserID, sess.DeviceID).Scan(&previousHash)
|
|
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, fmt.Errorf("store: find device session: %w", err)
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO sessions (
|
|
token_hash, emby_user_id, emby_token, username, server_id, device_id, device_name,
|
|
client_version, client_protocol, client_capabilities
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
ON CONFLICT (emby_user_id, device_id) DO UPDATE SET
|
|
token_hash = EXCLUDED.token_hash,
|
|
emby_token = EXCLUDED.emby_token,
|
|
username = EXCLUDED.username,
|
|
server_id = EXCLUDED.server_id,
|
|
device_name = EXCLUDED.device_name,
|
|
client_version = EXCLUDED.client_version,
|
|
client_protocol = EXCLUDED.client_protocol,
|
|
client_capabilities = EXCLUDED.client_capabilities,
|
|
last_seen_at = now()`,
|
|
sess.TokenHash, sess.EmbyUserID, sess.EmbyToken, sess.Username,
|
|
sess.ServerID, sess.DeviceID, sess.DeviceName, sess.ClientVersion, sess.ClientProtocol,
|
|
sess.ClientCapabilities)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: create session: %w", err)
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return nil, fmt.Errorf("store: commit session: %w", err)
|
|
}
|
|
return previousHash, nil
|
|
}
|
|
|
|
func (s *Store) SessionByTokenHash(ctx context.Context, hash []byte) (Session, error) {
|
|
var sess Session
|
|
err := s.pool.QueryRow(ctx, `
|
|
SELECT token_hash, emby_user_id, emby_token, username, server_id, device_id,
|
|
device_name, client_version, client_protocol, client_capabilities, last_seen_at
|
|
FROM sessions WHERE token_hash = $1`, hash).
|
|
Scan(&sess.TokenHash, &sess.EmbyUserID, &sess.EmbyToken, &sess.Username,
|
|
&sess.ServerID, &sess.DeviceID, &sess.DeviceName, &sess.ClientVersion,
|
|
&sess.ClientProtocol, &sess.ClientCapabilities, &sess.LastSeenAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return Session{}, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return Session{}, fmt.Errorf("store: load session: %w", err)
|
|
}
|
|
return sess, nil
|
|
}
|
|
|
|
// Touch records activity. Cheap enough to call on the auth path, and it is what the
|
|
// idle-expiry sweep reads.
|
|
func (s *Store) Touch(ctx context.Context, hash []byte) error {
|
|
_, err := s.pool.Exec(ctx, `UPDATE sessions SET last_seen_at = now() WHERE token_hash = $1`, hash)
|
|
return err
|
|
}
|
|
|
|
// UpdateSessionClientIdentity remembers the last non-empty identity supplied by a TV.
|
|
// Headerless image requests can then still be attributed to the correct app build.
|
|
func (s *Store) UpdateSessionClientIdentity(
|
|
ctx context.Context,
|
|
hash []byte,
|
|
version, protocol string, capabilities []string,
|
|
) error {
|
|
_, err := s.pool.Exec(ctx, `
|
|
UPDATE sessions
|
|
SET client_version = CASE WHEN $2 <> '' THEN $2 ELSE client_version END,
|
|
client_protocol = CASE WHEN $3 <> '' THEN $3 ELSE client_protocol END,
|
|
client_capabilities = CASE WHEN cardinality($4::text[]) > 0 THEN $4 ELSE client_capabilities END,
|
|
last_seen_at = now()
|
|
WHERE token_hash = $1`,
|
|
hash, version, protocol, capabilities)
|
|
return err
|
|
}
|
|
|
|
func (s *Store) DeleteSession(ctx context.Context, hash []byte) error {
|
|
_, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash = $1`, hash)
|
|
return err
|
|
}
|
|
|
|
// SessionsForUser returns the TVs whose gateway tokens are still active for a user.
|
|
func (s *Store) SessionsForUser(ctx context.Context, userID string) ([]Session, error) {
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT token_hash, emby_user_id, emby_token, username, server_id, device_id,
|
|
device_name, client_version, client_protocol, client_capabilities, last_seen_at
|
|
FROM sessions
|
|
WHERE emby_user_id = $1
|
|
ORDER BY last_seen_at DESC, device_name`, userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: list user sessions: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
var sessions []Session
|
|
for rows.Next() {
|
|
var sess Session
|
|
if err := rows.Scan(
|
|
&sess.TokenHash, &sess.EmbyUserID, &sess.EmbyToken, &sess.Username,
|
|
&sess.ServerID, &sess.DeviceID, &sess.DeviceName, &sess.ClientVersion,
|
|
&sess.ClientProtocol, &sess.ClientCapabilities, &sess.LastSeenAt,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("store: scan user session: %w", err)
|
|
}
|
|
sessions = append(sessions, sess)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("store: list user session rows: %w", err)
|
|
}
|
|
return sessions, nil
|
|
}
|
|
|
|
// DeleteUserDevice revokes one device while scoping the delete to the authenticated user.
|
|
func (s *Store) DeleteUserDevice(ctx context.Context, userID, deviceID string) ([]byte, error) {
|
|
var tokenHash []byte
|
|
err := s.pool.QueryRow(ctx, `
|
|
DELETE FROM sessions
|
|
WHERE emby_user_id = $1 AND device_id = $2
|
|
RETURNING token_hash`, userID, deviceID).Scan(&tokenHash)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: delete user device: %w", err)
|
|
}
|
|
return tokenHash, nil
|
|
}
|
|
|
|
// DeleteUserSessions removes the Memby account's active gateway access while leaving
|
|
// the upstream Emby user untouched.
|
|
func (s *Store) DeleteUserSessions(ctx context.Context, userID string) ([][]byte, error) {
|
|
rows, err := s.pool.Query(ctx, `
|
|
DELETE FROM sessions WHERE emby_user_id = $1 RETURNING token_hash`, userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: delete user sessions: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
hashes := [][]byte{}
|
|
for rows.Next() {
|
|
var hash []byte
|
|
if err := rows.Scan(&hash); err != nil {
|
|
return nil, fmt.Errorf("store: scan deleted session: %w", err)
|
|
}
|
|
hashes = append(hashes, hash)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("store: read deleted sessions: %w", err)
|
|
}
|
|
if len(hashes) == 0 {
|
|
return nil, ErrNotFound
|
|
}
|
|
return hashes, nil
|
|
}
|
|
|
|
// RenameUserDevice changes only the display name and keeps the session/token intact.
|
|
func (s *Store) RenameUserDevice(ctx context.Context, userID, deviceID, deviceName string) error {
|
|
tag, err := s.pool.Exec(ctx, `
|
|
UPDATE sessions SET device_name = $3
|
|
WHERE emby_user_id = $1 AND device_id = $2`, userID, deviceID, deviceName)
|
|
if err != nil {
|
|
return fmt.Errorf("store: rename user device: %w", err)
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteIdleSessions retires tokens unused for longer than idle, returning how many went.
|
|
func (s *Store) DeleteIdleSessions(ctx context.Context, idle time.Duration) (int64, error) {
|
|
tag, err := s.pool.Exec(ctx,
|
|
`DELETE FROM sessions WHERE last_seen_at < now() - $1::interval`,
|
|
fmt.Sprintf("%d seconds", int64(idle.Seconds())))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return tag.RowsAffected(), nil
|
|
}
|