added what im watching

This commit is contained in:
2026-11-03 19:32:08 +00:00
parent 7e8f329109
commit 1c2c577280
19 changed files with 255 additions and 124 deletions

View File

@@ -4,5 +4,6 @@ export const variables = defineEnvVars({
JELLYFIN_URL: {},
JELLYFIN_API_KEY: {},
JELLYFIN_PLAYLIST_ID: {},
JELLYFIN_USER_ID: {}
JELLYFIN_USER_ID: {},
JELLYFIN_LIBRARY_ID: {}
});

View File

@@ -16,6 +16,28 @@ interface PlaylistItemsResponse {
TotalRecordCount: number;
}
interface JellyfinEpisode {
Id: string;
Name: string;
SeriesName?: string;
SeriesId?: string;
SeasonName?: string;
ParentIndexNumber?: number;
IndexNumber?: number;
Overview?: string;
ProductionYear?: number;
UserData?: {
Played?: boolean;
LastPlayedDate?: string;
PlaybackPositionTicks?: number;
};
}
interface EpisodesResponse {
Items: JellyfinEpisode[];
TotalRecordCount: number;
}
export interface LatestSong {
id: string;
name: string;
@@ -25,15 +47,35 @@ export interface LatestSong {
coverArt: string | null;
}
export interface LatestSeries {
id: string;
name: string;
year: number | null;
poster: string | null;
episode: {
id: string;
name: string;
season: string;
seasonNumber: number | null;
episodeNumber: number | null;
overview: string | null;
dateWatched: string | null;
coverArt: string | null;
} | null;
}
interface CacheEntry<T> {
value: T;
expiresAt: number;
}
const playlistCache = new Map<string, CacheEntry<LatestSong | null>>();
const pendingRequests = new Map<string, Promise<LatestSong | null>>();
const seriesCache = new Map<string, CacheEntry<LatestSeries | null>>();
const pendingSeriesRequests = new Map<string, Promise<LatestSeries | null>>();
async function fetchLatestPlaylistSong(
fetch: typeof globalThis.fetch,
playlistId: string
@@ -119,6 +161,97 @@ export async function getLatestPlaylistSong(
return request;
}
async function fetchLatestWatchedSeries(
fetch: typeof globalThis.fetch,
libraryId: string
): Promise<LatestSeries | null> {
const url = new URL(`${JELLYFIN_URL}/Users/${JELLYFIN_USER_ID}/Items`);
url.searchParams.set('ParentId', libraryId);
url.searchParams.set('Recursive', 'true');
url.searchParams.set('IncludeItemTypes', 'Episode');
url.searchParams.set('Filters', 'IsPlayed');
url.searchParams.set('SortBy', 'DatePlayed');
url.searchParams.set('SortOrder', 'Descending');
url.searchParams.set('Limit', '1');
const headers = {
'X-Emby-Token': JELLYFIN_API_KEY
};
const response = await fetch(url, { headers });
if (!response.ok) {
const body = await response.text();
throw new Error(`Jellyfin error: ${response.status} - ${body}`);
}
const data: EpisodesResponse = await response.json();
const episode = data.Items?.[0];
if (!episode || !episode.SeriesId) return null;
return {
id: episode.SeriesId,
name: episode.SeriesName ?? 'Unknown series',
year: episode.ProductionYear ?? null,
// Series poster
poster: `/posters/${encodeURIComponent(episode.SeriesId)}`,
// Most recently watched episode
episode: {
id: episode.Id,
name: episode.Name,
season: episode.SeasonName ?? 'Unknown season',
seasonNumber: episode.ParentIndexNumber ?? null,
episodeNumber: episode.IndexNumber ?? null,
overview: episode.Overview ?? null,
dateWatched: episode.UserData?.LastPlayedDate ?? null,
// Episode artwork
coverArt: `/artwork/${encodeURIComponent(episode.Id)}`
}
};
}
export async function getLatestWatchedSeries(
fetch: typeof globalThis.fetch,
libraryId: string
): Promise<LatestSeries | null> {
const cached = seriesCache.get(libraryId);
if (cached && cached.expiresAt > Date.now()) {
return cached.value;
}
const pending = pendingSeriesRequests.get(libraryId);
if (pending) return pending;
const request = fetchLatestWatchedSeries(fetch, libraryId)
.then((series) => {
seriesCache.set(libraryId, {
value: series,
expiresAt: Date.now() + CACHE_TTL
});
return series;
})
.finally(() => {
pendingSeriesRequests.delete(libraryId);
});
pendingSeriesRequests.set(libraryId, request);
return request;
}
export function invalidatePlaylistCache(playlistId: string): void {
playlistCache.delete(playlistId);
}
export function invalidateSeriesCache(libraryId: string): void {
seriesCache.delete(libraryId);
}

View File

@@ -1,15 +1,19 @@
import type { PageServerLoad } from './$types';
import { getLatestPlaylistSong } from '#lib/server/jellyfin';
import { JELLYFIN_PLAYLIST_ID } from '$app/env/private';
import { getLatestPlaylistSong, getLatestWatchedSeries } from '#lib/server/jellyfin';
import { JELLYFIN_PLAYLIST_ID, JELLYFIN_LIBRARY_ID } from '$app/env/private';
export const load: PageServerLoad = () => {
const latestSong = getLatestPlaylistSong(globalThis.fetch, JELLYFIN_PLAYLIST_ID);
console.log(JELLYFIN_LIBRARY_ID);
const latestSeries = getLatestWatchedSeries(globalThis.fetch, JELLYFIN_LIBRARY_ID);
latestSong.catch(() => {});
latestSeries.catch(() => {});
return {
streamed: {
latestSong
latestSong,
latestSeries
}
};
};

View File

@@ -66,7 +66,48 @@
<p>{error}</p>
{/await}
</div>
<div class="sub-container" style="--container-color:var(--ctp-peach);">watching</div>
<div
class="sub-container flex items-center gap-3 overflow-hidden pr-3"
style="--container-color:var(--ctp-peach);"
>
{#await data.streamed.latestSeries}
<p>Loading Latest Watched Series...</p>
{:then series}
<img
src={series.poster}
class="aspect-1/1 h-full w-auto shrink-0 object-contain"
alt=""
/>
<div class="flex min-w-0 flex-col justify-center">
<p class="fira-mono-medium">Currently Watching…</p>
<div
id="music-title-block"
onclick={() =>
window.open(`https://thetvdb.com/search?query=${series.name}`, '_blank')}
style="cursor: pointer;"
role="link"
onkeydown={(e) => {
if (e.key === 'Enter') {
}
}}
tabindex="0"
title="{series.name} S{series.episode.seasonNumber}E{series.episode
.episodeNumber} - {series.episode.name}"
class="pl-2"
>
<p class="fira-mono-bold w-full truncate text-2xl">
{series.name}
</p>
<p class="fira-mono-medium w-full truncate text-xl">
S{series.episode.seasonNumber}E{series.episode.episodeNumber} - {series.episode
.name}
</p>
</div>
</div>
{:catch error}
<p>{error}</p>
{/await}
</div>
<div class="sub-container" style="--container-color:var(--ctp-red);">reading</div>
</div>
</div>

View File

@@ -0,0 +1,32 @@
import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { JELLYFIN_URL, JELLYFIN_API_KEY } from '$app/env/private';
export const GET: RequestHandler = async ({ params, fetch }) => {
const { itemId } = params;
if (!/^[a-zA-Z0-9-]+$/.test(itemId)) {
error(400, 'Invalid item ID');
}
const response = await fetch(
`${JELLYFIN_URL}/Items/${encodeURIComponent(itemId)}/Images/Primary`,
{
headers: {
'X-Emby-Token': JELLYFIN_API_KEY
}
}
);
if (!response.ok) {
error(response.status, 'Poster unavailable');
}
return new Response(response.body, {
headers: {
'Content-Type': response.headers.get('Content-Type') ?? 'image/jpeg',
'Cache-Control': 'private, max-age=3600'
}
});
};