Compare commits
22
Commits
bun
..
65fc04a4d8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65fc04a4d8 | ||
|
|
39593d470d | ||
|
|
c038316461 | ||
|
|
e98293fa7c | ||
|
|
9c3fd4c1a2 | ||
|
|
d7999785c8 | ||
|
|
62af3683a4 | ||
|
|
7a052c4e68 | ||
|
|
1c7736f832 | ||
|
|
64681befad | ||
|
|
090a145211 | ||
|
|
1dc3f4505b | ||
|
|
7febb497e9 | ||
|
|
6c12cfd49b | ||
|
|
3aa762d544 | ||
|
|
8573b82515 | ||
|
|
b47a433414 | ||
|
|
4d8f7c2b02 | ||
|
|
f777873432 | ||
|
|
347438928a | ||
|
|
dc84db8c79 | ||
|
|
7978ea5b37 |
+4
-1
@@ -23,7 +23,10 @@ const lookup = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Retrieve existing IDs from Stream
|
// Retrieve existing IDs from Stream
|
||||||
const existingIds = db.prepare('SELECT id FROM Stream').all().map(row => row.id);
|
const existingIds = db
|
||||||
|
.prepare('SELECT id FROM Stream')
|
||||||
|
.all()
|
||||||
|
.map((row) => row.id);
|
||||||
// Create a set of existing IDs for efficient lookup
|
// Create a set of existing IDs for efficient lookup
|
||||||
const idSet = new Set(existingIds);
|
const idSet = new Set(existingIds);
|
||||||
|
|
||||||
|
|||||||
Generated
-4327
File diff suppressed because it is too large
Load Diff
+20
-21
@@ -4,7 +4,7 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"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",
|
"preview": "vite preview",
|
||||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
"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"
|
"generate_iconfont_subset": "cd scripts && bash ./generate_iconfont_subset.sh"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@sveltejs/kit": "^2.17.1",
|
"@sveltejs/kit": "^2.55.0",
|
||||||
"@types/bun": "^1.2.2",
|
"@types/bun": "^1.3.10",
|
||||||
"@types/node": "^20.17.17",
|
"@types/node": "^25.5.0",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.62.0",
|
"@typescript-eslint/eslint-plugin": "^8.57.0",
|
||||||
"@typescript-eslint/parser": "^5.62.0",
|
"@typescript-eslint/parser": "^8.57.0",
|
||||||
"carta-md": "^4.6.7",
|
"dotenv": "^16.6.1",
|
||||||
"dotenv": "^16.4.7",
|
"eslint": "^10.0.3",
|
||||||
"eslint": "^8.57.1",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-config-prettier": "^8.10.0",
|
"eslint-plugin-svelte": "^3.15.2",
|
||||||
"eslint-plugin-svelte": "^2.46.1",
|
|
||||||
"fontkit": "^2.0.4",
|
"fontkit": "^2.0.4",
|
||||||
"isomorphic-dompurify": "^2.21.0",
|
"prettier": "^3.8.1",
|
||||||
"prettier": "^3.4.2",
|
"prettier-plugin-svelte": "^3.5.1",
|
||||||
"prettier-plugin-svelte": "^3.3.3",
|
|
||||||
"sqids": "0.3.0",
|
"sqids": "0.3.0",
|
||||||
"svelte": "^5.19.9",
|
"svelte": "^5.53.12",
|
||||||
"svelte-check": "^4.1.4",
|
"svelte-check": "^4.4.5",
|
||||||
"svelte-select": "^5.8.3",
|
"svelte-select": "^5.8.3",
|
||||||
"tslib": "^2.8.1",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.7.3",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^5.4.14"
|
"vite": "^8.0.0"
|
||||||
},
|
},
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@sveltejs/vite-plugin-svelte": "^4.0.4",
|
"@sveltejs/adapter-node": "^5.5.4",
|
||||||
"svelte-adapter-bun": "https://github.com/gornostay25/svelte-adapter-bun",
|
"@sveltejs/vite-plugin-svelte": "^7.0.0",
|
||||||
"typescript-svelte-plugin": "^0.3.45"
|
"svelte-adapter-bun": "^1.0.1",
|
||||||
|
"typescript-svelte-plugin": "^0.3.50"
|
||||||
},
|
},
|
||||||
"trustedDependencies": [
|
"trustedDependencies": [
|
||||||
"svelte-adapter-bun"
|
"svelte-adapter-bun"
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ fontFile="$(basename "$fontUrl")"
|
|||||||
unicodePoints=(
|
unicodePoints=(
|
||||||
"61-7a,5f" # ascii lowercase + underscore
|
"61-7a,5f" # ascii lowercase + underscore
|
||||||
"e2c4" # file_download
|
"e2c4" # file_download
|
||||||
|
"e872" # delete
|
||||||
"e037" # play_arrow
|
"e037" # play_arrow
|
||||||
"e034" # pause
|
"e034" # pause
|
||||||
"e04f" # volume_off
|
"e04f" # volume_off
|
||||||
|
|||||||
Vendored
+1
@@ -1,3 +1,4 @@
|
|||||||
|
/// <reference lib="dom.asynciterable" />
|
||||||
// See https://kit.svelte.dev/docs/types#app
|
// See https://kit.svelte.dev/docs/types#app
|
||||||
// for information about these interfaces
|
// for information about these interfaces
|
||||||
declare global {
|
declare global {
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -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: (JSON.parse(stream.tags as string) 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: (JSON.parse(streamData.tags as string) as string[]) ?? [],
|
||||||
|
length_seconds: streamData.length_seconds as number,
|
||||||
|
tracks: JSON.parse(streamData.tracks as string)
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
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 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'
|
||||||
|
];
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
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) {
|
||||||
|
$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 {
|
||||||
|
// 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);
|
||||||
|
const root = await navigator.storage.getDirectory();
|
||||||
|
await root.removeEntry(streamId).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
await assemble(stream.id, state.total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 });
|
||||||
|
const writable = await handle.createWritable();
|
||||||
|
|
||||||
|
// check at each step the chunk names (ranges) are coherent
|
||||||
|
let written = 0;
|
||||||
|
while (written < total) {
|
||||||
|
const part = await dir.getFileHandle(String(written)).catch(() => null);
|
||||||
|
if (!part) break;
|
||||||
|
const file = await part.getFile();
|
||||||
|
if (!file.size) break;
|
||||||
|
await writable.write(file);
|
||||||
|
written += file.size;
|
||||||
|
}
|
||||||
|
await writable.close();
|
||||||
|
|
||||||
|
await discard(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 stream's partial download state and run a sweep of leftover parts files */
|
||||||
|
async function discard(streamId: string) {
|
||||||
|
partials.delete(streamId);
|
||||||
|
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(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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;
|
||||||
|
}
|
||||||
@@ -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>();
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/** A track entry: [timestamp_seconds, artist, title] */
|
||||||
|
export type Track = [number, string, string];
|
||||||
|
|
||||||
|
/** The summary shape used in sidebar listings. */
|
||||||
|
export interface StreamSummary {
|
||||||
|
id: string;
|
||||||
|
stream_date: number;
|
||||||
|
filename: string;
|
||||||
|
title: string | null;
|
||||||
|
tags: string[];
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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);
|
|
||||||
}
|
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { getStreams } from '$lib/database.js';
|
import { getStreams } from '$lib/database.ts';
|
||||||
|
|
||||||
export function load() {
|
export function load() {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Sidebar from './Sidebar.svelte';
|
import Sidebar from './Sidebar.svelte';
|
||||||
import Footer from './Footer.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>
|
</script>
|
||||||
|
|
||||||
<div id="mainContainer">
|
<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="footer" class="panel-alt"><Footer /></div>
|
||||||
<div id="content">{@render children?.()}</div>
|
<div id="content">{@render children?.()}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { untrack } from 'svelte';
|
import { untrack } from 'svelte';
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { currentStream, favoritedStreams } from '$lib/stores.js';
|
import { favoritedStreams } from '$lib/stores.svelte.ts';
|
||||||
import { hashColor, shorthandCode, formatSecondsToHms, formatDate } from '$lib/utils.js';
|
import * as streamCache from '$lib/streamCache.svelte.ts';
|
||||||
|
import { getStreamContext } from '$lib/streamContext.svelte.ts';
|
||||||
|
import type { StreamSummary } from '$lib/types';
|
||||||
|
import { hashColor, shorthandCode, formatSecondsToHms, formatDate } from '$lib/utils.ts';
|
||||||
import TagSelect from './TagSelect.svelte';
|
import TagSelect from './TagSelect.svelte';
|
||||||
|
|
||||||
let { streams } = $props();
|
const ctx = getStreamContext();
|
||||||
let filteredTags = $state([]);
|
let filteredTags = $state([]);
|
||||||
let favoritesOnly = $state(false);
|
let favoritesOnly = $state(false);
|
||||||
|
let cachedOnly = $state(false);
|
||||||
let listOpen = $state();
|
let listOpen = $state();
|
||||||
let displayedStreams = $derived.by(streamsToDisplay);
|
let displayedStreams = $derived.by(streamsToDisplay);
|
||||||
let remainingTags = $derived.by(getRemainingTags);
|
let remainingTags = $derived.by(getRemainingTags);
|
||||||
@@ -19,15 +23,15 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
function streamsToDisplay() {
|
function streamsToDisplay() {
|
||||||
return streams.filter(
|
return ctx.streams.filter(
|
||||||
(stream) =>
|
(stream) =>
|
||||||
!('tags' in stream) || filteredTags.every((tag) => stream['tags'].includes(tag))
|
!('tags' in stream) || filteredTags.every((tag) => stream.tags.includes(tag))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function getRemainingTags() {
|
function getRemainingTags() {
|
||||||
let tagCounts = displayedStreams.reduce((tags, stream) => {
|
let tagCounts = displayedStreams.reduce((tags: Record<string, number>, stream) => {
|
||||||
stream['tags'].forEach((tag) => (tag in tags ? (tags[tag] += 1) : (tags[tag] = 1)));
|
stream.tags.forEach((tag) => (tags[tag] ? (tags[tag] += 1) : (tags[tag] = 1)));
|
||||||
return tags;
|
return tags;
|
||||||
}, {});
|
}, {});
|
||||||
return Object.entries(tagCounts)
|
return Object.entries(tagCounts)
|
||||||
@@ -35,20 +39,25 @@
|
|||||||
.map((el) => el[0]);
|
.map((el) => el[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function getDisplayedTagsInList(streamTags, remainingTags) {
|
function getDisplayedTagsInList(streamTags: string[], remainingTags: string[]) {
|
||||||
return streamTags.filter((tag) => remainingTags.includes(tag));
|
return streamTags.filter((tag) => remainingTags.includes(tag));
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateFavorites(stream) {
|
function updateFavorites(stream: StreamSummary) {
|
||||||
$favoritedStreams.has(stream['id'])
|
favoritedStreams.has(stream.id)
|
||||||
? $favoritedStreams.delete(stream['id'])
|
? favoritedStreams.delete(stream.id)
|
||||||
: $favoritedStreams.add(stream['id']);
|
: favoritedStreams.add(stream.id);
|
||||||
$favoritedStreams = $favoritedStreams; // for reactivity
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="tag-select">
|
<div class="tag-select">
|
||||||
<TagSelect bind:listOpen bind:checked={filteredTags} {remainingTags} />
|
<TagSelect bind:listOpen bind:checked={filteredTags} {remainingTags} />
|
||||||
|
<button
|
||||||
|
onclick={() => (cachedOnly = !cachedOnly)}
|
||||||
|
class="material-icons filter-download {cachedOnly
|
||||||
|
? 'select-faves-star'
|
||||||
|
: 'unselect-faves-star'}">file_download</button
|
||||||
|
>
|
||||||
<button
|
<button
|
||||||
onclick={() => (favoritesOnly = !favoritesOnly)}
|
onclick={() => (favoritesOnly = !favoritesOnly)}
|
||||||
class="material-icons {favoritesOnly ? '' : 'un'}select-faves-star">star</button
|
class="material-icons {favoritesOnly ? '' : 'un'}select-faves-star">star</button
|
||||||
@@ -56,29 +65,30 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ul class="stream-list">
|
<ul class="stream-list">
|
||||||
{#each streams as stream}
|
{#each ctx.streams as stream}
|
||||||
{@const favorited = $favoritedStreams.has(stream['id'])}
|
{@const favorited = favoritedStreams.has(stream.id)}
|
||||||
{@const current = $currentStream['id'] === stream['id']}
|
{@const isCached = streamCache.cached.has(stream.id)}
|
||||||
|
{@const current = ctx.current?.id === stream.id}
|
||||||
<li
|
<li
|
||||||
hidden={!displayedStreams.includes(stream) || (favoritesOnly && !favorited)}
|
hidden={!displayedStreams.includes(stream) ||
|
||||||
|
(favoritesOnly && !favorited) ||
|
||||||
|
(cachedOnly && !isCached)}
|
||||||
class="stream-item {current ? 'current-stream' : ''}"
|
class="stream-item {current ? 'current-stream' : ''}"
|
||||||
id="stream-{stream['id']}"
|
id="stream-{stream.id}"
|
||||||
>
|
>
|
||||||
<button class="stream-item-button" onclick={() => goto('/streams/' + stream['id'])}>
|
<button class="stream-item-button" onclick={() => goto('/streams/' + stream.id)}>
|
||||||
<span class="stream-item-id">
|
<span class="stream-item-id">
|
||||||
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"
|
<span class="stream-item-length">{formatSecondsToHms(stream.length_seconds)}</span>
|
||||||
>{formatSecondsToHms(stream['length_seconds'])}</span
|
|
||||||
>
|
|
||||||
|
|
||||||
<p class="stream-item-tags" hidden={!remainingTags.length}>
|
<p class="stream-item-tags" hidden={!remainingTags.length}>
|
||||||
Tags: <span hidden={!filteredTags.length}>[...] </span>{getDisplayedTagsInList(
|
Tags: <span hidden={!filteredTags.length}>[...] </span>{getDisplayedTagsInList(
|
||||||
stream['tags'],
|
stream.tags,
|
||||||
remainingTags
|
remainingTags
|
||||||
).join(', ')}
|
).join(', ')}
|
||||||
</p>
|
</p>
|
||||||
@@ -92,6 +102,31 @@
|
|||||||
class="material-icons stream-item-star {favorited ? 'stream-item-star-faved' : ''}"
|
class="material-icons stream-item-star {favorited ? 'stream-item-star-faved' : ''}"
|
||||||
>{favorited ? 'star' : 'star_border'}</button
|
>{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);
|
||||||
|
}}
|
||||||
|
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);
|
||||||
|
}}
|
||||||
|
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>
|
</li>
|
||||||
{/each}
|
{/each}
|
||||||
</ul>
|
</ul>
|
||||||
@@ -169,24 +204,51 @@
|
|||||||
.select-faves-star {
|
.select-faves-star {
|
||||||
color: rgba(255, 219, 88, 1);
|
color: rgba(255, 219, 88, 1);
|
||||||
font-size: 24px;
|
font-size: 24px;
|
||||||
|
transform: translateX(-1px);
|
||||||
}
|
}
|
||||||
|
|
||||||
.unselect-faves-star {
|
.unselect-faves-star {
|
||||||
color: #bbbbbb;
|
color: #bbbbbb;
|
||||||
font-size: 24px;
|
font-size: 24px;
|
||||||
|
transform: translateX(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-download {
|
||||||
|
transform: translateY(1px);
|
||||||
}
|
}
|
||||||
|
|
||||||
.stream-item-star {
|
.stream-item-star {
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
bottom: 0;
|
bottom: 2px;
|
||||||
right: 0;
|
right: 2px;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stream-item-star-faved {
|
.stream-item-star-faved {
|
||||||
opacity: 0.5;
|
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 {
|
.stream-item:hover .stream-item-star {
|
||||||
opacity: 0.5;
|
opacity: 0.5;
|
||||||
}
|
}
|
||||||
@@ -195,6 +257,11 @@
|
|||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.stream-item-cached.stream-item-partial {
|
||||||
|
color: #c8a415;
|
||||||
|
opacity: 0.75;
|
||||||
|
}
|
||||||
|
|
||||||
.material-icons::-moz-focus-inner {
|
.material-icons::-moz-focus-inner {
|
||||||
border: 0;
|
border: 0;
|
||||||
}
|
}
|
||||||
@@ -203,6 +270,15 @@
|
|||||||
.stream-item-star {
|
.stream-item-star {
|
||||||
opacity: 0.5;
|
opacity: 0.5;
|
||||||
font-size: 24px;
|
font-size: 24px;
|
||||||
|
bottom: 4px;
|
||||||
|
right: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-item-cached {
|
||||||
|
opacity: 0.4;
|
||||||
|
font-size: 24px;
|
||||||
|
bottom: 4px;
|
||||||
|
right: 30px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Select from 'svelte-select';
|
import Select from 'svelte-select';
|
||||||
import { tagList } from '$lib/stores.js';
|
import { tagList } from '$lib/stores.svelte.ts';
|
||||||
|
|
||||||
let { checked = $bindable([]), remainingTags = [], listOpen = $bindable() } = $props();
|
let { checked = $bindable([]), remainingTags = [], listOpen = $bindable() } = $props();
|
||||||
let items = $state(tagList.map((x) => ({ value: x, label: x })));
|
let items = $state(tagList.map((x) => ({ value: x, label: x })));
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleChange(e) {
|
function handleChange(e: CustomEvent) {
|
||||||
if (e.type === 'clear' && Array.isArray(e.detail)) checked = [];
|
if (e.type === 'clear' && Array.isArray(e.detail)) checked = [];
|
||||||
else
|
else
|
||||||
checked.includes(e.detail.value)
|
checked.includes(e.detail.value)
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
handleSelectable();
|
handleSelectable();
|
||||||
}
|
}
|
||||||
|
|
||||||
let itemFilter = function (label, filterText, option) {
|
let itemFilter = function (label: string, filterText: string, option: { value: string }) {
|
||||||
return (
|
return (
|
||||||
remainingTags.includes(option['value']) &&
|
remainingTags.includes(option['value']) &&
|
||||||
label.toLowerCase().includes(filterText.toLowerCase())
|
label.toLowerCase().includes(filterText.toLowerCase())
|
||||||
@@ -55,14 +55,13 @@
|
|||||||
--max-height="42px"
|
--max-height="42px"
|
||||||
listOffset={0}
|
listOffset={0}
|
||||||
>
|
>
|
||||||
{#snippet item({ item })}
|
<!-- svelte-select 5.8.3 exposes this as a slot, not a snippet prop -->
|
||||||
<div class="item">
|
<div class="item" slot="item" let:item>
|
||||||
<label for={item.value}>
|
<label for={item.value}>
|
||||||
<input type="checkbox" id={item.value} bind:checked={isChecked[item.value]} />
|
<input type="checkbox" id={item.value} checked={isChecked[item.value]} />
|
||||||
{item.label}
|
{item.label}
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
{/snippet}
|
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
<script>
|
<script>
|
||||||
import { currentStream } from '$lib/stores.js';
|
import { getStreamContext } from '$lib/streamContext.svelte.ts';
|
||||||
|
|
||||||
currentStream.set({});
|
const ctx = getStreamContext();
|
||||||
|
ctx.clearCurrent();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="stream-information">
|
<div class="stream-information">
|
||||||
@@ -10,7 +11,15 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="description-bubble">
|
<div class="description-bubble">
|
||||||
<p>Hello, there, welcome to V1.5.</p>
|
<p>Hello, there, welcome to V1.6.</p>
|
||||||
|
<p>
|
||||||
|
<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>
|
<p>
|
||||||
Still in construction. The design is responsive now, so phones should work well enough!
|
Still in construction. The design is responsive now, so phones should work well enough!
|
||||||
Needs touch events though.
|
Needs touch events though.
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
import fs from 'fs';
|
import fs from 'node:fs';
|
||||||
import path from 'path';
|
import path from 'node:path';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
import { getStreamInfo } from '$lib/database.js';
|
import { getStreamInfo } from '$lib/database.ts';
|
||||||
import { dev } from '$app/environment';
|
import { dev } from '$app/environment';
|
||||||
import { STREAM_JSON_LOCATION } from '$env/static/private';
|
import { STREAM_JSON_LOCATION } from '$env/static/private';
|
||||||
|
import type { Actions } from './$types';
|
||||||
|
|
||||||
let getOriginalJson, writeSideloadJson;
|
type SideloadJson = { title: unknown; description: unknown; tags: unknown };
|
||||||
export let actions;
|
|
||||||
|
let getOriginalJson: (streamId: string) => string;
|
||||||
|
let writeSideloadJson: (streamId: string, newJson: SideloadJson) => void;
|
||||||
|
export let actions: Actions | undefined;
|
||||||
|
|
||||||
// utilities for manipulating original stream JSONs
|
// utilities for manipulating original stream JSONs
|
||||||
if (dev) {
|
if (dev) {
|
||||||
@@ -30,11 +34,11 @@ if (dev) {
|
|||||||
actions = {
|
actions = {
|
||||||
default: async ({ params, request }) => {
|
default: async ({ params, request }) => {
|
||||||
const data = await request.formData();
|
const data = await request.formData();
|
||||||
// let newJson = JSON.parse(getOriginalJson(params.stream_id));
|
const newJson: SideloadJson = {
|
||||||
const newJson = {};
|
title: data.get('title'),
|
||||||
newJson['title'] = data.get('title');
|
description: data.get('description'),
|
||||||
newJson['description'] = data.get('description');
|
tags: data.getAll('tags')
|
||||||
newJson['tags'] = data.getAll('tags');
|
};
|
||||||
writeSideloadJson(params.stream_id, newJson);
|
writeSideloadJson(params.stream_id, newJson);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -46,6 +50,8 @@ export function load({ params }) {
|
|||||||
error(404);
|
error(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
result.descriptionHtml = Bun.markdown.html(result.description || 'No description available.');
|
||||||
|
|
||||||
if (dev) {
|
if (dev) {
|
||||||
// pass raw JSON for metadata editor
|
// pass raw JSON for metadata editor
|
||||||
const original = JSON.parse(getOriginalJson(params.stream_id));
|
const original = JSON.parse(getOriginalJson(params.stream_id));
|
||||||
|
|||||||
@@ -1,16 +1,50 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { run } from 'svelte/legacy';
|
|
||||||
|
|
||||||
import StreamPage from './StreamPage.svelte';
|
import StreamPage from './StreamPage.svelte';
|
||||||
import MetadataEditor from './MetadataEditor.svelte';
|
import MetadataEditor from './MetadataEditor.svelte';
|
||||||
import Player from './Player.svelte';
|
import Player from './Player.svelte';
|
||||||
|
import { untrack } from 'svelte';
|
||||||
import { dev } from '$app/environment';
|
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();
|
let { data } = $props();
|
||||||
|
const ctx = getStreamContext();
|
||||||
|
|
||||||
run(() => {
|
let source = $state<{ id: string; url: string } | null>(null);
|
||||||
updateCurrentStream(data.stream);
|
|
||||||
|
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>
|
</script>
|
||||||
|
|
||||||
@@ -22,8 +56,11 @@
|
|||||||
<StreamPage />
|
<StreamPage />
|
||||||
</div>
|
</div>
|
||||||
<div id="player">
|
<div id="player">
|
||||||
{#key $currentStream}
|
{#key streamId}
|
||||||
<Player display={true} src="/media/tracks/{$currentStream.filename}" />
|
<!-- until streamCache.getUrl() resolves, source still points at the previous stream -->
|
||||||
|
{#if source?.id === streamId}
|
||||||
|
<Player display={true} src={source.url} />
|
||||||
|
{/if}
|
||||||
{/key}
|
{/key}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { page } from '$app/stores';
|
import { page } from '$app/stores';
|
||||||
import { tagList } from '$lib/stores.js';
|
import { tagList } from '$lib/stores.svelte.ts';
|
||||||
|
|
||||||
let { original = $bindable() } = $props();
|
let { original = $bindable() } = $props();
|
||||||
|
|
||||||
let tagMap = new Map();
|
let tagMap = new Map<string, boolean>();
|
||||||
|
|
||||||
// Create a mapping of tags and their checked status
|
// Create a mapping of tags and their checked status
|
||||||
let reloadTags = (original) => {
|
let reloadTags = (original: { tags: string[] }) => {
|
||||||
tagList.forEach((tag) => {
|
tagList.forEach((tag) => {
|
||||||
tagMap.set(tag, original.tags.includes(tag));
|
tagMap.set(tag, original.tags.includes(tag));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,38 +2,34 @@
|
|||||||
taken from https://github.com/Linkcube/svelte-audio-controls
|
taken from https://github.com/Linkcube/svelte-audio-controls
|
||||||
ISC License
|
ISC License
|
||||||
-->
|
-->
|
||||||
<svelte:options />
|
|
||||||
|
|
||||||
<script module>
|
<script module lang="ts">
|
||||||
let getAudio = null;
|
let getAudio: (() => HTMLAudioElement) | null = null;
|
||||||
|
|
||||||
export function jumpToTrack(s) {
|
export function jumpToTrack(s: number) {
|
||||||
getAudio().currentTime = s;
|
const el = getAudio?.();
|
||||||
getAudio().play();
|
if (!el) return;
|
||||||
|
el.currentTime = s;
|
||||||
|
el.play();
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { run, createBubbler } from 'svelte/legacy';
|
import { onMount, untrack } from 'svelte';
|
||||||
|
|
||||||
const bubble = createBubbler();
|
|
||||||
import { onMount, onDestroy } from 'svelte';
|
|
||||||
import { fade } from 'svelte/transition';
|
import { fade } from 'svelte/transition';
|
||||||
import {
|
import { getStreamContext } from '$lib/streamContext.svelte.ts';
|
||||||
currentSongIndex,
|
import { readStored, writeStored } from '$lib/utils.ts';
|
||||||
currentStream,
|
import type { Track } from '$lib/types';
|
||||||
getSongAtTime,
|
|
||||||
updateCurrentSong
|
const ctx = getStreamContext();
|
||||||
} from '$lib/stores.js';
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
src: any;
|
src: any;
|
||||||
audio?: any;
|
|
||||||
paused?: boolean;
|
paused?: boolean;
|
||||||
duration?: number;
|
duration?: number;
|
||||||
muted?: boolean;
|
muted?: boolean;
|
||||||
volume?: number;
|
volume?: number;
|
||||||
preload?: string;
|
preload?: 'none' | 'metadata' | 'auto';
|
||||||
iconColor?: string;
|
iconColor?: string;
|
||||||
textColor?: string;
|
textColor?: string;
|
||||||
barPrimaryColor?: string;
|
barPrimaryColor?: string;
|
||||||
@@ -42,11 +38,11 @@
|
|||||||
display?: boolean;
|
display?: boolean;
|
||||||
inlineTooltip?: boolean;
|
inlineTooltip?: boolean;
|
||||||
disableTooltip?: boolean;
|
disableTooltip?: boolean;
|
||||||
|
onended?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
let {
|
let {
|
||||||
src,
|
src,
|
||||||
audio = $bindable(null),
|
|
||||||
paused = $bindable(true),
|
paused = $bindable(true),
|
||||||
duration = $bindable(0),
|
duration = $bindable(0),
|
||||||
muted = $bindable(false),
|
muted = $bindable(false),
|
||||||
@@ -59,15 +55,34 @@
|
|||||||
backgroundColor = 'white',
|
backgroundColor = 'white',
|
||||||
display = false,
|
display = false,
|
||||||
inlineTooltip = false,
|
inlineTooltip = false,
|
||||||
disableTooltip = false
|
disableTooltip = false,
|
||||||
|
onended
|
||||||
}: Props = $props();
|
}: Props = $props();
|
||||||
|
|
||||||
getAudio = () => {
|
let audio = $state<HTMLAudioElement>()!;
|
||||||
return audio;
|
|
||||||
|
// 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 currentTime = $state(0);
|
||||||
let tooltip = $state();
|
let tooltip = $state<HTMLElement>();
|
||||||
let tooltipX = $state(0);
|
let tooltipX = $state(0);
|
||||||
let tooltipY = $state(0);
|
let tooltipY = $state(0);
|
||||||
let showTooltip = $state(false);
|
let showTooltip = $state(false);
|
||||||
@@ -75,35 +90,72 @@
|
|||||||
let seekTrack = $state('');
|
let seekTrack = $state('');
|
||||||
let seeking = $state(false);
|
let seeking = $state(false);
|
||||||
let volumeSeeking = $state(false);
|
let volumeSeeking = $state(false);
|
||||||
let songBar = $state();
|
let pendingSeekTime = $state<number | null>(null);
|
||||||
let volumeBar = $state();
|
let songBar = $state<HTMLProgressElement>();
|
||||||
let innerWidth = $state();
|
let volumeBar = $state<HTMLProgressElement>();
|
||||||
let innerHeight = $state();
|
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
|
// default volume
|
||||||
const volumeData = localStorage.getItem('volume');
|
volume = readStored('volume', 0.67);
|
||||||
volume = volumeData ? parseFloat(volumeData) : 0.67;
|
|
||||||
setVolume(volume);
|
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) {
|
if ('mediaSession' in navigator) {
|
||||||
currentSongIndex.subscribe((val) => {
|
navigator.mediaSession.setActionHandler('previoustrack', previousTrack);
|
||||||
if (val != null && !paused) {
|
navigator.mediaSession.setActionHandler('nexttrack', nextTrack);
|
||||||
setMediaMetadata($currentStream.tracks[val]);
|
return () => {
|
||||||
}
|
navigator.mediaSession.setActionHandler('previoustrack', null);
|
||||||
});
|
navigator.mediaSession.setActionHandler('nexttrack', null);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
function seek(event, bounds) {
|
// update browser metadata on track changes
|
||||||
let x = event.pageX - bounds.left;
|
$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);
|
return Math.min(Math.max(x / bounds.width, 0), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// exponential volume bar
|
// exponential volume bar
|
||||||
// default is linear, which doesn't correspond to human hearing
|
// default is linear, which doesn't correspond to human hearing
|
||||||
function setVolume(volume) {
|
function setVolume(volume: number) {
|
||||||
if (volume != 0) {
|
if (volume != 0) {
|
||||||
audio.volume = Math.pow(10, 2.5 * (volume - 1));
|
audio.volume = Math.pow(10, 2.5 * (volume - 1));
|
||||||
} else {
|
} else {
|
||||||
@@ -111,7 +163,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setMediaMetadata(track) {
|
function setMediaMetadata(track: Track) {
|
||||||
navigator.mediaSession.metadata = new MediaMetadata({
|
navigator.mediaSession.metadata = new MediaMetadata({
|
||||||
artist: track[1],
|
artist: track[1],
|
||||||
title: track[2]
|
title: track[2]
|
||||||
@@ -120,99 +172,108 @@
|
|||||||
|
|
||||||
// browsers don't like if you update this while no media is playing
|
// browsers don't like if you update this while no media is playing
|
||||||
function setMediaMetadataOnPlay() {
|
function setMediaMetadataOnPlay() {
|
||||||
if ('mediaSession' in navigator) {
|
if ('mediaSession' in navigator && ctx.current && ctx.songIndex != null) {
|
||||||
setMediaMetadata($currentStream.tracks[$currentSongIndex]);
|
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
|
// need to init duration & volume after SSR first load
|
||||||
function updateAudioAttributes(audio) {
|
// also workaround for bug https://github.com/sveltejs/svelte/issues/5914
|
||||||
if (audio && audio.duration) {
|
$effect(() => {
|
||||||
|
if (!audio) return;
|
||||||
|
|
||||||
|
const onLoadedMetadata = () => {
|
||||||
duration = audio.duration;
|
duration = audio.duration;
|
||||||
setVolume(volume);
|
if (pending) {
|
||||||
|
// same stream but audio url changed, reload audio at current playhead
|
||||||
// workaround for bug https://github.com/sveltejs/svelte/issues/5914
|
audio.currentTime = currentTime = pending.time;
|
||||||
audio.addEventListener('loadedmetadata', (event) => {
|
if (pending.playing) audio.play().catch(() => {});
|
||||||
|
pending = null;
|
||||||
|
}
|
||||||
paused = audio.paused;
|
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;
|
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;
|
if (!volumeBar) return;
|
||||||
volume = seek(event, volumeBar.getBoundingClientRect());
|
volume = seek(event, volumeBar.getBoundingClientRect());
|
||||||
setVolume(volume);
|
setVolume(volume);
|
||||||
localStorage.setItem('volume', volume.toString());
|
writeStored('volume', volume);
|
||||||
muted = false;
|
muted = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatSeconds(totalSeconds) {
|
function formatSeconds(totalSeconds: number, forceHours = false) {
|
||||||
if (isNaN(totalSeconds)) return 'No Data';
|
if (isNaN(totalSeconds)) return 'No Data';
|
||||||
totalSeconds = parseInt(totalSeconds, 10);
|
totalSeconds = Math.trunc(totalSeconds);
|
||||||
var hours = Math.floor(totalSeconds / 3600);
|
const hours = Math.floor(totalSeconds / 3600);
|
||||||
var minutes = Math.floor(totalSeconds / 60) % 60;
|
const minutes = Math.floor(totalSeconds / 60) % 60;
|
||||||
var seconds = totalSeconds % 60;
|
const seconds = totalSeconds % 60;
|
||||||
|
|
||||||
return [hours, minutes, seconds]
|
return [hours, minutes, seconds]
|
||||||
.map((v) => (v < 10 ? '0' + v : v))
|
.map((v) => (v < 10 ? '0' + v : v))
|
||||||
.filter((v, i) => v !== '00' || i > 0)
|
.filter((v, i) => v !== '00' || i > 0 || forceHours)
|
||||||
.join(':');
|
.join(':');
|
||||||
}
|
}
|
||||||
|
|
||||||
function seekTooltip(event) {
|
function seekTooltip(event: MouseEvent) {
|
||||||
if (!inlineTooltip) {
|
if (!songBar) return;
|
||||||
|
if (!inlineTooltip && tooltip) {
|
||||||
let tooltipBounds = tooltip.getBoundingClientRect();
|
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);
|
tooltipY = Math.min(songBar.offsetTop - 30, innerHeight - tooltipBounds.height);
|
||||||
}
|
}
|
||||||
let bounds = songBar.getBoundingClientRect();
|
let bounds = songBar.getBoundingClientRect();
|
||||||
let seekValue = ((event.pageX - bounds.left) * duration) / bounds.width;
|
let seekValue = ((event.clientX - bounds.left) * duration) / bounds.width;
|
||||||
let trackArray = $currentStream.tracks[getSongAtTime(seekValue)];
|
updateTooltipText(seekValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateTooltipText(seekValue: number) {
|
||||||
|
if (!ctx.current) return;
|
||||||
|
let trackArray = ctx.current.tracks[ctx.getSongAtTime(seekValue)];
|
||||||
seekTrack = trackArray[1] + ' - ' + trackArray[2];
|
seekTrack = trackArray[1] + ' - ' + trackArray[2];
|
||||||
seekText = formatSeconds(seekValue);
|
seekText = formatSeconds(seekValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
function trackMouse(event) {
|
function trackMouse(event: MouseEvent) {
|
||||||
if (seeking) seekAudio(event);
|
if (seeking) updateSeekVisual(event);
|
||||||
if (showTooltip && !disableTooltip) seekTooltip(event);
|
if (showTooltip && !disableTooltip) seekTooltip(event);
|
||||||
if (volumeSeeking) seekVolume(event);
|
if (volumeSeeking) seekVolume(event);
|
||||||
}
|
}
|
||||||
run(() => {
|
|
||||||
updateCurrentSong(currentTime, $currentSongIndex);
|
|
||||||
});
|
|
||||||
run(() => {
|
|
||||||
updateAudioAttributes(audio);
|
|
||||||
});
|
|
||||||
|
|
||||||
export {
|
$effect(() => {
|
||||||
src,
|
const time = currentTime;
|
||||||
audio,
|
untrack(() => {
|
||||||
paused,
|
if (ctx.songIndex != null) {
|
||||||
duration,
|
ctx.updateCurrentSong(time, ctx.songIndex);
|
||||||
muted,
|
}
|
||||||
volume,
|
});
|
||||||
preload,
|
});
|
||||||
iconColor,
|
|
||||||
textColor,
|
|
||||||
barPrimaryColor,
|
|
||||||
barSecondaryColor,
|
|
||||||
backgroundColor,
|
|
||||||
display,
|
|
||||||
inlineTooltip,
|
|
||||||
disableTooltip
|
|
||||||
};
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:window
|
<svelte:window
|
||||||
bind:innerWidth
|
bind:innerWidth
|
||||||
bind:innerHeight
|
bind:innerHeight
|
||||||
onmouseup={() => (seeking = volumeSeeking = false)}
|
onmouseup={() => {
|
||||||
|
if (seeking && pendingSeekTime != null) {
|
||||||
|
audio.currentTime = pendingSeekTime;
|
||||||
|
currentTime = pendingSeekTime;
|
||||||
|
updateTooltipText(pendingSeekTime);
|
||||||
|
pendingSeekTime = null;
|
||||||
|
}
|
||||||
|
seeking = volumeSeeking = false;
|
||||||
|
}}
|
||||||
onmousemove={trackMouse}
|
onmousemove={trackMouse}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -231,16 +292,20 @@
|
|||||||
</button>
|
</button>
|
||||||
<progress
|
<progress
|
||||||
bind:this={songBar}
|
bind:this={songBar}
|
||||||
value={currentTime ? currentTime : 0}
|
value={seeking && pendingSeekTime != null ? pendingSeekTime : currentTime || 0}
|
||||||
max={duration}
|
max={duration}
|
||||||
onmousedown={() => (seeking = true)}
|
onmousedown={(e) => {
|
||||||
|
seeking = true;
|
||||||
|
updateSeekVisual(e);
|
||||||
|
}}
|
||||||
onmouseenter={() => (showTooltip = true)}
|
onmouseenter={() => (showTooltip = true)}
|
||||||
onmouseleave={() => (showTooltip = false)}
|
onmouseleave={() => (showTooltip = false)}
|
||||||
onclick={seekAudio}
|
|
||||||
style="--primary-color:{barPrimaryColor}; --secondary-color:{barSecondaryColor}"
|
style="--primary-color:{barPrimaryColor}; --secondary-color:{barSecondaryColor}"
|
||||||
class="song-progress"
|
class="song-progress"
|
||||||
></progress>
|
></progress>
|
||||||
<div class="control-times">{formatSeconds(currentTime)}/{formatSeconds(duration)}</div>
|
<div class="control-times">
|
||||||
|
{formatSeconds(currentTime, duration >= 3600)}/{formatSeconds(duration)}
|
||||||
|
</div>
|
||||||
<button
|
<button
|
||||||
style="--icon-color:{iconColor}"
|
style="--icon-color:{iconColor}"
|
||||||
class="material-icons"
|
class="material-icons"
|
||||||
@@ -296,13 +361,17 @@
|
|||||||
bind:duration={null, (d) => (duration = d || 0)}
|
bind:duration={null, (d) => (duration = d || 0)}
|
||||||
bind:currentTime
|
bind:currentTime
|
||||||
{muted}
|
{muted}
|
||||||
{volume}
|
|
||||||
onplay={setMediaMetadataOnPlay}
|
onplay={setMediaMetadataOnPlay}
|
||||||
onended={bubble('ended')}
|
{onended}
|
||||||
{preload}
|
{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} type="audio/ogg;codecs=opus" />
|
||||||
<source src="{src}.mp3" type="audio/mpeg" />
|
<source src="{src}.mp3" type="audio/mpeg" />
|
||||||
|
{/if}
|
||||||
</audio>
|
</audio>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
@@ -327,6 +396,9 @@
|
|||||||
.control-times {
|
.control-times {
|
||||||
margin: auto;
|
margin: auto;
|
||||||
margin-right: 5px;
|
margin-right: 5px;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
white-space: nowrap;
|
||||||
|
min-width: max-content;
|
||||||
}
|
}
|
||||||
|
|
||||||
.tooltip {
|
.tooltip {
|
||||||
|
|||||||
@@ -1,39 +1,36 @@
|
|||||||
<script>
|
<script>
|
||||||
import { currentStream, currentSongIndex } from '$lib/stores.js';
|
import { getStreamContext } from '$lib/streamContext.svelte.ts';
|
||||||
import { shorthandCode, formatTrackTime, formatDate } from '$lib/utils.js';
|
import { shorthandCode, formatTrackTime, formatDate } from '$lib/utils.ts';
|
||||||
import { jumpToTrack } from './Player.svelte';
|
import { jumpToTrack } from './Player.svelte';
|
||||||
import { Carta } from 'carta-md';
|
|
||||||
import DOMPurify from 'isomorphic-dompurify';
|
|
||||||
|
|
||||||
const carta = new Carta({
|
const ctx = getStreamContext();
|
||||||
sanitizer: DOMPurify.sanitize
|
|
||||||
});
|
|
||||||
|
|
||||||
let formattedStreamDate = $derived(formatDate($currentStream.stream_date));
|
let formattedStreamDate = $derived(ctx.current ? formatDate(ctx.current.stream_date) : '');
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
<title>{formattedStreamDate} | apt-get's auditorium</title>
|
<title>{formattedStreamDate} | apt-get's auditorium</title>
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
|
{#if ctx.current}
|
||||||
<div class="stream-information">
|
<div class="stream-information">
|
||||||
<div class="stream-information-flexbox">
|
<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>
|
<h1 class="stream-date">{formattedStreamDate}</h1>
|
||||||
</div>
|
</div>
|
||||||
<h5 class="stream-tags"><u>Tags</u>: {$currentStream.tags.join(', ')}</h5>
|
<h5 class="stream-tags"><u>Tags</u>: {ctx.current.tags.join(', ')}</h5>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="description-bubble">
|
<div class="description-bubble">
|
||||||
{@html carta.renderSSR($currentStream.description || 'No description available.')}
|
{@html ctx.current.descriptionHtml}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="table-container">
|
<div id="table-container">
|
||||||
<table>
|
<table>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr><th>Timestamp</th><th>Artist</th><th>Title</th></tr>
|
<tr><th>Timestamp</th><th>Artist</th><th>Title</th></tr>
|
||||||
{#each $currentStream.tracks as track, i}
|
{#each ctx.current.tracks as track, i}
|
||||||
<tr class:current={i == $currentSongIndex}>
|
<tr class:current={i == ctx.songIndex}>
|
||||||
<td class="timestamp-field"
|
<td class="timestamp-field"
|
||||||
><div class="timestamp-field-flex">
|
><div class="timestamp-field-flex">
|
||||||
{formatTrackTime(track[0])}
|
{formatTrackTime(track[0])}
|
||||||
@@ -52,6 +49,7 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.stream-information {
|
.stream-information {
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import fs from 'fs';
|
import fs from 'node:fs';
|
||||||
import { json } from '@sveltejs/kit';
|
import { json } from '@sveltejs/kit';
|
||||||
import { error } 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') {
|
if (process.env.NODE_ENV === 'development') {
|
||||||
const jsonFolder = './db/stream_json/';
|
const jsonFolder = './db/stream_json/';
|
||||||
|
|||||||
Binary file not shown.
@@ -1,4 +1,3 @@
|
|||||||
//import adapter from 'svelte-adapter-bun';
|
|
||||||
import adapter from 'svelte-adapter-bun';
|
import adapter from 'svelte-adapter-bun';
|
||||||
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
|
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
"extends": "./.svelte-kit/tsconfig.json",
|
"extends": "./.svelte-kit/tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
"checkJs": true,
|
"checkJs": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
|||||||
Reference in New Issue
Block a user