Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
22 changes: 18 additions & 4 deletions apps/server/src/modules/jellyfin/application/jellyfin-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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) {
Expand All @@ -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 };
Expand Down Expand Up @@ -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<JellyfinEvent, { kind: "episode-started" }>): Promise<Outcome> {
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,
Expand Down Expand Up @@ -161,7 +175,7 @@ export class JellyfinService {
}
}

private async resolveSeries(event: Extract<JellyfinEvent, { kind: "episode-watched" }>) {
private async resolveSeries(event: EpisodeEvent) {
const known = event.jellyfinSeriesId
? this.db.select().from(jellyfinSeries).where(eq(jellyfinSeries.jellyfinSeriesId, event.jellyfinSeriesId)).get()
: undefined;
Expand Down
10 changes: 10 additions & 0 deletions apps/server/src/modules/jellyfin/domain/jellyfin-event.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
29 changes: 17 additions & 12 deletions apps/server/src/modules/jellyfin/domain/jellyfin-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -30,7 +34,8 @@ export function parseJellyfinEvent(body: Record<string, unknown>): 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);
Expand All @@ -40,7 +45,7 @@ export function parseJellyfinEvent(body: Record<string, unknown>): JellyfinEvent
return { kind: "ignored", reason: t().webhook.incomplete };
}
return {
kind: "episode-watched",
kind: watched ? "episode-watched" : "episode-started",
seriesName,
season,
number,
Expand Down
16 changes: 16 additions & 0 deletions apps/server/src/modules/tracking/application/tracking-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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));
}
Expand Down
4 changes: 4 additions & 0 deletions apps/server/src/shared/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
};

Expand Down Expand Up @@ -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",
},
};

Expand Down
7 changes: 4 additions & 3 deletions apps/web/src/i18n/en.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,21 +222,22 @@ 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: [
(b: Bold) => <>Install the {b("Webhook")} plugin (Dashboard → Plugins → Catalog) and restart.</>,
(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`,
Expand Down
7 changes: 4 additions & 3 deletions apps/web/src/i18n/fr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -214,22 +214,23 @@ 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: [
(b) => <>Installez le plugin {b("Webhook")} (Tableau de bord → Plugins → Catalogue) et redémarrez.</>,
(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`,
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/pages/settings/webhook-history.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) {
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading