Publish current app and server
This commit is contained in:
+151
-91
@@ -17,19 +17,80 @@ var schema string
|
||||
|
||||
// ErrNotFound is returned when a token does not match a live session.
|
||||
var ErrNotFound = errors.New("store: session not found")
|
||||
var ErrDeviceLimit = errors.New("store: device limit reached")
|
||||
|
||||
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
|
||||
LastSeenAt time.Time
|
||||
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"`
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -112,18 +173,18 @@ func (s *Store) Migrate(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateSession enforces a user's device allowance under a per-user transaction lock.
|
||||
// Re-authenticating the same stable device replaces its token and never consumes a slot.
|
||||
// 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, maxClients int) ([]byte, int, error) {
|
||||
func (s *Store) CreateSession(ctx context.Context, sess Session) ([]byte, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("store: begin session: %w", err)
|
||||
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, 0, fmt.Errorf("store: lock user sessions: %w", err)
|
||||
return nil, fmt.Errorf("store: lock user sessions: %w", err)
|
||||
}
|
||||
|
||||
var previousHash []byte
|
||||
@@ -132,26 +193,15 @@ func (s *Store) CreateSession(ctx context.Context, sess Session, maxClients int)
|
||||
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, 0, fmt.Errorf("store: find device session: %w", err)
|
||||
}
|
||||
existingDevice := err == nil
|
||||
|
||||
var activeClients int
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT count(*) FROM sessions WHERE emby_user_id = $1`,
|
||||
sess.EmbyUserID).Scan(&activeClients); err != nil {
|
||||
return nil, 0, fmt.Errorf("store: count user sessions: %w", err)
|
||||
}
|
||||
if !existingDevice && activeClients >= maxClients {
|
||||
return nil, activeClients, ErrDeviceLimit
|
||||
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_version, client_protocol, client_capabilities
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
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,
|
||||
@@ -160,30 +210,29 @@ func (s *Store) CreateSession(ctx context.Context, sess Session, maxClients int)
|
||||
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.ServerID, sess.DeviceID, sess.DeviceName, sess.ClientVersion, sess.ClientProtocol,
|
||||
sess.ClientCapabilities)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("store: create session: %w", err)
|
||||
}
|
||||
if !existingDevice {
|
||||
activeClients++
|
||||
return nil, fmt.Errorf("store: create session: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, 0, fmt.Errorf("store: commit session: %w", err)
|
||||
return nil, fmt.Errorf("store: commit session: %w", err)
|
||||
}
|
||||
return previousHash, activeClients, nil
|
||||
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, last_seen_at
|
||||
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.LastSeenAt)
|
||||
&sess.ClientProtocol, &sess.ClientCapabilities, &sess.LastSeenAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
@@ -205,15 +254,16 @@ func (s *Store) Touch(ctx context.Context, hash []byte) error {
|
||||
func (s *Store) UpdateSessionClientIdentity(
|
||||
ctx context.Context,
|
||||
hash []byte,
|
||||
version, protocol string,
|
||||
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)
|
||||
hash, version, protocol, capabilities)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -222,6 +272,66 @@ func (s *Store) DeleteSession(ctx context.Context, hash []byte) error {
|
||||
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
|
||||
}
|
||||
|
||||
// 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,
|
||||
@@ -232,53 +342,3 @@ func (s *Store) DeleteIdleSessions(ctx context.Context, idle time.Duration) (int
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
// TrimSessionsToLimit brings data created under an older, more generous policy back
|
||||
// within the current allowance. The most recently active devices survive.
|
||||
func (s *Store) TrimSessionsToLimit(ctx context.Context, maxClients int) ([]Session, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
WITH ranked AS (
|
||||
SELECT token_hash,
|
||||
row_number() OVER (
|
||||
PARTITION BY emby_user_id
|
||||
ORDER BY last_seen_at DESC, created_at DESC, token_hash DESC
|
||||
) AS device_rank
|
||||
FROM sessions
|
||||
),
|
||||
retired AS (
|
||||
DELETE FROM sessions current
|
||||
USING ranked
|
||||
WHERE current.token_hash = ranked.token_hash
|
||||
AND ranked.device_rank > $1
|
||||
RETURNING current.token_hash, current.emby_user_id, current.emby_token,
|
||||
current.username, current.server_id, current.device_id,
|
||||
current.device_name, current.client_version, current.client_protocol,
|
||||
current.last_seen_at
|
||||
)
|
||||
SELECT token_hash, emby_user_id, emby_token, username, server_id,
|
||||
device_id, device_name, client_version, client_protocol, last_seen_at
|
||||
FROM retired`,
|
||||
maxClients,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: trim sessions: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var retired []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.LastSeenAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("store: scan trimmed session: %w", err)
|
||||
}
|
||||
retired = append(retired, sess)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("store: trim sessions rows: %w", err)
|
||||
}
|
||||
return retired, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user