31 Commits
Author SHA1 Message Date
apt-get 3aae8a0130 yay accessibility!
aria tags + better touchscreen support
2026-09-25 21:50:00 +02:00
apt-get 83cc73acff add varying intensity to stream tags
plus improving the tag select dropdown in general
2026-09-25 21:26:31 +02:00
apt-get c49fb9bb54 upgrade svelte-select to v6 2026-09-25 14:25:00 +02:00
apt-get b8f1a1aa73 update frontpage msg 2026-09-06 02:32:28 +02:00
apt-get 3c42834d47 display cache usage and warn if not enough disk space available 2026-09-06 02:23:06 +02:00
apt-get 343447c37c delete done parts during assembly to prevent needing double the stream size as available disk space 2026-09-05 03:27:39 +02:00
apt-get 0ed1a094a2 don't hold 2x stream size while reassembling 2026-09-02 20:51:58 +02:00
apt-get 828c0a1d7b add some logging... 2026-09-02 20:43:40 +02:00
apt-get 771e81f50b insert into db script fixes 2026-09-02 20:33:23 +02:00
apt-get 65fc04a4d8 more linter fixes 2026-09-02 20:21:24 +02:00
apt-get 39593d470d decrease chunk size to 4MB, fix more potential breakages 2026-09-02 20:18:42 +02:00
apt-get c038316461 fix linter nitpicks 2026-09-02 19:04:43 +02:00
apt-get e98293fa7c guard around potential crashes 2026-09-02 18:38:38 +02:00
apt-get 9c3fd4c1a2 formatting pass 2026-09-02 18:23:22 +02:00
apt-get d7999785c8 partial download support for stream caching, better error handling 2026-09-02 18:23:16 +02:00
apt-get 62af3683a4 Put stream in downloading map on click rather than on dl start
prevents network issue race conditions
2026-09-02 14:25:16 +02:00
apt-get 7a052c4e68 formatting fix 2026-03-17 01:27:13 +01:00
apt-get 1c7736f832 cleanup svelte legacy APIs and stuff 2026-03-17 01:27:07 +01:00
apt-get 64681befad replace carta with bun's own api 2026-03-17 01:26:52 +01:00
apt-get 090a145211 add previous/next track button handling 2026-03-17 00:05:44 +01:00
apt-get 1dc3f4505b fix seeking problems due to progress bar width inconsistency 2026-03-16 23:21:00 +01:00
apt-get 7febb497e9 update homepage message 2026-03-16 20:38:35 +01:00
apt-get 6c12cfd49b Merge branch 'offline-mode' 2026-03-16 20:33:03 +01:00
apt-get 3aa762d544 add stream caching ("offline mode") 2026-03-16 20:32:33 +01:00
apt-get 8573b82515 more ts switches, use setcontext instead of stores 2026-03-15 17:20:16 +01:00
apt-get b47a433414 update packages 2026-03-15 17:18:43 +01:00
apt-get 4d8f7c2b02 add types 2026-03-15 14:50:56 +01:00
apt-get f777873432 work around opus bug 2026-02-20 16:21:22 +01:00
apt-get 347438928a use SvelteSet instead of Set for favoritedStreams 2025-07-06 22:31:55 +02:00
apt-get dc84db8c79 don't bind volume to audio element 2025-06-30 13:11:29 +02:00
apt-get 7978ea5b37 update build command 2025-05-25 01:43:08 +02:00
32 changed files with 1613 additions and 5421 deletions
+241 -599
View File
File diff suppressed because it is too large Load Diff
+40 -27
View File
@@ -22,49 +22,62 @@ const lookup = {
tracks: 'tracks'
};
// Retrieve existing IDs from Stream
const existingIds = db.prepare('SELECT id FROM Stream').all().map(row => row.id);
// Create a set of existing IDs for efficient lookup
const idSet = new Set(existingIds);
const existingRow = db.prepare('SELECT * FROM Stream WHERE id = ?');
// Check if --overwrite flag is set
// Overwrite differing streams without asking
const shouldOverwrite = process.argv.includes('--overwrite');
// Process JSON files and insert data into Stream
fs.readdir(jsonFolder, (err, files) => {
if (err) throw err;
const files = fs.readdirSync(jsonFolder);
console.log(`Found ${files.length} JSON file(s) in ${jsonFolder}.`);
files.forEach((file) => {
if (!file.endsWith('.json')) return;
if (file.endsWith('.sideload.json')) return;
for (const file of files) {
if (!file.endsWith('.json')) continue;
if (file.endsWith('.sideload.json')) continue;
const jsonString = fs.readFileSync(path.join(jsonFolder, file), 'utf8');
let jsonData = JSON.parse(jsonString);
const sideloadPath = path.join(jsonFolder, file.slice(0, -5) + '.sideload.json');
if (fs.existsSync(sideloadPath, 'utf8')) {
if (fs.existsSync(sideloadPath)) {
const sideloadData = JSON.parse(fs.readFileSync(sideloadPath));
jsonData = { ...jsonData, ...sideloadData };
}
// Skip if ID already exists in Stream
if (idSet.has(jsonData.id)) {
if (!shouldOverwrite) {
console.log(`Skipped data for ID ${jsonData.id} (already exists).`);
return;
}
console.log(`Overwriting data for ID ${jsonData.id}.`);
}
// A key with no column would otherwise reach the query as `undefined`
const unknown = Object.keys(jsonData).filter((key) => !(key in lookup));
if (unknown.length > 0)
console.log(`Ignored unknown key(s) in ${file}: ${unknown.join(', ')}.`);
// Prepare attributes for insertion
const values = Object.keys(jsonData).map(
// Serialize value if array
(key) => (Array.isArray(jsonData[key]) ? JSON.stringify(jsonData[key]) : jsonData[key])
);
const columns = Object.keys(jsonData).map((key) => lookup[key]);
const fields = Object.entries(jsonData)
.filter(([key]) => key in lookup)
// Serialize value if array or object
.map(([key, value]) => [
lookup[key],
typeof value === 'object' && value !== null ? JSON.stringify(value) : value
]);
const row = existingRow.get(jsonData.id);
if (row) {
const changed = fields
.filter(([column, value]) => String(row[column] ?? '') !== String(value ?? ''))
.map(([column]) => column);
if (changed.length === 0) {
console.log(`Unchanged data for ID ${jsonData.id}.`);
continue;
}
console.log(`ID ${jsonData.id} differs from the database in: ${changed.join(', ')}.`);
if (!shouldOverwrite && !confirm(`Overwrite ID ${jsonData.id}?`)) {
console.log(`Kept database version of ID ${jsonData.id}.`);
continue;
}
}
const columns = fields.map(([column]) => column);
const sql = `INSERT OR REPLACE INTO Stream (${columns.join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;
db.prepare(sql).run(...values);
db.prepare(sql).run(...fields.map(([, value]) => value));
console.log(`Inserted data for ID ${jsonData.id}.`);
});
});
}
-4327
View File
File diff suppressed because it is too large Load Diff
+21 -22
View File
@@ -4,7 +4,7 @@
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build && node ./scripts/create_media_symlink.js",
"build": "vite build && bun --bun run ./scripts/create_media_symlink.js",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
@@ -15,33 +15,32 @@
"generate_iconfont_subset": "cd scripts && bash ./generate_iconfont_subset.sh"
},
"dependencies": {
"@sveltejs/kit": "^2.17.1",
"@types/bun": "^1.2.2",
"@types/node": "^20.17.17",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"carta-md": "^4.6.7",
"dotenv": "^16.4.7",
"eslint": "^8.57.1",
"eslint-config-prettier": "^8.10.0",
"eslint-plugin-svelte": "^2.46.1",
"@sveltejs/kit": "^2.55.0",
"@types/bun": "^1.3.10",
"@types/node": "^25.5.0",
"@typescript-eslint/eslint-plugin": "^8.57.0",
"@typescript-eslint/parser": "^8.57.0",
"dotenv": "^16.6.1",
"eslint": "^10.0.3",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.15.2",
"fontkit": "^2.0.4",
"isomorphic-dompurify": "^2.21.0",
"prettier": "^3.4.2",
"prettier-plugin-svelte": "^3.3.3",
"prettier": "^3.8.1",
"prettier-plugin-svelte": "^3.5.1",
"sqids": "0.3.0",
"svelte": "^5.19.9",
"svelte-check": "^4.1.4",
"svelte-select": "^5.8.3",
"svelte": "^5.53.12",
"svelte-check": "^4.4.5",
"svelte-select": "^6",
"tslib": "^2.8.1",
"typescript": "^5.7.3",
"vite": "^5.4.14"
"typescript": "^5.9.3",
"vite": "^8.0.0"
},
"type": "module",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^4.0.4",
"svelte-adapter-bun": "https://github.com/gornostay25/svelte-adapter-bun",
"typescript-svelte-plugin": "^0.3.45"
"@sveltejs/adapter-node": "^5.5.4",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"svelte-adapter-bun": "^1.0.1",
"typescript-svelte-plugin": "^0.3.50"
},
"trustedDependencies": [
"svelte-adapter-bun"
+1
View File
@@ -8,6 +8,7 @@ fontFile="$(basename "$fontUrl")"
unicodePoints=(
"61-7a,5f" # ascii lowercase + underscore
"e2c4" # file_download
"e872" # delete
"e037" # play_arrow
"e034" # pause
"e04f" # volume_off
+1
View File
@@ -1,3 +1,4 @@
/// <reference lib="dom.asynciterable" />
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
+44
View File
@@ -0,0 +1,44 @@
<script lang="ts">
import { TAG_WEIGHT_NAMES } from '$lib/stores.svelte.ts';
import type { TagWeights } from '$lib/types';
let { tags, highlighted = {} }: { tags: TagWeights; highlighted?: Record<string, number> } =
$props();
let sorted = $derived(Object.entries(tags).sort((a, b) => b[1] - a[1]));
</script>
{#each sorted as [tag, weight], i}{i ? ', ' : ''}<span
class="weight-{weight}"
class:highlighted={tag in highlighted}
>{tag}<span class="screen-reader-only"> ({TAG_WEIGHT_NAMES[weight]})</span></span
>{/each}
<style>
.weight-1 {
font-weight: normal;
}
.weight-2 {
font-weight: bold;
}
.weight-3 {
font-weight: bold;
text-decoration: underline;
}
/* translucent to take on the hover/selected bg colour tint */
.highlighted {
background: rgba(255, 220, 0, 0.18);
}
.screen-reader-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
</style>
-36
View File
@@ -1,36 +0,0 @@
import { Database } from 'bun:sqlite';
const dbName = './db/strimserve.db';
// Create a new database object and initialize it with the schema
const db = new Database(dbName);
export function getStreams() {
const indexData = db
.prepare(
'SELECT id, stream_date, title, tags, length_seconds ' + 'FROM Stream ORDER BY id DESC'
)
.all();
indexData.forEach((stream) => {
stream['stream_date'] = Date.parse(stream['stream_date']);
stream['tags'] = JSON.parse(stream['tags']);
});
return indexData;
}
export function getStreamInfo(streamId) {
const streamData = db
.prepare(
'SELECT id, stream_date, filename, ' +
'format, title, description, tags, ' +
'length_seconds, tracks FROM Stream ' +
'WHERE id = ?'
)
.get(streamId);
if (streamData) {
streamData['stream_date'] = Date.parse(streamData['stream_date']);
streamData['tracks'] = JSON.parse(streamData['tracks']);
streamData['tags'] = JSON.parse(streamData['tags']);
}
return streamData;
}
+47
View File
@@ -0,0 +1,47 @@
import { Database } from 'bun:sqlite';
import type { Stream, StreamSummary } from './types.ts';
const dbName = './db/strimserve.db';
// Create a new database object and initialize it with the schema
const db = new Database(dbName);
export function getStreams(): StreamSummary[] {
const indexData = db
.prepare(
'SELECT id, stream_date, filename, title, tags, length_seconds ' +
'FROM Stream ORDER BY id DESC'
)
.all() as Record<string, unknown>[];
return indexData.map((stream) => ({
id: stream.id as string,
stream_date: Date.parse(stream.stream_date as string),
filename: stream.filename as string,
title: stream.title as string | null,
tags: stream.tags ? JSON.parse(stream.tags as string) : {},
length_seconds: stream.length_seconds as number
}));
}
export function getStreamInfo(streamId: string): Stream | null {
const streamData = db
.prepare(
'SELECT id, stream_date, filename, ' +
'format, title, description, tags, ' +
'length_seconds, tracks FROM Stream ' +
'WHERE id = ?'
)
.get(streamId) as Record<string, unknown> | null;
if (!streamData) return null;
return {
id: streamData.id as string,
stream_date: Date.parse(streamData.stream_date as string),
filename: streamData.filename as string,
format: streamData.format as string,
title: streamData.title as string | null,
description: streamData.description as string | null,
tags: streamData.tags ? JSON.parse(streamData.tags as string) : {},
length_seconds: streamData.length_seconds as number,
tracks: JSON.parse(streamData.tracks as string)
};
}
-85
View File
@@ -1,85 +0,0 @@
import { writable, get } from 'svelte/store';
import { browser } from '$app/environment';
export const currentStream = writable({});
export const currentSongIndex = writable(null);
export const favoritedStreams = writable(
new Set(JSON.parse((browser && localStorage.getItem('favoritedStreams')) || '[]'))
);
if (browser) {
favoritedStreams.subscribe((val) => {
localStorage.setItem('favoritedStreams', JSON.stringify(Array.from(val)));
});
}
export const tagList = [
'acoustic',
'electronic',
'orchestral',
'rock',
'pop',
'metal',
'aggressive',
'folk',
'jazzy',
'dance.music',
'untz',
'breakbeats',
'electronica',
'chiptune',
'left.field',
'denpa',
'vocaloid',
'funky',
'lush',
'noisy',
'psychedelic',
'dark',
'calm',
'moody',
'uplifting'
];
let timestampList;
// utility
function locationOf(element, array, start, end) {
start = start || 0;
end = end || array.length;
var pivot = parseInt(start + (end - start) / 2, 10);
if (end - start <= 1 || array[pivot] === element) return pivot;
if (array[pivot] < element) {
return locationOf(element, array, pivot, end);
} else {
return locationOf(element, array, start, pivot);
}
}
// exported methods
export function getSongAtTime(currentTime) {
return locationOf(currentTime, timestampList) - 1;
}
// less operations needed when doing regular lookups
export function updateCurrentSong(currentTime, songIndex) {
function updateCurrentSongRecurse(songIndex) {
if (currentTime >= timestampList[songIndex + 2]) {
return updateCurrentSongRecurse(songIndex + 1);
} else if (currentTime < timestampList[songIndex + 1]) {
return updateCurrentSongRecurse(songIndex - 1);
}
return songIndex;
}
currentSongIndex.set(updateCurrentSongRecurse(songIndex));
}
export function updateCurrentStream(stream) {
currentStream.set(stream);
timestampList = [-Infinity, ...stream.tracks.map((track) => track[0]), Infinity];
currentSongIndex.set(0);
}
+40
View File
@@ -0,0 +1,40 @@
import { SvelteSet } from 'svelte/reactivity';
import { readStored, writeStored } from './utils.ts';
export const favoritedStreams = new SvelteSet<string>(readStored('favoritedStreams', []));
$effect.root(() => {
$effect(() => {
writeStored('favoritedStreams', Array.from(favoritedStreams));
});
});
export const MAX_TAG_WEIGHT = 3;
export const TAG_WEIGHT_NAMES = ['off', 'light', 'medium', 'heavy'];
export const tagList = [
'acoustic',
'electronic',
'orchestral',
'rock',
'pop',
'metal',
'aggressive',
'folk',
'jazzy',
'dance.music',
'untz',
'breakbeats',
'electronica',
'chiptune',
'left.field',
'denpa',
'vocaloid',
'funky',
'lush',
'noisy',
'psychedelic',
'dark',
'calm',
'moody',
'uplifting'
];
+253
View File
@@ -0,0 +1,253 @@
import { browser } from '$app/environment';
import { SvelteSet, SvelteMap } from 'svelte/reactivity';
import { readStored, writeStored } from './utils.ts';
import type { StreamSummary, PartialDownload } from './types.ts';
const STORAGE_KEY = 'cachedStreams';
const PARTIALS_KEY = 'partialStreams';
const PARTS_DIR = 'parts';
// MAX_ATTEMPTS is consecutive attempts that acquired zero chunks, so the exponential
// backoff below tolerates roughly 8 minutes of outage before giving up
const MAX_ATTEMPTS = 8;
const CHUNK_SIZE = 4 * 1024 * 1024;
// 60s as the limit for downloading one chunk is a reasonable guess
// as the intent is to catch socket breakage during cellular network changes for example
const CHUNK_TIMEOUT = 60_000;
class QuotaError extends Error {
constructor(readonly missing: number) {
super();
}
}
// total bytes used by our OPFS origin
export const usage = $state<{ bytes?: number }>({});
export const cached = new SvelteSet<string>(readStored<string[]>(STORAGE_KEY, []));
export const downloading = new SvelteMap<string, number>();
// bytes already written to OPFS for each incomplete download
export const partials = new SvelteMap<string, PartialDownload>(
Object.entries(readStored<Record<string, PartialDownload>>(PARTIALS_KEY, {}))
);
if (browser) {
refreshUsage();
$effect.root(() => {
$effect(() => {
writeStored(STORAGE_KEY, [...cached]);
});
$effect(() => {
writeStored(PARTIALS_KEY, Object.fromEntries(partials));
});
});
}
export async function download(stream: StreamSummary) {
if (downloading.has(stream.id) || cached.has(stream.id)) return;
const resumed = partials.get(stream.id);
downloading.set(stream.id, percent(resumed?.received ?? 0, resumed?.total ?? 0));
try {
let attempt = 0;
while (true) {
const before = partials.get(stream.id)?.received ?? 0;
try {
await attemptDownload(stream);
partials.delete(stream.id);
cached.add(stream.id);
return;
} catch (err) {
if (err instanceof QuotaError) {
alert(
`not enough disk space ;_;, need ${Math.ceil(err.missing / 1_000_000)} MB more.`
);
return;
}
console.error(`[streamCache] ${stream.id} attempt failed`, err);
// reset attempts if download of at least one chunk successful
attempt = (partials.get(stream.id)?.received ?? 0) > before ? 0 : attempt + 1;
if (attempt === MAX_ATTEMPTS) return;
}
await waitForRetry(attempt);
}
} finally {
downloading.delete(stream.id);
}
}
export async function remove(streamId: string) {
cached.delete(streamId);
await discard(streamId);
}
export async function getUrl(streamId: string): Promise<string | null> {
if (!cached.has(streamId)) return null;
try {
const root = await navigator.storage.getDirectory();
const handle = await root.getFileHandle(streamId);
const file = await handle.getFile();
return URL.createObjectURL(file);
} catch {
cached.delete(streamId);
return null;
}
}
async function attemptDownload(stream: StreamSummary) {
let state = partials.get(stream.id);
let checkedSpace = false;
while (!state || state.received < state.total) {
state = await fetchChunk(stream, state);
partials.set(stream.id, state);
downloading.set(stream.id, percent(state.received, state.total));
// first chunk's HTTP response carries the total stream size
if (!checkedSpace) {
await checkSpace(stream.id, state);
checkedSpace = true;
}
}
console.log(`[streamCache] ${stream.id} assembling ${state.total} bytes`);
await assemble(stream.id, state.total);
console.log(`[streamCache] ${stream.id} assembled`);
}
/** check available space below what's needed to download the stream */
async function checkSpace(streamId: string, state: PartialDownload) {
const { usage: used, quota } = await navigator.storage.estimate();
if (used === undefined || quota === undefined) return;
// extra CHUNK_SIZE is due to the delta in `assemble()` merging one chunk in (+1) then deleting it
const peak = used + (state.total - state.received) + CHUNK_SIZE;
if (peak > quota) throw new QuotaError(peak - quota);
}
/** fetch chunk starting from the last valid one, store in OPFS, and return updated state */
async function fetchChunk(stream: StreamSummary, state?: PartialDownload) {
const start = state?.received ?? 0;
const headers = new Headers({ Range: `bytes=${start}-${start + CHUNK_SIZE - 1}` });
// attach existing ETag to the request
if (state?.etag) headers.set('If-Range', state.etag);
const res = await fetch(`/media/tracks/${stream.filename}`, {
headers,
signal: AbortSignal.timeout(CHUNK_TIMEOUT)
});
// 200 means the range was ignored or the file changed (different ETag)
// 416 that our start offset is past its end
// anything else can be transient, so the chunks already on disk are kept
if (res.status !== 206) {
if (res.status === 200 || res.status === 416) await discard(stream.id);
throw new Error(`Download failed: ${res.status}`);
}
const total = Number(res.headers.get('content-range')?.split('/')[1]);
if (!total) throw new Error('Malformed Content-Range');
const etag = res.headers.get('etag') ?? res.headers.get('last-modified');
if (state && state.total !== total) {
await discard(stream.id);
throw new Error('File changed while downloading');
}
const bytes = await res.arrayBuffer();
const dir = await partsDir(stream.id, true);
const handle = await dir.getFileHandle(String(start), { create: true });
const writable = await handle.createWritable();
await writable.write(bytes);
await writable.close();
return { received: start + bytes.byteLength, total, etag };
}
/** concatenate stream file once all the parts are downloaded */
async function assemble(streamId: string, total: number) {
const root = await navigator.storage.getDirectory();
const dir = await partsDir(streamId, true);
const handle = await root.getFileHandle(streamId, { create: true });
// track size from previous assembling attempt if there was one
const done = (await handle.getFile()).size;
const writable = await handle.createWritable({ keepExistingData: done > 0 });
await writable.seek(done);
// check at each step the chunk names (ranges) are coherent
let written = done;
while (written < total) {
const name = String(written);
const part = await dir.getFileHandle(name).catch(() => null);
if (!part) break;
const file = await part.getFile();
if (!file.size) break;
await writable.write(file);
written += file.size;
await dir.removeEntry(name).catch(() => {});
}
await writable.close();
partials.delete(streamId);
await sweep(streamId);
// chunks went missing, shit's fucked...
if (written !== total) throw new Error(`Assembled ${written} of ${total} bytes`);
}
/** returns directory handle dedicated to partial downloads of given stream id */
async function partsDir(streamId: string, create = false) {
const root = await navigator.storage.getDirectory();
const parts = await root.getDirectoryHandle(PARTS_DIR, { create });
return parts.getDirectoryHandle(streamId, { create });
}
/** discard everything on disk for a stream that is not fully downloaded */
async function discard(streamId: string) {
partials.delete(streamId);
const root = await navigator.storage.getDirectory();
await root.removeEntry(streamId).catch(() => {});
await sweep(streamId);
}
/** remove unreferenced chunk directories (that aren't still downloading)
* `force` is there for `discard()` to use as an escape hatch, otherwise it'd be caught in
* the guard condition due to still being in `downloading` by then
*/
async function sweep(force?: string) {
const root = await navigator.storage.getDirectory();
const parts = await root.getDirectoryHandle(PARTS_DIR, { create: true });
const orphans: string[] = [];
for await (const name of parts.keys()) {
if (partials.has(name)) continue;
if (downloading.has(name) && name !== force) continue;
orphans.push(name);
}
for (const name of orphans) await parts.removeEntry(name, { recursive: true }).catch(() => {});
await refreshUsage();
}
async function refreshUsage() {
usage.bytes = (await navigator.storage.estimate()).usage;
}
/** exponential backoff, cut short if the connection comes back before it elapses */
function waitForRetry(attempt: number) {
return new Promise<void>((resolve) => {
const done = () => {
removeEventListener('online', done);
clearTimeout(timer);
resolve();
};
const timer = setTimeout(done, 2 ** attempt * 1000);
addEventListener('online', done);
});
}
function percent(received: number, total: number) {
return total ? Math.round((received / total) * 100) : 0;
}
+48
View File
@@ -0,0 +1,48 @@
import { createContext } from 'svelte';
import type { Stream, StreamSummary } from './types.ts';
export class StreamContext {
streams: StreamSummary[];
current = $state<Stream | null>(null);
songIndex = $state<number | null>(null);
#timestamps: number[] = [];
constructor(streams: StreamSummary[]) {
this.streams = streams;
}
setCurrent(stream: Stream) {
this.current = stream;
this.#timestamps = [-Infinity, ...stream.tracks.map((t) => t[0]), Infinity];
this.songIndex = 0;
}
clearCurrent() {
this.current = null;
this.songIndex = null;
}
getSongAtTime(time: number): number {
return Math.max(this.#locationOf(time, this.#timestamps) - 1, 0);
}
updateCurrentSong(currentTime: number, songIndex: number) {
const ts = this.#timestamps;
// the first track need not start at 0, so descending past index 0 is possible
const recurse = (idx: number): number => {
if (currentTime >= ts[idx + 2]) return recurse(idx + 1);
if (idx > 0 && currentTime < ts[idx + 1]) return recurse(idx - 1);
return idx;
};
this.songIndex = recurse(songIndex);
}
#locationOf(element: number, array: number[], start = 0, end = array.length): number {
const pivot = Math.floor(start + (end - start) / 2);
if (end - start <= 1 || array[pivot] === element) return pivot;
if (array[pivot] < element) return this.#locationOf(element, array, pivot, end);
return this.#locationOf(element, array, start, pivot);
}
}
export const [getStreamContext, setStreamContext] = createContext<StreamContext>();
+31
View File
@@ -0,0 +1,31 @@
/** A track entry: [timestamp_seconds, artist, title] */
export type Track = [number, string, string];
// tag -> weight, 1 (light) to 3 (heavy)
export type TagWeights = Record<string, number>;
/** The summary shape used in sidebar listings. */
export interface StreamSummary {
id: string;
stream_date: number;
filename: string;
title: string | null;
tags: TagWeights;
length_seconds: number;
}
/** The full stream shape used on the detail/player page. */
export interface Stream extends StreamSummary {
format: string;
description: string | null;
// rendered at page load, so absent straight out of the database
descriptionHtml?: string;
tracks: Track[];
}
/** Partial stream downloads, as well as associated etag for cache validation. */
export interface PartialDownload {
received: number;
total: number;
etag: string | null;
}
-37
View File
@@ -1,37 +0,0 @@
import Sqids from 'sqids';
let sqids = new Sqids({ minLength: 6, alphabet: 'abcdefghijklmnopqrstuvwxyz0123456789' });
export function hashcode(str) {
for (var i = 0, h = 9; i < str.length; ) h = Math.imul(h ^ str.charCodeAt(i++), 9 ** 9);
return h ^ (h >>> 9);
}
// for mnemonic display
export function shorthandCode(str) {
return sqids.encode([hashcode(str) & 0xffff]);
}
// for tag display
export function hashColor(str) {
const hash = hashcode(str);
return `hsl(${hash % 360}, ${65 + (hash % 30) + 1}%, ${85 + (hash % 10) + 1}%)`;
}
export function formatSecondsToHms(s) {
s = Number(s);
var h = Math.floor(s / 3600);
var m = Math.ceil((s % 3600) / 60);
var hDisplay = h > 0 ? h + (h == 1 ? ' hr' : ' hrs') + (m > 0 ? ', ' : '') : '';
var mDisplay = m > 0 ? m + (m == 1 ? ' min' : ' mins') : '';
return hDisplay + mDisplay;
}
export function formatDate(unix_timestamp) {
return new Date(unix_timestamp).toISOString().split('T')[0];
}
export function formatTrackTime(s) {
return new Date(s * 1000).toISOString().slice(11, 19);
}
+57
View File
@@ -0,0 +1,57 @@
import { browser } from '$app/environment';
import Sqids from 'sqids';
const sqids = new Sqids({ minLength: 6, alphabet: 'abcdefghijklmnopqrstuvwxyz0123456789' });
// browser blocks site data => localStorage throws
// so we're wrapping our calls to ensure things running at module init
// don't bring down the site render entirely
export function readStored<T>(key: string, fallback: T): T {
if (!browser) return fallback;
try {
return (JSON.parse(localStorage.getItem(key) ?? '') as T) ?? fallback;
} catch {
return fallback;
}
}
export function writeStored(key: string, value: unknown) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {}
}
export function hashcode(str: string): number {
let h = 9;
for (let i = 0; i < str.length; ) h = Math.imul(h ^ str.charCodeAt(i++), 9 ** 9);
return h ^ (h >>> 9);
}
// for mnemonic display
export function shorthandCode(str: string): string {
return sqids.encode([hashcode(str) & 0xffff]);
}
// for tag display
export function hashColor(str: string): string {
const hash = hashcode(str);
return `hsl(${hash % 360}, ${65 + (hash % 30) + 1}%, ${85 + (hash % 10) + 1}%)`;
}
export function formatSecondsToHms(s: number): string {
s = Number(s);
const h = Math.floor(s / 3600);
const m = Math.ceil((s % 3600) / 60);
const hDisplay = h > 0 ? h + (h == 1 ? ' hr' : ' hrs') + (m > 0 ? ', ' : '') : '';
const mDisplay = m > 0 ? m + (m == 1 ? ' min' : ' mins') : '';
return hDisplay + mDisplay;
}
export function formatDate(unix_timestamp: number): string {
return new Date(unix_timestamp).toISOString().split('T')[0];
}
export function formatTrackTime(s: number): string {
return new Date(s * 1000).toISOString().slice(11, 19);
}
+4
View File
@@ -8,6 +8,10 @@
<svelte:head>
<style>
:root {
--accent: #add8e6;
}
body,
html {
margin: 0;
+1 -1
View File
@@ -1,4 +1,4 @@
import { getStreams } from '$lib/database.js';
import { getStreams } from '$lib/database.ts';
export function load() {
return {
+8 -2
View File
@@ -1,11 +1,17 @@
<script lang="ts">
import Sidebar from './Sidebar.svelte';
import Footer from './Footer.svelte';
let { data, children } = $props();
import { untrack } from 'svelte';
import { setStreamContext, StreamContext } from '$lib/streamContext.svelte.ts';
// streams are grabbed from the server here, then accessed throughout the rest
// of the components through the svelte context api
const { data, children } = $props();
setStreamContext(new StreamContext(untrack(() => data.streams)));
</script>
<div id="mainContainer">
<div id="sidebar" class="panel"><Sidebar streams={data.streams} /></div>
<div id="sidebar" class="panel"><Sidebar /></div>
<div id="footer" class="panel-alt"><Footer /></div>
<div id="content">{@render children?.()}</div>
</div>
-1
View File
@@ -38,7 +38,6 @@
a,
a:visited {
outline: none;
color: black;
}
</style>
+237 -49
View File
@@ -1,87 +1,154 @@
<script lang="ts">
import { untrack } from 'svelte';
import { goto } from '$app/navigation';
import { currentStream, favoritedStreams } from '$lib/stores.js';
import { hashColor, shorthandCode, formatSecondsToHms, formatDate } from '$lib/utils.js';
import { favoritedStreams, tagList, MAX_TAG_WEIGHT } from '$lib/stores.svelte.ts';
import * as streamCache from '$lib/streamCache.svelte.ts';
import { getStreamContext } from '$lib/streamContext.svelte.ts';
import type { StreamSummary } from '$lib/types';
import { shorthandCode, formatSecondsToHms, formatDate } from '$lib/utils.ts';
import TagSelect from './TagSelect.svelte';
import WeightedTags from '$lib/components/WeightedTags.svelte';
let { streams } = $props();
let filteredTags = $state([]);
const ctx = getStreamContext();
// map of tag -> minimum weight
// a stream shows if it has every tag with at least the minimum weight
let filteredTags: Record<string, number> = $state({});
let favoritesOnly = $state(false);
let listOpen = $state();
let cachedOnly = $state(false);
let listOpen = $state(false);
let displayedStreams = $derived.by(streamsToDisplay);
let remainingTags = $derived.by(getRemainingTags);
// how many displayed streams have each unselected tag, at each weight?
// used in the tag select dropdown
let dropdownCounts = $derived.by(getDropdownCounts);
// how many displayed streams would be shown
// if filtered per each of this tag's weights,
// all other filters unchanged?
// used for the selected tag pills
let pillCounts = $derived.by(getPillCounts);
// which tags can still alter the displayed streams if selected?
// we eliminate either those which aren't present in the displayed streams
// or those present (at the same weight) in every displayed stream
// decides which tags are visible in the selection dropdown
let remainingTags = $derived(
Object.keys(dropdownCounts).filter((tag) =>
dropdownCounts[tag].some((count) => count > 0 && count < displayedStreams.size)
)
);
let cacheUsage = $derived(streamCache.usage.bytes);
$effect(() => {
if (displayedStreams.length == 1) {
listOpen = untrack(() => !listOpen);
if (displayedStreams.size == 1) {
listOpen = false;
}
});
function matchesFilter(stream: StreamSummary, filters: Record<string, number>) {
return Object.entries(filters).every(([tag, min]) => (stream.tags[tag] ?? 0) >= min);
}
function streamsToDisplay() {
return streams.filter(
(stream) =>
!('tags' in stream) || filteredTags.every((tag) => stream['tags'].includes(tag))
return new Set(ctx.streams.filter((stream) => matchesFilter(stream, filteredTags)));
}
// how many of these streams have the tag at weight 1+, 2+ and 3+
// e.g. dark at weights [1, 3, 3, None] on four streams gives [3, 2, 2]
function weightCounts(streams: Iterable<StreamSummary>, tag: string) {
const counts = new Array(MAX_TAG_WEIGHT).fill(0);
for (const stream of streams) {
const weight = stream.tags[tag] ?? 0;
for (let i = 0; i < weight; i++) counts[i]++;
}
return counts;
}
function getDropdownCounts() {
const unselected = tagList.filter((tag) => !(tag in filteredTags));
return Object.fromEntries(
unselected.map((tag) => [tag, weightCounts(displayedStreams, tag)])
);
}
function getRemainingTags() {
let tagCounts = displayedStreams.reduce((tags, stream) => {
stream['tags'].forEach((tag) => (tag in tags ? (tags[tag] += 1) : (tags[tag] = 1)));
return tags;
}, {});
return Object.entries(tagCounts)
.filter((el) => el[1] != displayedStreams.length)
.map((el) => el[0]);
function getPillCounts() {
return Object.fromEntries(
Object.keys(filteredTags).map((tag) => {
const otherFilters = { ...filteredTags };
delete otherFilters[tag];
const candidates = ctx.streams.filter((stream) =>
matchesFilter(stream, otherFilters)
);
return [tag, weightCounts(candidates, tag)];
})
);
}
function getDisplayedTagsInList(streamTags, remainingTags) {
return streamTags.filter((tag) => remainingTags.includes(tag));
}
function updateFavorites(stream) {
$favoritedStreams.has(stream['id'])
? $favoritedStreams.delete(stream['id'])
: $favoritedStreams.add(stream['id']);
$favoritedStreams = $favoritedStreams; // for reactivity
function updateFavorites(stream: StreamSummary) {
favoritedStreams.has(stream.id)
? favoritedStreams.delete(stream.id)
: favoritedStreams.add(stream.id);
}
</script>
<div class="tag-select">
<TagSelect bind:listOpen bind:checked={filteredTags} {remainingTags} />
<TagSelect
bind:listOpen
bind:checked={filteredTags}
{remainingTags}
{dropdownCounts}
{pillCounts}
/>
<button
onclick={() => (cachedOnly = !cachedOnly)}
aria-label="Downloaded only"
aria-pressed={cachedOnly}
class="material-icons filter-download {cachedOnly
? 'select-faves-star'
: 'unselect-faves-star'}">file_download</button
>
<button
onclick={() => (favoritesOnly = !favoritesOnly)}
aria-label="Favorites only"
aria-pressed={favoritesOnly}
class="material-icons {favoritesOnly ? '' : 'un'}select-faves-star">star</button
>
</div>
<ul class="stream-list">
{#each streams as stream}
{@const favorited = $favoritedStreams.has(stream['id'])}
{@const current = $currentStream['id'] === stream['id']}
{#each ctx.streams as stream}
{@const favorited = favoritedStreams.has(stream.id)}
{@const isCached = streamCache.cached.has(stream.id)}
{@const isPartial = streamCache.partials.has(stream.id)}
{@const current = ctx.current?.id === stream.id}
<li
hidden={!displayedStreams.includes(stream) || (favoritesOnly && !favorited)}
hidden={!displayedStreams.has(stream) ||
(favoritesOnly && !favorited) ||
(cachedOnly && !(isCached || isPartial))}
class="stream-item {current ? 'current-stream' : ''}"
id="stream-{stream['id']}"
id="stream-{stream.id}"
>
<button
class="stream-item-button"
aria-current={current ? 'page' : undefined}
onclick={() => goto('/streams/' + stream.id)}
>
<button class="stream-item-button" onclick={() => goto('/streams/' + stream['id'])}>
<span class="stream-item-id">
ID:
{shorthandCode(stream['id'])}</span
{shorthandCode(stream.id)}</span
>
<span class="stream-item-date">{formatDate(stream['stream_date'])}</span>
<span class="stream-item-date">{formatDate(stream.stream_date)}</span>
<span class="stream-item-length"
>{formatSecondsToHms(stream['length_seconds'])}</span
<span class="stream-item-length">{formatSecondsToHms(stream.length_seconds)}</span>
<span class="stream-item-tags" hidden={!Object.keys(stream.tags).length}>
<span class="stream-item-tags-label">Tags:</span>
<span class="stream-item-tags-list"
><WeightedTags tags={stream.tags} highlighted={filteredTags} /></span
>
<p class="stream-item-tags" hidden={!remainingTags.length}>
Tags: <span hidden={!filteredTags.length}>[...] </span>{getDisplayedTagsInList(
stream['tags'],
remainingTags
).join(', ')}
</p>
</span>
</button>
<button
@@ -89,13 +156,54 @@
e.stopPropagation();
updateFavorites(stream);
}}
aria-label="Favorite"
aria-pressed={favorited}
class="material-icons stream-item-star {favorited ? 'stream-item-star-faved' : ''}"
>{favorited ? 'star' : 'star_border'}</button
>
{#if streamCache.downloading.has(stream.id)}
<span class="stream-item-cached">{streamCache.downloading.get(stream.id)}%</span>
{:else if isCached}
<button
onclick={(e) => {
e.stopPropagation();
streamCache.remove(stream.id);
}}
aria-label="Delete download"
class="material-icons stream-item-cached stream-item-cached-btn">delete</button
>
{:else}
{@const partial = streamCache.partials.get(stream.id)}
<button
onclick={(e) => {
e.stopPropagation();
streamCache.download(stream);
}}
aria-label={partial ? 'Resume download' : 'Download'}
title={partial
? `Partially downloaded (${Math.round((partial.received / partial.total) * 100)}%). Click to resume.`
: undefined}
class="material-icons filter-download stream-item-cached stream-item-cached-btn {partial
? 'stream-item-partial'
: ''}">file_download</button
>
{/if}
</li>
{/each}
</ul>
{#if cachedOnly && (streamCache.cached.size || streamCache.partials.size)}
<p class="cache-usage">
{#if cacheUsage !== undefined}
{cacheUsage > 1_000_000_000
? (cacheUsage / 1_000_000_000).toFixed(1) + ' GB'
: Math.round(cacheUsage / 1_000_000) + ' MB'} of cached streams
{:else}
Calculating…
{/if}
</p>
{/if}
<style>
.stream-list {
list-style-type: none;
@@ -107,11 +215,27 @@
}
.stream-item-tags {
display: flex;
clear: both;
gap: 0.3em;
margin: 0;
font-family: Tahoma;
font-size: smaller;
}
.stream-item-tags[hidden] {
display: none;
}
.stream-item-tags-label {
flex-shrink: 0;
}
.stream-item-tags-list {
flex-grow: 1;
text-align: center;
}
.stream-item-id {
float: left;
font-family: monospace;
@@ -157,6 +281,13 @@
margin-bottom: 1px;
}
.cache-usage {
margin: 0;
padding: 4px 5px;
font-family: Tahoma;
font-size: smaller;
}
.material-icons {
margin-bottom: 0px;
color: black;
@@ -169,24 +300,51 @@
.select-faves-star {
color: rgba(255, 219, 88, 1);
font-size: 24px;
transform: translateX(-1px);
}
.unselect-faves-star {
color: #bbbbbb;
font-size: 24px;
transform: translateX(-1px);
}
.filter-download {
transform: translateY(1px);
}
.stream-item-star {
font-size: 18px;
position: absolute;
bottom: 0;
right: 0;
bottom: 2px;
right: 2px;
opacity: 0;
}
.stream-item-star-faved {
opacity: 0.5;
}
.stream-item-cached {
font-size: 18px;
position: absolute;
bottom: 2px;
right: 22px;
opacity: 0;
}
.stream-item-cached-btn {
cursor: pointer;
}
.stream-item:hover .stream-item-cached {
opacity: 0.5;
}
.stream-item:hover .stream-item-cached-btn:hover {
opacity: 1;
}
.stream-item:hover .stream-item-star {
opacity: 0.5;
}
@@ -195,14 +353,44 @@
opacity: 1;
}
.stream-item-cached.stream-item-partial {
color: #c8a415;
opacity: 0.75;
}
.material-icons::-moz-focus-inner {
border: 0;
}
.stream-item .stream-item-star:focus-visible,
.stream-item .stream-item-cached-btn:focus-visible {
opacity: 1;
}
/* touch screens can't hover, so always display */
@media (hover: none) {
.stream-item-star {
opacity: 0.5;
}
.stream-item-cached {
opacity: 0.4;
}
}
@media (max-width: 575px) {
.stream-item-star {
opacity: 0.5;
font-size: 24px;
bottom: 4px;
right: 4px;
}
.stream-item-cached {
opacity: 0.4;
font-size: 24px;
bottom: 4px;
right: 30px;
}
}
</style>
+140 -32
View File
@@ -1,42 +1,68 @@
<script lang="ts">
import Select from 'svelte-select';
import { tagList } from '$lib/stores.js';
import { tagList, MAX_TAG_WEIGHT, TAG_WEIGHT_NAMES } from '$lib/stores.svelte.ts';
let { checked = $bindable([]), remainingTags = [], listOpen = $bindable() } = $props();
// type not exported in the lib itself
type SelectItem = Record<string, unknown>;
type Props = {
// tag -> minimum weight
checked: Record<string, number>;
// unselected tags that can still narrow the list
remainingTags: string[];
// unselected tag -> [displayed streams with it at weight 1+, 2+, 3+]
dropdownCounts: Record<string, number[]>;
// selected tag -> [streams shown if its minimum weight were 1, 2, 3]
pillCounts: Record<string, number[]>;
listOpen: boolean;
};
let {
checked = $bindable({}),
remainingTags = [],
dropdownCounts = {},
pillCounts = {},
listOpen = $bindable()
}: Props = $props();
let items = $state(tagList.map((x) => ({ value: x, label: x })));
let isChecked = $derived.by(computeIsChecked);
let value = $derived.by(computeValue);
function computeIsChecked() {
return checked.reduce((acc, c) => {
acc[c] = true;
return acc;
}, {});
}
function computeValue() {
return checked.map((c) => items.find((i) => i.value === c));
return Object.keys(checked).map((c) => items.find((i) => i.value === c));
}
function handleSelectable() {
items = items.map((item) => {
return { ...item, selectable: !checked.includes(item.value) };
return { ...item, selectable: !(item.value in checked) };
});
}
function handleChange(e) {
if (e.type === 'clear' && Array.isArray(e.detail)) checked = [];
else
checked.includes(e.detail.value)
? (checked = checked.filter((i) => i != e.detail.value))
: (checked = [...checked, e.detail.value]);
// item selected or deleted => passes every selected item as a list
// removing last pill or clearing all => passes undefined
function handleInput(selected: unknown) {
const tags = ((selected ?? []) as SelectItem[]).map((item) => item.value as string);
checked = Object.fromEntries(tags.map((tag) => [tag, checked[tag] ?? 1]));
handleSelectable();
}
let itemFilter = function (label, filterText, option) {
// maximum weight that matches at least one stream for this tag with the current filters
function ceilingOf(tag: string) {
return pillCounts[tag].filter((count) => count > 0).length;
}
// increment the weight threshold for this tag
// and cycles back to 1 once we hit ceilingOf
function cycle(tag: string, back: boolean) {
const min = checked[tag];
const ceiling = ceilingOf(tag);
const next = back ? (min > 1 ? min - 1 : ceiling) : min < ceiling ? min + 1 : 1;
checked = { ...checked, [tag]: next };
}
let itemFilter = function (label: unknown, filterText: string, option: SelectItem) {
return (
remainingTags.includes(option['value']) &&
label.toLowerCase().includes(filterText.toLowerCase())
remainingTags.includes(option.value as string) &&
String(label).toLowerCase().includes(filterText.toLowerCase())
);
};
</script>
@@ -49,28 +75,110 @@
placeholder="Tag Filter..."
filterSelectedItems={true}
closeListOnChange={false}
on:select={handleChange}
on:clear={handleChange}
oninput={handleInput}
{itemFilter}
--max-height="42px"
--background="rgba(255, 255, 255, 0.1)"
--border="1px solid rgba(255, 255, 255, 0.3)"
--border-hover="1px solid rgba(255, 255, 255, 0.3)"
--border-focused="1px solid var(--accent)"
--item-color="white"
--placeholder-color="rgba(255, 255, 255, 0.5)"
--icons-color="rgba(255, 255, 255, 0.6)"
--list-background="#3a3a3a"
--list-border="1px solid rgba(255, 255, 255, 0.3)"
--list-shadow="none"
--item-hover-bg="rgba(255, 255, 255, 0.15)"
--item-hover-color="white"
--item-transition="none"
--item-height="30px"
--item-line-height="30px"
--item-active-background="rgba(173, 216, 230, 0.3)"
--multi-item-bg="rgba(255, 255, 255, 0.15)"
--multi-item-outline="none"
--multi-item-clear-icon-color="white"
listOffset={0}
>
{#snippet item({ item })}
<div class="item">
<label for={item.value}>
<input type="checkbox" id={item.value} bind:checked={isChecked[item.value]} />
{item.label}
</label>
</div>
{#snippet item({ item }: { item: SelectItem })}
{item.label}<span class="count">{dropdownCounts[item.value as string][0]}</span>
{/snippet}
{#snippet empty()}
<div class="empty">(´・ω・`)</div>
{/snippet}
{#snippet selection({ selection }: { selection: SelectItem })}
{@const tag = selection.value as string}
{#if tag in checked}
{@const min = checked[tag]}
{@const ceiling = ceilingOf(tag)}
<button
type="button"
class="weight"
aria-label="{selection.label}, at least {TAG_WEIGHT_NAMES[min]}, press to change"
onpointerup={(e) => e.stopPropagation()}
onclick={(e) => cycle(tag, e.shiftKey)}
>
{selection.label}<span class="dots"
>{#each { length: MAX_TAG_WEIGHT }, i}<span
class:headroom={i >= min}
class:spacer={i >= ceiling}>·</span
>{/each}</span
>
</button>
{:else}
{selection.label}
{/if}
{/snippet}
</Select>
<style>
.item {
pointer-events: none;
.count {
float: right;
opacity: 0.4;
}
.empty {
text-align: center;
padding: 6px 0;
color: rgba(255, 255, 255, 0.5);
}
.weight {
background: none;
border: none;
padding: 0;
font: inherit;
color: inherit;
cursor: pointer;
}
.weight:hover {
color: var(--accent);
}
.dots {
margin-left: 3px;
color: var(--accent);
font-weight: bold;
letter-spacing: 1px;
}
/* to avoid pills' size shifting as tags are selected */
.headroom {
opacity: 0.3;
}
.spacer {
visibility: hidden;
}
:global(.svelte-select:hover) {
max-height: unset !important;
}
:global(.svelte-select-list) {
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}
</style>
+19 -3
View File
@@ -1,7 +1,8 @@
<script>
import { currentStream } from '$lib/stores.js';
import { getStreamContext } from '$lib/streamContext.svelte.ts';
currentStream.set({});
const ctx = getStreamContext();
ctx.clearCurrent();
</script>
<div class="stream-information">
@@ -10,7 +11,22 @@
</div>
<div class="description-bubble">
<p>Hello, there, welcome to V1.5.</p>
<p>Hello, there, welcome to V1.7.</p>
<p>
<u>2026-09-06 update:</u> caching behavior has been greatly improved when trying to download
streams in poor network conditions.<br />
You can now also resume interrupted downloads and see how much disk space is being used when the
downloads-only filter is enabled.<br />
I've done a bit of refactoring to the codebase, so don't hesitate to message me if you're having
any weird issues!<br /><br />
<u>2026-03-16 update:</u> you can now cache streams offline for playback in low-connectivity
environments (and to prevent buffering)!<br />
Simply click on the download icon in the stream list (and click again to remove them from cache).
You can also filter by cached streams at the top. This all goes into your browser storage, and
a stream is generally 100~250MB depending on its length.
</p>
<hr />
<p>
Still in construction. The design is responsive now, so phones should work well enough!
Needs touch events though.
+20 -11
View File
@@ -1,12 +1,17 @@
import fs from 'fs';
import path from 'path';
import fs from 'node:fs';
import path from 'node:path';
import { error } from '@sveltejs/kit';
import { getStreamInfo } from '$lib/database.js';
import { getStreamInfo } from '$lib/database.ts';
import { dev } from '$app/environment';
import { STREAM_JSON_LOCATION } from '$env/static/private';
import type { Actions } from './$types';
import type { TagWeights } from '$lib/types';
let getOriginalJson, writeSideloadJson;
export let actions;
type SideloadJson = { title: unknown; description: unknown; tags: unknown };
let getOriginalJson: (streamId: string) => string;
let writeSideloadJson: (streamId: string, newJson: SideloadJson) => void;
export let actions: Actions | undefined;
// utilities for manipulating original stream JSONs
if (dev) {
@@ -18,7 +23,7 @@ if (dev) {
const jsonString = fs.readFileSync(filePath, 'utf8');
return jsonString;
} else {
return JSON.stringify({ title: '', description: '', tags: [] });
return JSON.stringify({ title: '', description: '', tags: {} });
}
};
@@ -30,11 +35,13 @@ if (dev) {
actions = {
default: async ({ params, request }) => {
const data = await request.formData();
// let newJson = JSON.parse(getOriginalJson(params.stream_id));
const newJson = {};
newJson['title'] = data.get('title');
newJson['description'] = data.get('description');
newJson['tags'] = data.getAll('tags');
const weights = JSON.parse(String(data.get('tags'))) as TagWeights;
const newJson: SideloadJson = {
title: data.get('title'),
description: data.get('description'),
// weight 0 means the tag is off
tags: Object.fromEntries(Object.entries(weights).filter(([, weight]) => weight > 0))
};
writeSideloadJson(params.stream_id, newJson);
}
};
@@ -46,6 +53,8 @@ export function load({ params }) {
error(404);
}
result.descriptionHtml = Bun.markdown.html(result.description || 'No description available.');
if (dev) {
// pass raw JSON for metadata editor
const original = JSON.parse(getOriginalJson(params.stream_id));
+44 -7
View File
@@ -1,16 +1,50 @@
<script lang="ts">
import { run } from 'svelte/legacy';
import StreamPage from './StreamPage.svelte';
import MetadataEditor from './MetadataEditor.svelte';
import Player from './Player.svelte';
import { untrack } from 'svelte';
import { dev } from '$app/environment';
import { currentStream, updateCurrentStream } from '$lib/stores.js';
import { getStreamContext } from '$lib/streamContext.svelte.ts';
import * as streamCache from '$lib/streamCache.svelte.ts';
let { data } = $props();
const ctx = getStreamContext();
run(() => {
updateCurrentStream(data.stream);
let source = $state<{ id: string; url: string } | null>(null);
const streamId = $derived(data.stream.id);
const isCached = $derived(streamCache.cached.has(streamId));
// update stream context only when we actually swap streams
// this avoids reloading the audio element when we click on the same stream
$effect.pre(() => {
streamId;
ctx.setCurrent(untrack(() => data.stream));
});
$effect.pre(() => {
const id = streamId;
const cached = isCached;
const networkUrl = untrack(() => `/media/tracks/${data.stream.filename}`);
// not in cache (or just deleted from cache)? use network url
if (!cached) {
source = { id, url: networkUrl };
return;
}
// otherwise use the cached blob
// if the cache finished downloading while the stream is playing,
// Player.svelte will notice and swap it in at the right time uninterrupted
let objectUrl: string | null = null;
streamCache.getUrl(id).then((url) => {
objectUrl = url;
source = { id, url: url ?? networkUrl };
});
return () => {
// cleanup blob handle when switching away from cached stream
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
});
</script>
@@ -22,8 +56,11 @@
<StreamPage />
</div>
<div id="player">
{#key $currentStream}
<Player display={true} src="/media/tracks/{$currentStream.filename}" />
{#key streamId}
<!-- until streamCache.getUrl() resolves, source still points at the previous stream -->
{#if source?.id === streamId}
<Player display={true} src={source.url} />
{/if}
{/key}
</div>
</div>
@@ -1,24 +1,20 @@
<script lang="ts">
import { page } from '$app/stores';
import { tagList } from '$lib/stores.js';
import { page } from '$app/state';
import { tagList, MAX_TAG_WEIGHT, TAG_WEIGHT_NAMES } from '$lib/stores.svelte.ts';
import type { TagWeights } from '$lib/types';
let { original = $bindable() } = $props();
let tagMap = new Map();
let weights: TagWeights = $derived({ ...original.tags });
// Create a mapping of tags and their checked status
let reloadTags = (original) => {
tagList.forEach((tag) => {
tagMap.set(tag, original.tags.includes(tag));
});
};
$effect.pre(() => {
reloadTags(original);
});
// off -> light -> medium -> heavy -> off, backwards with shift
function cycle(tag: string, back: boolean) {
const step = back ? MAX_TAG_WEIGHT : 1;
weights = { ...weights, [tag]: ((weights[tag] ?? 0) + step) % (MAX_TAG_WEIGHT + 1) };
}
</script>
{#key $page.url.pathname}
{#key page.url.pathname}
<form method="POST">
<br />
<label>
@@ -36,17 +32,24 @@
></textarea>
</label>
<br />
<label>
<div class="tags">
<p>Tags:</p>
<div class="checkboxContainer">
<input type="hidden" name="tags" value={JSON.stringify(weights)} />
<div class="tag-pills">
{#each tagList as tag}
<label>
<input type="checkbox" name="tags" value={tag} checked={tagMap.get(tag)} />
{tag}
</label>
{@const weight = weights[tag] ?? 0}
<button
type="button"
class="tag-pill"
class:off={!weight}
aria-label="{tag}, {TAG_WEIGHT_NAMES[weight]}"
onclick={(e) => cycle(tag, e.shiftKey)}
>
{tag}<span class="dots">{'·'.repeat(weight)}</span>
</button>
{/each}
</div>
</label>
</div>
<br />
<button type="submit">Submit</button>
@@ -58,19 +61,54 @@
margin-left: 10px;
}
label {
label,
.tags {
display: flex;
align-items: center;
}
label > p {
label > p,
.tags > p {
margin-right: 5px;
}
.checkboxContainer {
.tag-pills {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 1px;
max-width: 50%;
padding: 4px 8px;
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
.tag-pill {
background: none;
border: none;
padding: 2px 0;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
user-select: none;
}
.tag-pill.off {
opacity: 0.35;
}
.tag-pill:hover {
color: var(--accent);
}
.tag-pill.off:hover {
opacity: 0.65;
color: inherit;
}
.dots {
margin-left: 2px;
color: var(--accent);
font-weight: bold;
}
</style>
+183 -102
View File
@@ -2,38 +2,34 @@
taken from https://github.com/Linkcube/svelte-audio-controls
ISC License
-->
<svelte:options />
<script module>
let getAudio = null;
<script module lang="ts">
let getAudio: (() => HTMLAudioElement) | null = null;
export function jumpToTrack(s) {
getAudio().currentTime = s;
getAudio().play();
export function jumpToTrack(s: number) {
const el = getAudio?.();
if (!el) return;
el.currentTime = s;
el.play();
}
</script>
<script lang="ts">
import { run, createBubbler } from 'svelte/legacy';
const bubble = createBubbler();
import { onMount, onDestroy } from 'svelte';
import { onMount, untrack } from 'svelte';
import { fade } from 'svelte/transition';
import {
currentSongIndex,
currentStream,
getSongAtTime,
updateCurrentSong
} from '$lib/stores.js';
import { getStreamContext } from '$lib/streamContext.svelte.ts';
import { readStored, writeStored } from '$lib/utils.ts';
import type { Track } from '$lib/types';
const ctx = getStreamContext();
interface Props {
src: any;
audio?: any;
paused?: boolean;
duration?: number;
muted?: boolean;
volume?: number;
preload?: string;
preload?: 'none' | 'metadata' | 'auto';
iconColor?: string;
textColor?: string;
barPrimaryColor?: string;
@@ -42,11 +38,11 @@
display?: boolean;
inlineTooltip?: boolean;
disableTooltip?: boolean;
onended?: () => void;
}
let {
src,
audio = $bindable(null),
paused = $bindable(true),
duration = $bindable(0),
muted = $bindable(false),
@@ -59,15 +55,34 @@
backgroundColor = 'white',
display = false,
inlineTooltip = false,
disableTooltip = false
disableTooltip = false,
onended
}: Props = $props();
getAudio = () => {
return audio;
let audio = $state<HTMLAudioElement>()!;
// if src changes on the same stream id (in practice when a stream cache finishes downloading),
// save current playhead, then call load() to use the new src
// playhead is restored in the onLoadedMetadata below in this file
let pending: { time: number; playing: boolean } | null = null;
$effect(() => {
src;
if (!audio) return;
pending =
audio.currentTime > 0 ? { time: audio.currentTime, playing: !audio.paused } : null;
audio.load();
});
// module scope, so it has to be released or a destroyed instance keeps answering
$effect(() => {
getAudio = () => audio;
return () => {
getAudio = null;
};
});
let currentTime = $state(0);
let tooltip = $state();
let tooltip = $state<HTMLElement>();
let tooltipX = $state(0);
let tooltipY = $state(0);
let showTooltip = $state(false);
@@ -75,35 +90,72 @@
let seekTrack = $state('');
let seeking = $state(false);
let volumeSeeking = $state(false);
let songBar = $state();
let volumeBar = $state();
let innerWidth = $state();
let innerHeight = $state();
let pendingSeekTime = $state<number | null>(null);
let songBar = $state<HTMLProgressElement>();
let volumeBar = $state<HTMLProgressElement>();
let innerWidth = $state(0);
let innerHeight = $state(0);
let isSafari = $state(false);
onMount(() => {
// work around coreaudio bug
// see https://git.webbieweb.org/apt-get/strimserve/issues/1
const ua = navigator.userAgent;
const isIOS = /iPad|iPhone|iPod/.test(ua);
const isDesktopSafari = /Safari/.test(ua) && !/Chrome/.test(ua) && !/Chromium/.test(ua);
isSafari = isIOS || isDesktopSafari;
onMount(async () => {
// default volume
const volumeData = localStorage.getItem('volume');
volume = volumeData ? parseFloat(volumeData) : 0.67;
volume = readStored('volume', 0.67);
setVolume(volume);
// update browser metadata on track changes
// set actions for previous/next track media buttons
// mediaSession is global, so handlers of a destroyed instance would keep firing
if ('mediaSession' in navigator) {
currentSongIndex.subscribe((val) => {
if (val != null && !paused) {
setMediaMetadata($currentStream.tracks[val]);
}
});
navigator.mediaSession.setActionHandler('previoustrack', previousTrack);
navigator.mediaSession.setActionHandler('nexttrack', nextTrack);
return () => {
navigator.mediaSession.setActionHandler('previoustrack', null);
navigator.mediaSession.setActionHandler('nexttrack', null);
};
}
});
function seek(event, bounds) {
let x = event.pageX - bounds.left;
// update browser metadata on track changes
$effect(() => {
if ('mediaSession' in navigator && ctx.songIndex != null && !paused && ctx.current) {
setMediaMetadata(ctx.current.tracks[ctx.songIndex]);
}
});
function previousTrack() {
if (!ctx.current || ctx.songIndex == null) return;
const tracks = ctx.current.tracks;
const trackStart = tracks[ctx.songIndex][0];
// if more than 3s into the track, restart it; otherwise go to previous
if (audio.currentTime - trackStart > 3 || ctx.songIndex === 0) {
audio.currentTime = currentTime = trackStart;
} else {
audio.currentTime = currentTime = tracks[ctx.songIndex - 1][0];
}
}
function nextTrack() {
if (!ctx.current || ctx.songIndex == null) return;
const tracks = ctx.current.tracks;
if (ctx.songIndex < tracks.length - 1) {
audio.currentTime = currentTime = tracks[ctx.songIndex + 1][0];
}
}
function seek(event: MouseEvent, bounds: DOMRect) {
let x = event.clientX - bounds.left;
return Math.min(Math.max(x / bounds.width, 0), 1);
}
// exponential volume bar
// default is linear, which doesn't correspond to human hearing
function setVolume(volume) {
function setVolume(volume: number) {
if (volume != 0) {
audio.volume = Math.pow(10, 2.5 * (volume - 1));
} else {
@@ -111,7 +163,7 @@
}
}
function setMediaMetadata(track) {
function setMediaMetadata(track: Track) {
navigator.mediaSession.metadata = new MediaMetadata({
artist: track[1],
title: track[2]
@@ -120,100 +172,113 @@
// browsers don't like if you update this while no media is playing
function setMediaMetadataOnPlay() {
if ('mediaSession' in navigator) {
setMediaMetadata($currentStream.tracks[$currentSongIndex]);
if ('mediaSession' in navigator && ctx.current && ctx.songIndex != null) {
setMediaMetadata(ctx.current.tracks[ctx.songIndex]);
}
}
// workaround for bug https://github.com/sveltejs/svelte/issues/5347
// partly workaround for bug https://github.com/sveltejs/svelte/issues/5347
// need to init duration & volume after SSR first load
function updateAudioAttributes(audio) {
if (audio && audio.duration) {
// also workaround for bug https://github.com/sveltejs/svelte/issues/5914
$effect(() => {
if (!audio) return;
const onLoadedMetadata = () => {
duration = audio.duration;
setVolume(volume);
// workaround for bug https://github.com/sveltejs/svelte/issues/5914
audio.addEventListener('loadedmetadata', (event) => {
if (pending) {
// same stream but audio url changed, reload audio at current playhead
audio.currentTime = currentTime = pending.time;
if (pending.playing) audio.play().catch(() => {});
pending = null;
}
paused = audio.paused;
setVolume(volume);
};
if (audio.duration) onLoadedMetadata();
audio.addEventListener('loadedmetadata', onLoadedMetadata);
return () => audio.removeEventListener('loadedmetadata', onLoadedMetadata);
});
}
}
function seekAudio(event) {
function updateSeekVisual(event: MouseEvent) {
if (!songBar) return;
audio.currentTime = seek(event, songBar.getBoundingClientRect()) * duration;
pendingSeekTime = seek(event, songBar.getBoundingClientRect()) * duration;
}
function seekVolume(event) {
function seekVolume(event: MouseEvent) {
if (!volumeBar) return;
volume = seek(event, volumeBar.getBoundingClientRect());
setVolume(volume);
localStorage.setItem('volume', volume.toString());
writeStored('volume', volume);
muted = false;
}
function formatSeconds(totalSeconds) {
function formatSeconds(totalSeconds: number, forceHours = false) {
if (isNaN(totalSeconds)) return 'No Data';
totalSeconds = parseInt(totalSeconds, 10);
var hours = Math.floor(totalSeconds / 3600);
var minutes = Math.floor(totalSeconds / 60) % 60;
var seconds = totalSeconds % 60;
totalSeconds = Math.trunc(totalSeconds);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor(totalSeconds / 60) % 60;
const seconds = totalSeconds % 60;
return [hours, minutes, seconds]
.map((v) => (v < 10 ? '0' + v : v))
.filter((v, i) => v !== '00' || i > 0)
.filter((v, i) => v !== '00' || i > 0 || forceHours)
.join(':');
}
function seekTooltip(event) {
if (!inlineTooltip) {
function seekTooltip(event: MouseEvent) {
if (!songBar) return;
if (!inlineTooltip && tooltip) {
let tooltipBounds = tooltip.getBoundingClientRect();
tooltipX = Math.min(event.pageX + 10, innerWidth - tooltipBounds.width);
tooltipX = Math.min(event.clientX + 10, innerWidth - tooltipBounds.width);
tooltipY = Math.min(songBar.offsetTop - 30, innerHeight - tooltipBounds.height);
}
let bounds = songBar.getBoundingClientRect();
let seekValue = ((event.pageX - bounds.left) * duration) / bounds.width;
let trackArray = $currentStream.tracks[getSongAtTime(seekValue)];
let seekValue = ((event.clientX - bounds.left) * duration) / bounds.width;
updateTooltipText(seekValue);
}
function updateTooltipText(seekValue: number) {
if (!ctx.current) return;
let trackArray = ctx.current.tracks[ctx.getSongAtTime(seekValue)];
seekTrack = trackArray[1] + ' - ' + trackArray[2];
seekText = formatSeconds(seekValue);
}
function trackMouse(event) {
if (seeking) seekAudio(event);
function trackPointer(event: MouseEvent) {
if (seeking) updateSeekVisual(event);
if (showTooltip && !disableTooltip) seekTooltip(event);
if (volumeSeeking) seekVolume(event);
}
run(() => {
updateCurrentSong(currentTime, $currentSongIndex);
});
run(() => {
updateAudioAttributes(audio);
});
export {
src,
audio,
paused,
duration,
muted,
volume,
preload,
iconColor,
textColor,
barPrimaryColor,
barSecondaryColor,
backgroundColor,
display,
inlineTooltip,
disableTooltip
};
$effect(() => {
const time = currentTime;
untrack(() => {
if (ctx.songIndex != null) {
ctx.updateCurrentSong(time, ctx.songIndex);
}
});
});
</script>
<svelte:window
bind:innerWidth
bind:innerHeight
onmouseup={() => (seeking = volumeSeeking = false)}
onmousemove={trackMouse}
onpointerup={() => {
if (seeking && pendingSeekTime != null) {
audio.currentTime = pendingSeekTime;
currentTime = pendingSeekTime;
updateTooltipText(pendingSeekTime);
pendingSeekTime = null;
}
seeking = volumeSeeking = false;
}}
onpointercancel={() => {
pendingSeekTime = null;
seeking = volumeSeeking = false;
}}
onpointermove={trackPointer}
/>
{#if display}
@@ -221,6 +286,7 @@
<button
class="material-icons"
style="--icon-color:{iconColor}"
aria-label={paused ? 'Play' : 'Pause'}
onclick={() => (audio.paused ? audio.play() : audio.pause())}
>
{#if paused}
@@ -231,19 +297,25 @@
</button>
<progress
bind:this={songBar}
value={currentTime ? currentTime : 0}
value={seeking && pendingSeekTime != null ? pendingSeekTime : currentTime || 0}
max={duration}
onmousedown={() => (seeking = true)}
onmouseenter={() => (showTooltip = true)}
onmouseleave={() => (showTooltip = false)}
onclick={seekAudio}
onpointerdown={(e) => {
seeking = true;
updateSeekVisual(e);
}}
onpointerenter={() => (showTooltip = true)}
onpointerleave={() => (showTooltip = false)}
style="--primary-color:{barPrimaryColor}; --secondary-color:{barSecondaryColor}"
class="song-progress"
></progress>
<div class="control-times">{formatSeconds(currentTime)}/{formatSeconds(duration)}</div>
<div class="control-times">
{formatSeconds(currentTime, duration >= 3600)}/{formatSeconds(duration)}
</div>
<button
style="--icon-color:{iconColor}"
class="material-icons"
aria-label="Mute"
aria-pressed={muted}
onclick={() => (muted = !muted)}
>
{#if muted}
@@ -259,7 +331,7 @@
<progress
bind:this={volumeBar}
value={volume}
onmousedown={() => (volumeSeeking = true)}
onpointerdown={() => (volumeSeeking = true)}
onclick={seekVolume}
style="--primary-color:{barPrimaryColor}; --secondary-color:{barSecondaryColor}"
class="volume-progress"
@@ -296,13 +368,17 @@
bind:duration={null, (d) => (duration = d || 0)}
bind:currentTime
{muted}
{volume}
onplay={setMediaMetadataOnPlay}
onended={bubble('ended')}
{onended}
{preload}
>
{#if isSafari}
<source src="{src}.mp3" type="audio/mpeg" />
<source {src} type="audio/ogg;codecs=opus" />
{:else}
<source {src} type="audio/ogg;codecs=opus" />
<source src="{src}.mp3" type="audio/mpeg" />
{/if}
</audio>
<style>
@@ -327,6 +403,9 @@
.control-times {
margin: auto;
margin-right: 5px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
min-width: max-content;
}
.tooltip {
@@ -376,6 +455,8 @@
margin: auto;
margin-left: 5px;
margin-right: 5px;
/* make finger drags seek */
touch-action: none;
}
progress::-webkit-progress-bar {
@@ -1,44 +1,46 @@
<script>
import { currentStream, currentSongIndex } from '$lib/stores.js';
import { shorthandCode, formatTrackTime, formatDate } from '$lib/utils.js';
import { getStreamContext } from '$lib/streamContext.svelte.ts';
import { shorthandCode, formatTrackTime, formatDate } from '$lib/utils.ts';
import { jumpToTrack } from './Player.svelte';
import { Carta } from 'carta-md';
import DOMPurify from 'isomorphic-dompurify';
import WeightedTags from '$lib/components/WeightedTags.svelte';
const carta = new Carta({
sanitizer: DOMPurify.sanitize
});
const ctx = getStreamContext();
let formattedStreamDate = $derived(formatDate($currentStream.stream_date));
let formattedStreamDate = $derived(ctx.current ? formatDate(ctx.current.stream_date) : '');
</script>
<svelte:head>
<title>{formattedStreamDate} | apt-get's auditorium</title>
</svelte:head>
{#if ctx.current}
<div class="stream-information">
<div class="stream-information-flexbox">
<h3 class="stream-id">ID: {shorthandCode($currentStream.id)}</h3>
<h3 class="stream-id">ID: {shorthandCode(ctx.current.id)}</h3>
<h1 class="stream-date">{formattedStreamDate}</h1>
</div>
<h5 class="stream-tags"><u>Tags</u>: {$currentStream.tags.join(', ')}</h5>
<h5 class="stream-tags"><u>Tags</u>: <WeightedTags tags={ctx.current.tags} /></h5>
</div>
<div class="description-bubble">
{@html carta.renderSSR($currentStream.description || 'No description available.')}
{@html ctx.current.descriptionHtml}
</div>
<div id="table-container">
<table>
<tbody>
<tr><th>Timestamp</th><th>Artist</th><th>Title</th></tr>
{#each $currentStream.tracks as track, i}
<tr class:current={i == $currentSongIndex}>
{#each ctx.current.tracks as track, i}
<tr
class:current={i == ctx.songIndex}
aria-current={i == ctx.songIndex ? 'true' : undefined}
>
<td class="timestamp-field"
><div class="timestamp-field-flex">
{formatTrackTime(track[0])}
<button
onclick={() => jumpToTrack(track[0])}
aria-label="Play from {formatTrackTime(track[0])}"
class="material-icons"
style="padding: 4px 6px; margin-top: -4px; margin-bottom: -4px; margin-right: -6px"
>fast_forward</button
@@ -52,6 +54,7 @@
</tbody>
</table>
</div>
{/if}
<style>
.stream-information {
@@ -181,6 +184,17 @@
border: 0;
}
tr .material-icons:focus-visible {
opacity: 1;
}
/* touch screens can't hover, so always display */
@media (hover: none) {
.material-icons {
opacity: 0.5;
}
}
@media (max-width: 575px) {
.material-icons {
opacity: 0.5;
@@ -1,8 +1,9 @@
import fs from 'fs';
import fs from 'node:fs';
import { json } from '@sveltejs/kit';
import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
export let GET;
export let GET: RequestHandler | undefined;
if (process.env.NODE_ENV === 'development') {
const jsonFolder = './db/stream_json/';
Binary file not shown.
-1
View File
@@ -1,4 +1,3 @@
//import adapter from 'svelte-adapter-bun';
import adapter from 'svelte-adapter-bun';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
+1
View File
@@ -2,6 +2,7 @@
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"allowImportingTsExtensions": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,