Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@noah/mega-radio

MEGA Radio (the WAKE album) for members of the MEGA.dev Discord: sign in with Kody, verify with Discord, listen with repeat.

FollowForkOpen app

Files

plays.ts

52 lines · 2.6 KB · TypeScript
/**
 * Listen counts in package storage (SQLite): a per-track total and a per-member count. Numbers only; the
 * one timestamp kept (`last_ms`, per member and track) is what enforces the rate limit. No history.
 */
import { packageStorage } from 'kody:runtime'
import { minGapMs, type Plays } from './stats.ts'

const sql = async (q: string, b: unknown[] = []) => (((await packageStorage().sql(q, b as never)) as { rows?: Record<string, unknown>[] } | null)?.rows ?? [])

let ready: Promise<void> | null = null
const schema = () =>
	(ready ??= (async () => {
		await sql('CREATE TABLE IF NOT EXISTS play_total (n INTEGER PRIMARY KEY, plays INTEGER NOT NULL)')
		await sql('CREATE TABLE IF NOT EXISTS play_user (user_id TEXT NOT NULL, n INTEGER NOT NULL, plays INTEGER NOT NULL, last_ms INTEGER NOT NULL, PRIMARY KEY (user_id, n))')
	})())

/**
 * Counts for every track, with the viewer's own.
 *
 * @param userId - the viewer's Kody user id
 * @returns track number to { total, mine }
 */
export async function loadPlays(userId: string): Promise<Record<number, Plays>> {
	await schema()
	const out: Record<number, Plays> = {}
	for (const r of await sql('SELECT n, plays FROM play_total')) out[Number(r.n)] = { total: Number(r.plays), mine: 0 }
	for (const r of await sql('SELECT n, plays FROM play_user WHERE user_id = ?', [userId])) (out[Number(r.n)] ??= { total: 0, mine: 0 }).mine = Number(r.plays)
	return out
}

/**
 * Record one play unless the same member counted this track less than about one track length ago.
 *
 * @param userId - a verified member's Kody user id
 * @param n - the track
 * @param length - its length "m:ss" (sets the rate limit)
 * @param now - ms
 * @returns whether it counted, plus the new counts
 */
export async function recordPlay(userId: string, n: number, length: string | null, now = Date.now()): Promise<{ counted: boolean } & Plays> {
	await schema()
	const [row] = await sql('SELECT plays, last_ms FROM play_user WHERE user_id = ? AND n = ?', [userId, n])
	let counted = false
	if (!row || now - Number(row.last_ms) >= minGapMs(length)) {
		await sql('INSERT INTO play_user (user_id, n, plays, last_ms) VALUES (?, ?, 1, ?) ON CONFLICT (user_id, n) DO UPDATE SET plays = plays + 1, last_ms = excluded.last_ms', [userId, n, now])
		await sql('INSERT INTO play_total (n, plays) VALUES (?, 1) ON CONFLICT (n) DO UPDATE SET plays = plays + 1', [n])
		counted = true
	}
	const [t] = await sql('SELECT plays FROM play_total WHERE n = ?', [n])
	const [u] = await sql('SELECT plays FROM play_user WHERE user_id = ? AND n = ?', [userId, n])
	return { counted, total: Number(t?.plays ?? 0), mine: Number(u?.plays ?? 0) }
}