diff --git a/README.md b/README.md index 4781d3e..f77c187 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,9 @@ To back up the whole instance, copy `DATA_DIR` while Snug is stopped. Each user 1. Install the **Webhook** plugin (Dashboard → Plugins → Catalog) and restart Jellyfin. 2. Add a **Generic Destination** with your webhook URL from Snug → Settings → Integrations → Jellyfin. -3. Tick **Playback Stop** and **User Data Saved**, select your user, tick **Send All Properties**. +3. Tick **Playback Start**, **Playback Stop** and **User Data Saved**, select your user, tick **Send All Properties**. + +Finished episodes are marked watched; a series you start that Snug doesn't follow yet (or only has on the Watchlist) moves to Watching as soon as playback begins. > [!TIP] > The URL must be reachable **from Jellyfin's container**: use Snug's LAN address or `host.docker.internal`, not `localhost`. diff --git a/apps/server/src/modules/jellyfin/application/jellyfin-service.test.ts b/apps/server/src/modules/jellyfin/application/jellyfin-service.test.ts index 824aa45..bde10c0 100644 --- a/apps/server/src/modules/jellyfin/application/jellyfin-service.test.ts +++ b/apps/server/src/modules/jellyfin/application/jellyfin-service.test.ts @@ -128,3 +128,64 @@ test("the UserDataSaved call that follows a finished Episode is ignored, but a l now = new Date(now.getTime() + 2 * 60 * 60_000); expect((await service.handle("token", stop)).outcome).toBe("watched"); }); + +test("starting a Series Snug doesn't follow adds it to Watching; one already followed keeps its Status", async () => { + const { db } = testDb(); + const series = (tmdbId: number, name: string): Series => ({ + tmdbId, + tvdbId: null, + name, + year: 2026, + overview: "", + posterPath: null, + backdropPath: null, + ended: false, + episodes: [ + { season: 1, number: 1, name: "E1", airDate: "2026-01-01" }, + { season: 1, number: 2, name: "E2", airDate: "2026-01-08" }, + ], + fetchedAt: new Date(), + }); + const catalog = { + resolve: async (hint: { tmdbId?: number }) => hint.tmdbId ?? null, + ensure: async (tmdbId: number) => series(tmdbId, `Series ${tmdbId}`), + refresh: async (tmdbId: number) => series(tmdbId, `Series ${tmdbId}`), + } as unknown as CatalogService; + const tracking = new TrackingService(new DrizzleTrackedSeriesRepository(db), catalog); + const identity = { + webhookTokens: { userIdOf: () => "u" }, + nameOf: () => "U", + preferences: () => DEFAULT_PREFERENCES, + } as unknown as IdentityService; + const notifications: Notification[] = []; + const notifier: Notifier = { notify: async (_, notification) => void notifications.push(notification) }; + const service = new JellyfinService(db, identity, catalog, tracking, notifier); + const start = (tmdbId: number) => + service.handle("token", { + NotificationType: "PlaybackStart", + ItemType: "Episode", + SeriesName: `Series ${tmdbId}`, + SeriesProvider_tmdb: String(tmdbId), + SeasonNumber: 1, + EpisodeNumber: 1, + }); + + // Untracked: Watching, nothing marked watched yet. + expect(await start(1)).toEqual({ outcome: "added", message: "Series 1 added to Watching" }); + const added = await tracking.detail("u", 1); + expect(added.status).toBe("watching"); + expect(added.progress).toBeNull(); + + // The Watchlist moves to Watching; a paused Series stays paused. + await tracking.track("u", 2, "watchlist"); + expect((await start(2)).outcome).toBe("added"); + expect((await tracking.detail("u", 2)).status).toBe("watching"); + await tracking.track("u", 3, "paused"); + expect(await start(3)).toEqual({ outcome: "ignored", message: "Already followed" }); + expect((await tracking.detail("u", 3)).status).toBe("paused"); + + // Starting the next Episode of a Series already Watching changes nothing, and no notification is sent. + expect((await start(1)).outcome).toBe("ignored"); + await Bun.sleep(0); + expect(notifications).toHaveLength(0); +}); diff --git a/apps/server/src/modules/jellyfin/application/jellyfin-service.ts b/apps/server/src/modules/jellyfin/application/jellyfin-service.ts index d2c0447..2bbac72 100644 --- a/apps/server/src/modules/jellyfin/application/jellyfin-service.ts +++ b/apps/server/src/modules/jellyfin/application/jellyfin-service.ts @@ -8,7 +8,7 @@ import { ForbiddenError } from "@/shared/errors"; import { moduleLogger, reason } from "@/shared/logger"; import type { Notifier } from "@/modules/notifications/application/notification-service"; import type { TrackingService } from "@/modules/tracking/application/tracking-service"; -import { type JellyfinEvent, parseJellyfinEvent } from "@/modules/jellyfin/domain/jellyfin-event"; +import { type EpisodeEvent, type JellyfinEvent, parseJellyfinEvent } from "@/modules/jellyfin/domain/jellyfin-event"; import { jellyfinEvents, jellyfinSeries } from "@/modules/jellyfin/infrastructure/schema"; import { episodeLabel, t } from "@/shared/i18n"; import { today } from "@/shared/day"; @@ -60,11 +60,14 @@ export class JellyfinService { const summary = event.kind === "episode-watched" ? `${event.seriesName} ${episodeCode(event)}` - : `${String(body.NotificationType ?? "?")} · ${String(body.Name ?? body.ItemType ?? "")}`; + : event.kind === "episode-started" + ? `▶ ${event.seriesName} ${episodeCode(event)}` + : `${String(body.NotificationType ?? "?")} · ${String(body.Name ?? body.ItemType ?? "")}`; let result: Outcome; try { if (event.kind === "ignored") result = { outcome: "ignored", message: event.reason }; + else if (event.kind === "episode-started") result = await this.start(userId, event); else if (this.justWatched(userId, summary)) result = { outcome: "ignored", message: t().webhook.duplicate }; else result = await this.watch(userId, event); } catch (error) { @@ -73,7 +76,7 @@ export class JellyfinService { this.log(userId, summary, result, body); // Ignored calls come in bursts (UserDataSaved on every pause), so they only show at debug. const line = `${this.identity.nameOf(userId)} · ${summary} → ${result.outcome}: ${result.message}`; - if (result.outcome === "watched") log.info(line); + if (result.outcome === "watched" || result.outcome === "added") log.info(line); else if (result.outcome === "ignored") log.debug(line); else log.warn(line); return { outcome: result.outcome, message: result.message }; @@ -132,6 +135,17 @@ export class JellyfinService { return { outcome: "watched", message: t().webhook.marked(series.name, label(event)), seriesId }; } + /** Playback began: the Series shows in Snug from the first minute, not once the Episode is over. */ + private async start(userId: string, event: Extract): Promise { + if (event.season === 0) return { outcome: "ignored", message: t().webhook.specials }; + const seriesId = await this.resolveSeries(event); + if (!seriesId) return { outcome: "error", message: t().webhook.notFound }; + const { name } = await this.catalog.ensure(seriesId); + return (await this.tracking.startWatching(userId, seriesId)) + ? { outcome: "added", message: t().webhook.added(name), seriesId } + : { outcome: "ignored", message: t().webhook.alreadyTracked, seriesId }; + } + /** "✓ Severance S02E05", with what comes next; a season marked at once collapses into one notification. */ private async announce( userId: string, @@ -161,7 +175,7 @@ export class JellyfinService { } } - private async resolveSeries(event: Extract) { + private async resolveSeries(event: EpisodeEvent) { const known = event.jellyfinSeriesId ? this.db.select().from(jellyfinSeries).where(eq(jellyfinSeries.jellyfinSeriesId, event.jellyfinSeriesId)).get() : undefined; diff --git a/apps/server/src/modules/jellyfin/domain/jellyfin-event.test.ts b/apps/server/src/modules/jellyfin/domain/jellyfin-event.test.ts index fde5f74..34f689f 100644 --- a/apps/server/src/modules/jellyfin/domain/jellyfin-event.test.ts +++ b/apps/server/src/modules/jellyfin/domain/jellyfin-event.test.ts @@ -40,3 +40,13 @@ test("partial playback, unmarking and movies are ignored", () => { expect(parseJellyfinEvent(body).kind).toBe("ignored"); } }); + +test("starting an episode is a start, not a watch", () => { + expect(parseJellyfinEvent({ ...episode, NotificationType: "PlaybackStart" })).toMatchObject({ + kind: "episode-started", + seriesName: "Severance", + season: 2, + number: 5, + }); + expect(parseJellyfinEvent({ ...episode, NotificationType: "PlaybackStart", ItemType: "Movie" }).kind).toBe("ignored"); +}); diff --git a/apps/server/src/modules/jellyfin/domain/jellyfin-event.ts b/apps/server/src/modules/jellyfin/domain/jellyfin-event.ts index c3eb296..5c7405b 100644 --- a/apps/server/src/modules/jellyfin/domain/jellyfin-event.ts +++ b/apps/server/src/modules/jellyfin/domain/jellyfin-event.ts @@ -4,17 +4,21 @@ */ import { t } from "@/shared/i18n"; +/** The Episode a call is about, and what Jellyfin knows to find its Series. */ +export interface EpisodeEvent { + seriesName: string; + season: number; + number: number; + jellyfinSeriesId?: string; + seriesTmdbId?: number; + tvdbEpisodeId?: string; + imdbEpisodeId?: string; +} + +/** Watched: finished or ticked played. Started: playback began (Playback Start), so the Series shows in Snug right away. */ export type JellyfinEvent = - | { - kind: "episode-watched"; - seriesName: string; - season: number; - number: number; - jellyfinSeriesId?: string; - seriesTmdbId?: number; - tvdbEpisodeId?: string; - imdbEpisodeId?: string; - } + | ({ kind: "episode-watched" } & EpisodeEvent) + | ({ kind: "episode-started" } & EpisodeEvent) | { kind: "ignored"; reason: string }; const truthy = (v: unknown) => v === true || (typeof v === "string" && v.toLowerCase() === "true"); @@ -30,7 +34,8 @@ export function parseJellyfinEvent(body: Record): JellyfinEvent const watched = (type === "PlaybackStop" && truthy(body.PlayedToCompletion)) || (type === "UserDataSaved" && truthy(body.Played) && (!body.SaveReason || body.SaveReason === "TogglePlayed")); - if (!watched) return { kind: "ignored", reason: `${type ?? "Unknown"} event without a completed watch` }; + const started = type === "PlaybackStart"; + if (!watched && !started) return { kind: "ignored", reason: `${type ?? "Unknown"} event without a completed watch` }; if (body.ItemType !== "Episode") return { kind: "ignored", reason: `${str(body.ItemType) ?? "Item"} is not an episode` }; const season = int(body.SeasonNumber); @@ -40,7 +45,7 @@ export function parseJellyfinEvent(body: Record): JellyfinEvent return { kind: "ignored", reason: t().webhook.incomplete }; } return { - kind: "episode-watched", + kind: watched ? "episode-watched" : "episode-started", seriesName, season, number, diff --git a/apps/server/src/modules/tracking/application/tracking-service.ts b/apps/server/src/modules/tracking/application/tracking-service.ts index 9325020..99aa25d 100644 --- a/apps/server/src/modules/tracking/application/tracking-service.ts +++ b/apps/server/src/modules/tracking/application/tracking-service.ts @@ -79,6 +79,22 @@ export class TrackingService { }); } + /** + * A Series started on a media server: untracked or on the Watchlist, it becomes Watching; any other Status + * (paused, dropped, a rewatch of a completed one…) is left alone. Returns whether it changed. + */ + async startWatching(userId: string, seriesId: number): Promise { + const series = await this.catalog.ensure(seriesId); + return this.exclusive(userId, seriesId, async () => { + const existing = await this.repo.find(userId, seriesId); + if (existing && existing.status !== "watchlist") return false; + const tracked = existing ?? TrackedSeries.start(userId, seriesId, "watching", this.now()); + tracked.choose("watching", series, today(this.now())); + await this.repo.save(tracked); + return true; + }); + } + untrack(userId: string, seriesId: number) { return this.exclusive(userId, seriesId, () => this.repo.delete(userId, seriesId)); } diff --git a/apps/server/src/shared/i18n.ts b/apps/server/src/shared/i18n.ts index 05d03f4..b242e98 100644 --- a/apps/server/src/shared/i18n.ts +++ b/apps/server/src/shared/i18n.ts @@ -75,6 +75,8 @@ const en = { marked: (series: string, code: string) => `Marked ${series} ${code} as watched`, incomplete: "Missing series name, season or episode number", duplicate: "Already marked as watched a moment ago", + added: (series: string) => `${series} added to Watching`, + alreadyTracked: "Already followed", }, }; @@ -150,6 +152,8 @@ const fr: Messages = { marked: (series, code) => `${series} ${code} marqué vu`, incomplete: "Nom de la série, saison ou numéro d'épisode manquant", duplicate: "Déjà marqué vu à l'instant", + added: (series) => `${series} ajoutée à En cours`, + alreadyTracked: "Déjà suivie", }, }; diff --git a/apps/web/src/i18n/en.tsx b/apps/web/src/i18n/en.tsx index 906f95e..db2750d 100644 --- a/apps/web/src/i18n/en.tsx +++ b/apps/web/src/i18n/en.tsx @@ -222,7 +222,7 @@ export const en = { jellyfin: { title: "Jellyfin", term: "Webhook", - description: "Episodes you finish in Jellyfin are marked watched in Snug.", + description: "Episodes you finish in Jellyfin are marked watched in Snug, and a series you start shows up right away.", neverCalled: "Never called", url: "webhook URL", steps: [ @@ -230,13 +230,14 @@ export const en = { (b: Bold) => <>Plugins → Webhook → {b("Add Generic Destination")}, paste the URL below., (b: Bold) => ( <> - Tick {b("Playback Stop")} and {b("User Data Saved")}, select your user, tick {b("Send All Properties")}, save. + Tick {b("Playback Start")}, {b("Playback Stop")} and {b("User Data Saved")}, select your user, tick{" "} + {b("Send All Properties")}, save. ), ], history: "Webhook history", historyFilter: "Webhook history filter", - outcomes: { all: "All", watched: "Watched", ignored: "Ignored", error: "Errors" }, + outcomes: { all: "All", watched: "Watched", added: "Added", ignored: "Ignored", error: "Errors" }, noMatch: "Nothing matches this filter.", noCalls: "No calls yet. Finish an episode in Jellyfin to see one here.", showMore: (n: number) => `Show ${n} more`, diff --git a/apps/web/src/i18n/fr.tsx b/apps/web/src/i18n/fr.tsx index a8da778..e04a8df 100644 --- a/apps/web/src/i18n/fr.tsx +++ b/apps/web/src/i18n/fr.tsx @@ -214,7 +214,7 @@ export const fr: Messages = { jellyfin: { title: "Jellyfin", term: "Webhook", - description: "Les épisodes finis dans Jellyfin sont marqués vus dans Snug.", + description: "Les épisodes finis dans Jellyfin sont marqués vus dans Snug, et une série lancée y apparaît tout de suite.", neverCalled: "Jamais appelé", url: "l'URL du webhook", steps: [ @@ -222,14 +222,15 @@ export const fr: Messages = { (b) => <>Plugins → Webhook → {b("Add Generic Destination")}, collez l'URL ci-dessous., (b) => ( <> - Cochez {b("Playback Stop")} et {b("User Data Saved")}, choisissez votre utilisateur, cochez{" "} + Cochez {b("Playback Start")}, {b("Playback Stop")} et {b("User Data Saved")}, choisissez votre utilisateur, + cochez{" "} {b("Send All Properties")}, enregistrez. ), ], history: "Historique du webhook", historyFilter: "Filtre de l'historique", - outcomes: { all: "Tout", watched: "Vus", ignored: "Ignorés", error: "Erreurs" }, + outcomes: { all: "Tout", watched: "Vus", added: "Ajoutées", ignored: "Ignorés", error: "Erreurs" }, noMatch: "Rien ne correspond à ce filtre.", noCalls: "Aucun appel pour l'instant. Finissez un épisode dans Jellyfin pour en voir un ici.", showMore: (n) => `Afficher ${n} de plus`, diff --git a/apps/web/src/pages/settings/webhook-history.tsx b/apps/web/src/pages/settings/webhook-history.tsx index 2dd2a6e..7624d53 100644 --- a/apps/web/src/pages/settings/webhook-history.tsx +++ b/apps/web/src/pages/settings/webhook-history.tsx @@ -6,8 +6,8 @@ import { Chips, cx, Skeleton } from "@/components/ui"; import { useT } from "@/i18n"; import { ago } from "@/lib/format"; -const OUTCOMES = ["all", "watched", "ignored", "error"] as const; -const DOT = { watched: "bg-sage", ignored: "bg-muted/50", error: "bg-rose" }; +const OUTCOMES = ["all", "watched", "added", "ignored", "error"] as const; +const DOT = { watched: "bg-sage", added: "bg-accent", ignored: "bg-muted/50", error: "bg-rose" }; /** Every call Jellyfin made to the webhook, newest first, with what Snug did and the raw payload. */ export function WebhookHistory({ events }: { events: JellyfinEventLog[] | undefined }) { diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index a8af4c9..bc4042e 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -290,7 +290,8 @@ export interface ImportProgress { export interface JellyfinEventLog { receivedAt: string; summary: string; - outcome: "watched" | "ignored" | "error"; + /** "added": a Series started in Jellyfin that Snug didn't follow (or only had on the Watchlist) is now Watching. */ + outcome: "watched" | "added" | "ignored" | "error"; message: string; /** Series the call was resolved to, when it was. */ seriesId: number | null;