-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathjellyfinWebhook.js
More file actions
1478 lines (1325 loc) · 53.3 KB
/
jellyfinWebhook.js
File metadata and controls
1478 lines (1325 loc) · 53.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
EmbedBuilder,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
} from "discord.js";
import axios from "axios";
import debounce from "lodash.debounce";
import { minutesToHhMm } from "./utils/time.js";
import logger from "./utils/logger.js";
import { fetchOMDbData } from "./api/omdb.js";
import { findBestBackdrop } from "./api/tmdb.js";
import { isValidUrl } from "./utils/url.js";
import {
getLibraryChannels,
resolveTargetChannel,
getLibraryAnimeFlag,
buildIdentityKey,
} from "./jellyfin/libraryResolver.js";
import { PersistentMap } from "./utils/persistentMap.js";
const debouncedSenders = new Map();
// Persistent so dedup state survives container restarts (otherwise a restart
// re-notifies anything in the recently-added window via the next poll/WS reconnect).
const sentNotifications = new PersistentMap(
"sent-notifications",
7 * 24 * 60 * 60 * 1000, // 7 days — survive Sonarr/Radarr upgrade cycles
{ validateValue: (v) => v && typeof v.level === "number" }
);
// Sweep stale "in-progress" markers (level: -1) from a previous run. Their
// associated debouncer is gone after restart, so the marker would otherwise
// block notifications for that series until its 5-min TTL expires.
const staleMarkers = sentNotifications.prune(
(_key, value) => value?.level === -1
);
if (staleMarkers > 0) {
logger.info(
`[DEDUP] Cleared ${staleMarkers} stale in-progress markers from previous run`
);
}
const episodeMessages = new Map(); // Track Discord messages for editing: SeriesId -> { messageId, channelId }
const creatingDebouncers = new Set(); // Prevent race condition: track SeriesIds currently creating debouncers
// API response cache to reduce external API calls
const apiCache = new Map(); // tmdbId -> { data, timestamp }
const API_CACHE_DURATION_MS = 6 * 60 * 60 * 1000; // 6 hours
// Library cache to avoid repeated API calls at webhook time
const libraryCache = {
data: null,
timestamp: null,
isValid: function () {
return (
this.data &&
this.timestamp &&
Date.now() - this.timestamp < 15 * 60 * 1000
); // 15 min cache
},
set: function (libraries) {
this.data = libraries;
this.timestamp = Date.now();
},
get: function () {
return this.isValid() ? this.data : null;
},
};
// Cleanup configuration
const CLEANUP_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
const CLEANUP_THRESHOLD_MS = 14 * 24 * 60 * 60 * 1000; // 14 days — periodic cleanup of stale debouncers
const DEFAULT_DEBOUNCE_MS = 60000; // 60 seconds
const NEW_SERIES_DEBOUNCE_MS = 120000; // 2 minutes - longer debounce for episodes/seasons of new series
const SEASON_NOTIFICATION_DELAY_MS = 3 * 60 * 1000; // 3 minutes - allow season notifications after this delay
// Periodic cleanup for old debouncer entries and API cache (prevent memory leaks on long-running servers)
setInterval(() => {
const now = Date.now();
const sevenDaysAgo = now - CLEANUP_THRESHOLD_MS;
let cleanedDebouncers = 0;
for (const [seriesId, data] of debouncedSenders.entries()) {
// Check if debouncer has a timestamp and is older than 7 days
if (data.timestamp && data.timestamp < sevenDaysAgo) {
debouncedSenders.delete(seriesId);
creatingDebouncers.delete(seriesId); // Also cleanup from creatingDebouncers
cleanedDebouncers++;
}
}
// Clean up old API cache entries
let cleanedCache = 0;
for (const [key, cached] of apiCache.entries()) {
if (now - cached.timestamp > API_CACHE_DURATION_MS) {
apiCache.delete(key);
cleanedCache++;
}
}
if (cleanedDebouncers > 0 || cleanedCache > 0) {
logger.debug(
`Periodic cleanup: Removed ${cleanedDebouncers} old debouncer(s), ${cleanedCache} expired cache entries`
);
}
}, CLEANUP_INTERVAL_MS);
function getItemLevel(itemType) {
switch (itemType) {
case "Series":
return 3;
case "Season":
return 2;
case "Episode":
return 1;
default:
return 0;
}
}
// Build a Jellyfin URL that preserves a potential subpath (e.g., /jellyfin)
// and appends the provided path and optional hash fragment safely.
// Always uses the configured JELLYFIN_BASE_URL — the webhook-provided ServerUrl
// is not trusted as it could be poisoned via Jellyfin metadata.
function buildJellyfinUrl(_baseUrl, appendPath, hash) {
const effectiveBaseUrl = process.env.JELLYFIN_BASE_URL;
try {
const u = new URL(effectiveBaseUrl);
let p = u.pathname || "/";
if (!p.endsWith("/")) p += "/";
const pathClean = String(appendPath || "").replace(/^\/+/, "");
u.pathname = p + pathClean;
if (hash != null) {
const h = String(hash);
u.hash = h.startsWith("#") ? h.slice(1) : h;
}
return u.toString();
} catch (_e) {
logger.warn(`buildJellyfinUrl: Invalid JELLYFIN_BASE_URL "${effectiveBaseUrl}": ${_e?.message}. Falling back to string concatenation.`);
const baseNoSlash = String(effectiveBaseUrl || "").replace(/\/+$/, "");
const pathNoLead = String(appendPath || "").replace(/^\/+/, "");
const h = hash
? String(hash).startsWith("#")
? String(hash)
: `#${hash}`
: "";
return `${baseNoSlash}/${pathNoLead}${h}`;
}
}
/**
* Clean title by removing Jellyfin/TMDB metadata like [tvdbid-123], [imdbid-123], (?), etc.
* @param {string} title - Original title from Jellyfin
* @returns {string} Cleaned title
*/
function cleanTitle(title) {
if (!title) return title;
// Remove metadata patterns like [tvdbid-123], [imdbid-123], (?)
return title
.replace(/\[tvdbid-\d+\]/gi, "")
.replace(/\[imdbid-\d+\]/gi, "")
.replace(/\(\?\)$/, "")
.trim();
}
async function processAndSendNotification(
data,
client,
pendingRequests,
targetChannelId = null,
episodeCount = 0,
episodeDetails = null,
seasonCount = 0,
seasonDetails = null,
isTestNotif = false,
onPendingRequestsChanged = null,
isAnimeLibrary = false
) {
const {
ItemType,
ItemId,
SeasonId,
SeriesId,
Name,
SeriesName,
IndexNumber,
Year,
Overview,
RunTime,
Genres,
Provider_imdb: imdbIdFromWebhook, // Renamed to avoid conflict
ServerUrl,
ServerId,
SeasonNumber,
EpisodeNumber,
Video_0_Height,
Video_0_Codec,
Video_0_VideoRange,
Audio_0_Codec,
Audio_0_Channels,
Audio_0_Language,
} = data;
// We need to fetch details from TMDB to get the backdrop
const tmdbId = data.Provider_tmdb;
const testPrefix = isTestNotif ? "[TEST NOTIFICATION] " : "";
logger.info(
`${testPrefix}Webhook received: ItemType=${ItemType}, Name=${Name}, tmdbId=${tmdbId}, Provider_imdb=${data.Provider_imdb}${isAnimeLibrary ? " [anime library]" : ""}`
);
// Get embed customization settings from environment
const showBackdrop = process.env.EMBED_SHOW_BACKDROP !== "false";
const showOverview = process.env.EMBED_SHOW_OVERVIEW !== "false";
const showGenre = process.env.EMBED_SHOW_GENRE !== "false";
const showRuntime = process.env.EMBED_SHOW_RUNTIME !== "false";
const showRating = process.env.EMBED_SHOW_RATING !== "false";
const showButtonLetterboxd = process.env.EMBED_SHOW_BUTTON_LETTERBOXD !== "false";
const showButtonImdb = process.env.EMBED_SHOW_BUTTON_IMDB !== "false";
const showButtonWatch = process.env.EMBED_SHOW_BUTTON_WATCH !== "false";
// Check if anyone requested this content
const notifyEnabled = process.env.NOTIFY_ON_AVAILABLE === "true";
let usersToNotify = [];
if (notifyEnabled && tmdbId && pendingRequests) {
const movieKey = `${tmdbId}-movie`;
const tvKey = `${tmdbId}-tv`;
logger.debug(
`Checking pending requests. notifyEnabled=${notifyEnabled}, tmdbId=${tmdbId}`
);
logger.debug(`Pending requests keys:`, Array.from(pendingRequests.keys()));
if (ItemType === "Movie" && pendingRequests.has(movieKey)) {
usersToNotify = Array.from(pendingRequests.get(movieKey));
pendingRequests.delete(movieKey);
if (onPendingRequestsChanged) onPendingRequestsChanged();
logger.info(
`Found ${usersToNotify.length} users to notify for movie ${tmdbId}`
);
} else if (
(ItemType === "Series" ||
ItemType === "Season" ||
ItemType === "Episode") &&
pendingRequests.has(tvKey)
) {
usersToNotify = Array.from(pendingRequests.get(tvKey));
pendingRequests.delete(tvKey);
if (onPendingRequestsChanged) onPendingRequestsChanged();
logger.info(
`Found ${usersToNotify.length} users to notify for TV show ${tmdbId}`
);
} else {
logger.debug(`No matching pending requests found for ${tmdbId}`);
}
} else {
logger.debug(
`Notification check skipped: notifyEnabled=${notifyEnabled}, tmdbId=${tmdbId}, hasPendingRequests=${!!pendingRequests}`
);
}
let details = null;
if (tmdbId) {
// Check cache first
const cacheKey = `tmdb-${ItemType}-${tmdbId}`;
const cached = apiCache.get(cacheKey);
const now = Date.now();
if (cached && now - cached.timestamp < API_CACHE_DURATION_MS) {
details = cached.data;
logger.debug(`Using cached TMDB data for ${tmdbId}`);
} else {
try {
const tmdbIdNum = parseInt(tmdbId, 10);
const res = await axios.get(
`https://api.themoviedb.org/3/${
ItemType === "Movie" ? "movie" : "tv"
}/${tmdbIdNum}`,
{
params: {
api_key: process.env.TMDB_API_KEY,
append_to_response: "images,external_ids",
},
}
);
details = res.data;
// Cache the response
apiCache.set(cacheKey, { data: details, timestamp: now });
logger.debug(`Cached TMDB data for ${tmdbId}`);
} catch (e) {
logger.warn(`Could not fetch TMDB details for ${tmdbId}: ${e?.message || e}`);
}
}
}
// Prioritize IMDb ID from TMDB, fallback to webhook
const imdbId = details?.external_ids?.imdb_id || imdbIdFromWebhook;
const omdb = imdbId ? await fetchOMDbData(imdbId) : null;
let runtime = "Unknown";
// Prioritize webhook runtime data for episodes
if (ItemType === "Episode" && RunTime) {
runtime = RunTime; // Webhook already provides formatted runtime like "00:25:02"
} else if (omdb?.Runtime && omdb.Runtime !== "N/A") {
const match = String(omdb.Runtime).match(/(\d+)/);
if (match) runtime = minutesToHhMm(parseInt(match[1], 10));
} else if (ItemType === "Movie" && details?.runtime > 0) {
runtime = minutesToHhMm(details.runtime);
} else if (
(ItemType === "Series" || ItemType === "Season") &&
details &&
Array.isArray(details.episode_run_time) &&
details.episode_run_time.length > 0
) {
runtime = minutesToHhMm(details.episode_run_time[0]);
}
const rating = omdb?.imdbRating ? `${omdb.imdbRating}/10` : "N/A";
const genreList = Array.isArray(Genres)
? Genres.join(", ")
: Genres || omdb?.Genre || "Unknown";
let overviewText =
Overview?.trim() || omdb?.Plot || "No description available.";
let headerLine = "Summary";
if (omdb) {
if (ItemType === "Movie" && omdb.Director && omdb.Director !== "N/A") {
headerLine = `Directed by ${omdb.Director}`;
} else if (omdb.Writer && omdb.Writer !== "N/A") {
const creator = omdb.Writer.split(",")[0].trim();
headerLine = `Created by ${creator}`;
}
}
// Build quality info from webhook data
let qualityInfo = "";
if (Video_0_Height && Video_0_Codec) {
const videoQuality =
Video_0_Height >= 2160
? "4K"
: Video_0_Height >= 1440
? "1440p"
: Video_0_Height >= 1080
? "1080p"
: Video_0_Height >= 720
? "720p"
: `${Video_0_Height}p`;
const videoCodec = Video_0_Codec.toUpperCase();
const hdr =
Video_0_VideoRange && Video_0_VideoRange !== "SDR"
? ` ${Video_0_VideoRange}`
: "";
qualityInfo = `${videoQuality} ${videoCodec}${hdr}`;
if (Audio_0_Codec && Audio_0_Channels) {
const audioCodec = Audio_0_Codec.toUpperCase();
const channels =
Audio_0_Channels === 6
? "5.1"
: Audio_0_Channels === 8
? "7.1"
: Audio_0_Channels === 2
? "Stereo"
: `${Audio_0_Channels}ch`;
qualityInfo += ` • ${audioCodec} ${channels}`;
}
}
let embedTitle = "";
let authorName = "";
// Clean names from Jellyfin metadata
const cleanedName = cleanTitle(Name);
// For Series items, SeriesName might be undefined, so fallback to Name
const cleanedSeriesName = cleanTitle(SeriesName || Name);
switch (ItemType) {
case "Movie":
authorName = "🎬 New movie added!";
embedTitle = `${cleanedName || "Unknown Title"} (${Year || "?"})`;
break;
case "Series":
authorName = "📺 New TV show added!";
embedTitle = `${cleanedSeriesName || "Unknown Series"} (${Year || "?"})`;
break;
case "Season":
if (seasonCount > 1 && seasonDetails) {
authorName = `📺 ${seasonCount} new seasons added!`;
embedTitle = `${cleanedSeriesName || "Unknown Series"} (${Year || "?"})`;
} else {
authorName = "📺 New season added!";
embedTitle = `${cleanedSeriesName || "Unknown Series"} - Season ${SeasonNumber || IndexNumber || "?"}`;
}
break;
case "Episode":
if (episodeCount > 1 && episodeDetails) {
authorName = `📺 ${episodeCount} new episodes added!`;
embedTitle = `${cleanedSeriesName || "Unknown Series"} (${Year || "?"})`;
} else {
authorName = "📺 New episode added!";
const season = String(SeasonNumber || 1).padStart(2, "0");
const episode = String(EpisodeNumber || IndexNumber || 1).padStart(
2,
"0"
);
embedTitle = `${
cleanedSeriesName || "Unknown Series"
} - S${season}E${episode}`;
}
break;
default:
authorName = "✨ New item added";
embedTitle = cleanedName || "Unknown Title";
}
// Smart color coding based on content type and count
// Use custom colors from config or fallback to defaults
let embedColor = process.env.EMBED_COLOR_EPISODE_SINGLE || "#89b4fa"; // Default blue for episodes
if (ItemType === "Movie") {
embedColor = process.env.EMBED_COLOR_MOVIE || "#cba6f7"; // Purple/Mauve for movies
} else if (ItemType === "Series") {
embedColor = process.env.EMBED_COLOR_SERIES || "#cba6f7"; // Purple/Mauve for new series
} else if (ItemType === "Season") {
embedColor = process.env.EMBED_COLOR_SEASON || "#89b4fa"; // Blue for seasons
} else if (ItemType === "Episode") {
if (episodeCount > 5) {
embedColor = process.env.EMBED_COLOR_EPISODE_MANY || "#89b4fa"; // Blue for many episodes
} else if (episodeCount > 1) {
embedColor = process.env.EMBED_COLOR_EPISODE_FEW || "#89b4fa"; // Blue for few episodes
} else {
embedColor = process.env.EMBED_COLOR_EPISODE_SINGLE || "#89b4fa"; // Blue for single episode
}
}
const embed = new EmbedBuilder()
.setAuthor({ name: authorName })
.setTitle(embedTitle);
// Only set URL if ServerUrl is valid
const jellyfinUrl = buildJellyfinUrl(
ServerUrl,
"web/index.html",
`!/details?id=${ItemId}&serverId=${ServerId}`
);
if (isValidUrl(jellyfinUrl)) {
embed.setURL(jellyfinUrl);
}
embed.setColor(embedColor);
// Add fields based on ItemType
if (ItemType === "Episode" && episodeCount <= 1) {
// Single episode: show overview
if (showOverview && overviewText) {
embed.addFields({ name: "Episode Summary", value: overviewText });
}
} else if (ItemType === "Season") {
// Seasons: no fields
} else {
// Movies and Series: Summary, Genre, Runtime, Rating
const fields = [];
if (showOverview) {
fields.push({ name: headerLine, value: overviewText || "No description available." });
}
if (showGenre) {
fields.push({ name: "Genre", value: genreList || "Unknown", inline: true });
}
if (showRuntime) {
fields.push({ name: "Runtime", value: runtime || "Unknown", inline: true });
}
if (showRating) {
fields.push({ name: "Rating", value: rating || "N/A", inline: true });
}
if (fields.length > 0) {
embed.addFields(...fields);
}
}
// Add season list for multiple seasons
if (ItemType === "Season" && seasonCount > 1 && seasonDetails && seasonDetails.seasons.length <= 10) {
const seasonList = seasonDetails.seasons
.sort(
(a, b) =>
(a.SeasonNumber || a.IndexNumber || 0) -
(b.SeasonNumber || b.IndexNumber || 0)
)
.map((s) => {
const seasonNum = s.SeasonNumber || s.IndexNumber || "?";
return `**Season ${seasonNum}**: ${s.Name || `Season ${seasonNum}`}`;
})
.join("\n");
embed.addFields({
name: "Seasons Added",
value: seasonList,
inline: false,
});
} else if (ItemType === "Season" && seasonCount > 10) {
embed.addFields({
name: "Seasons Added",
value: `${seasonCount} seasons (too many to list individually)`,
inline: false,
});
}
// Add episode list for multiple episodes
if (ItemType === "Episode") {
if (
episodeCount > 1 &&
episodeDetails &&
episodeDetails.episodes.length <= 10
) {
const episodeList = episodeDetails.episodes
.sort((a, b) => (a.EpisodeNumber || 0) - (b.EpisodeNumber || 0))
.map((ep) => {
const seasonNum = String(ep.SeasonNumber || 1).padStart(2, "0");
const epNum = String(ep.EpisodeNumber || 0).padStart(2, "0");
return `**S${seasonNum}E${epNum}**: ${ep.Name || "Unknown Episode"}`;
})
.join("\n");
embed.addFields({
name: "Episodes Added",
value: episodeList,
inline: false,
});
} else if (episodeCount > 10) {
embed.addFields({
name: "Episodes Added",
value: `${episodeCount} episodes (too many to list individually)`,
inline: false,
});
}
}
const backdropPath = details ? findBestBackdrop(details) : null;
// Episodes don't have their own backdrop in Jellyfin — fall back to the series.
if (ItemType === "Episode" && !SeriesId) {
logger.warn(
`Episode webhook missing SeriesId; backdrop fallback will use ItemId and likely 404. ItemId=${ItemId}, Name=${Name}`
);
}
const fallbackBackdropItemId =
ItemType === "Episode" && SeriesId ? SeriesId : ItemId;
const backdrop = backdropPath
? `https://image.tmdb.org/t/p/w1280${backdropPath}`
: buildJellyfinUrl(ServerUrl, `Items/${fallbackBackdropItemId}/Images/Backdrop`);
if (showBackdrop && isValidUrl(backdrop)) {
embed.setImage(backdrop);
}
// Series poster thumbnail for single episode notifications
if (ItemType === "Episode" && episodeCount <= 1 && details?.poster_path) {
const posterUrl = `https://image.tmdb.org/t/p/w500${details.poster_path}`;
if (isValidUrl(posterUrl)) embed.setThumbnail(posterUrl);
}
const buttonComponents = [];
if (imdbId) {
if (showButtonLetterboxd) {
const letterboxdUrl = `https://letterboxd.com/imdb/${imdbId}`;
if (isValidUrl(letterboxdUrl)) {
buttonComponents.push(
new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel("Letterboxd")
.setURL(letterboxdUrl)
);
}
}
if (showButtonImdb) {
const imdbUrl = `https://www.imdb.com/title/${imdbId}/`;
if (isValidUrl(imdbUrl)) {
buttonComponents.push(
new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel("IMDb")
.setURL(imdbUrl)
);
}
}
}
if (showButtonWatch) {
const watchUrl = buildJellyfinUrl(
ServerUrl,
"web/index.html",
`!/details?id=${ItemId}&serverId=${ServerId}`
);
if (isValidUrl(watchUrl)) {
buttonComponents.push(
new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel("▶ Watch Now!")
.setURL(watchUrl)
);
} else {
logger.warn(`Invalid watch URL generated: ${watchUrl}. Skipping watch button.`);
}
}
const buttons = buttonComponents.length > 0 ? new ActionRowBuilder().addComponents(buttonComponents) : null;
// Select channel with priority hierarchy:
// 1. Episode/Season specific channel (if enabled and configured)
// 2. Library-specific channel (targetChannelId)
// 3. Default Jellyfin channel
let channelId;
if (ItemType === "Episode") {
const episodeNotifyEnabled = process.env.JELLYFIN_NOTIFY_EPISODES === "true";
const episodeChannelId = process.env.JELLYFIN_EPISODE_CHANNEL_ID;
if (episodeNotifyEnabled && episodeChannelId) {
// Episode notifications enabled with specific channel - use it
channelId = episodeChannelId;
logger.debug(`Using episode-specific channel: ${channelId}`);
} else if (episodeNotifyEnabled && !episodeChannelId) {
// Episode notifications enabled but no specific channel - fallback to library or default
channelId = targetChannelId || process.env.JELLYFIN_CHANNEL_ID;
logger.debug(`Episode notifications enabled, using fallback channel: ${channelId}`);
} else if (!episodeNotifyEnabled) {
// Episode notifications disabled - skip
logger.info(`Episode notifications disabled. Skipping notification for: ${data.Name}`);
return;
}
} else if (ItemType === "Season") {
const seasonNotifyEnabled = process.env.JELLYFIN_NOTIFY_SEASONS === "true";
const seasonChannelId = process.env.JELLYFIN_SEASON_CHANNEL_ID;
if (seasonNotifyEnabled && seasonChannelId) {
// Season notifications enabled with specific channel - use it
channelId = seasonChannelId;
logger.debug(`Using season-specific channel: ${channelId}`);
} else if (seasonNotifyEnabled && !seasonChannelId) {
// Season notifications enabled but no specific channel - fallback to library or default
channelId = targetChannelId || process.env.JELLYFIN_CHANNEL_ID;
logger.debug(`Season notifications enabled, using fallback channel: ${channelId}`);
} else if (!seasonNotifyEnabled) {
// Season notifications disabled - skip
logger.info(`Season notifications disabled. Skipping notification for: ${data.Name}`);
return;
}
} else {
// For movies, series, etc. - use library channel or default
channelId = targetChannelId || process.env.JELLYFIN_CHANNEL_ID;
}
if (!channelId) {
logger.error(`❌ No Discord channel configured for ${ItemType} "${data.Name}" — set JELLYFIN_CHANNEL_ID or configure a library channel in the dashboard`);
return;
}
let channel;
try {
channel = await client.channels.fetch(channelId);
} catch (error) {
logger.error(`❌ Failed to fetch Discord channel ${channelId} for "${data.Name}" (${ItemType}): ${error.message}`);
throw new Error(`Discord channel ${channelId} not accessible`);
}
// Check if this is a batched episode notification and we have an existing message to edit
if (
ItemType === "Episode" &&
episodeCount > 1 &&
episodeDetails &&
SeriesId
) {
const existingMessage = episodeMessages.get(SeriesId);
if (existingMessage) {
try {
const channel = await client.channels.fetch(existingMessage.channelId);
const message = await channel.messages.fetch(existingMessage.messageId);
await message.edit({ embeds: [embed], components: [buttons] });
logger.info(
`Updated existing message for: ${embedTitle} (${episodeCount} episodes total)`
);
return; // Early return, don't send a new message
} catch (err) {
logger.warn(
`Failed to edit existing message for ${SeriesId}, sending new one:`,
err
);
// Continue to send new message
}
}
}
let sentMessage;
try {
const messageOptions = {
embeds: [embed],
};
if (buttons) {
messageOptions.components = [buttons];
}
sentMessage = await channel.send(messageOptions);
} catch (error) {
logger.error(`Failed to send Discord message:`, error);
throw new Error(`Failed to send Discord notification: ${error.message}`);
}
// Store message reference for future edits (batched episodes only)
if (
ItemType === "Episode" &&
episodeCount > 1 &&
episodeDetails &&
SeriesId
) {
episodeMessages.set(SeriesId, {
messageId: sentMessage.id,
channelId: channel.id,
});
// Clean up message reference after some time (prevent memory leaks)
setTimeout(() => {
episodeMessages.delete(SeriesId);
logger.debug(`Cleaned up message reference for SeriesId: ${SeriesId}`);
}, 6 * 60 * 60 * 1000); // 6 hours
}
logger.info(`${testPrefix}Sent notification for: ${embedTitle}`);
// Send DMs to users who requested this content
if (usersToNotify.length > 0) {
for (const userId of usersToNotify) {
try {
const user = await client.users.fetch(userId);
const dmEmbed = new EmbedBuilder()
.setAuthor({ name: "✅ Your request is now available!" })
.setTitle(embedTitle);
const dmJellyfinUrl = buildJellyfinUrl(
ServerUrl,
"web/index.html",
`!/details?id=${ItemId}&serverId=${ServerId}`
);
if (isValidUrl(dmJellyfinUrl)) {
dmEmbed.setURL(dmJellyfinUrl);
}
dmEmbed
.setColor(process.env.EMBED_COLOR_SUCCESS || "#a6e3a1")
.setDescription(
`${
Name || SeriesName || "Your requested content"
} is now available on Jellyfin!`
)
.addFields(
{ name: "Genre", value: genreList, inline: true },
{ name: "Runtime", value: runtime, inline: true },
{ name: "Rating", value: rating, inline: true }
);
if (backdropPath) {
const backdropUrl = `https://image.tmdb.org/t/p/w1280${backdropPath}`;
if (isValidUrl(backdropUrl)) {
dmEmbed.setImage(backdropUrl);
}
}
const dmButtons = isValidUrl(dmJellyfinUrl) ? new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel("▶ Watch Now!")
.setURL(dmJellyfinUrl)
) : null;
const messageOptions = { embeds: [dmEmbed] };
if (dmButtons) {
messageOptions.components = [dmButtons];
}
await user.send(messageOptions);
logger.info(`Sent DM notification to user ${userId} for ${embedTitle}`);
} catch (err) {
logger.error(
`Failed to send DM to user ${userId}:`,
err?.message || err
);
}
}
}
}
export { processAndSendNotification, libraryCache };
export async function handleJellyfinWebhook(req, res, client, pendingRequests, onPendingRequestsChanged) {
try {
const data = req.body;
if (!data || !data.ItemId) {
if (res) return res.status(400).send("No valid data");
return; // If no res object, just return
}
// Allow episodes and seasons with enhanced debouncing
// Get library ID - try multiple sources from webhook data
let libraryId = data.LibraryId || data.CollectionId || data.Library_Id;
// Check if this is a test notification
const isTestNotification = data.ItemId && (data.ItemId.startsWith("test-") || data.ItemId.startsWith("batch-"));
// If no library ID in webhook, use advanced detection (traverse parent chain)
// Skip library detection for test notifications
if (!libraryId && data.ItemId && !isTestNotification) {
try {
const apiKey = process.env.JELLYFIN_API_KEY;
const baseUrl = process.env.JELLYFIN_BASE_URL;
if (!apiKey || !baseUrl) {
logger.warn(
"Cannot detect library: JELLYFIN_API_KEY or JELLYFIN_BASE_URL not configured"
);
} else {
// Try to use cached libraries first (to avoid timeout issues at webhook time)
let libraries = libraryCache.get();
if (!libraries) {
// Cache is invalid, fetch fresh libraries
const { fetchLibraries } = await import(
"./api/jellyfin.js"
);
libraries = await fetchLibraries(apiKey, baseUrl);
}
const libraryMap = new Map();
for (const lib of libraries) {
// Map both CollectionId and ItemId to the library object
libraryMap.set(lib.CollectionId, lib);
if (lib.ItemId !== lib.CollectionId) {
libraryMap.set(lib.ItemId, lib);
}
}
// First try: Check if item's Path directly matches a library location
if (data.Path) {
const normalizedItemPath = data.Path.replace(/\\/g, "/").toLowerCase();
for (const lib of libraries) {
if (lib.Locations && lib.Locations.length > 0) {
for (const location of lib.Locations) {
const normalizedLocation = location.replace(/\\/g, "/").toLowerCase();
if (normalizedItemPath.startsWith(normalizedLocation)) {
// Verify type matches
const itemTypeLower = data.ItemType?.toLowerCase();
const libTypeLower = lib.CollectionType?.toLowerCase();
let typeMatch = true;
if (libTypeLower) {
// Only reject known cross-type mismatches; allow "mixed" and any
// unrecognised CollectionType (e.g. custom anime libraries) through.
if (itemTypeLower === "movie" && libTypeLower === "tvshows") typeMatch = false;
if ((itemTypeLower === "series" || itemTypeLower === "season" || itemTypeLower === "episode") && libTypeLower === "movies") typeMatch = false;
}
if (typeMatch) {
libraryId = lib.ItemId;
logger.debug(`✅ Library detected via Path matching: ${libraryId} (${lib.Name})`);
break;
}
}
}
}
if (libraryId) break;
}
}
// Second try: Use ancestor-based detection
if (!libraryId) {
const { findLibraryByAncestors } = await import("./api/jellyfin.js");
libraryId = await findLibraryByAncestors(
data.ItemId,
apiKey,
baseUrl,
libraryMap,
data.ItemType
);
if (libraryId) {
logger.debug(`✅ Library detected via Ancestors: ${libraryId}`);
}
}
}
} catch (err) {
if (!isTestNotification) {
logger.warn(`Advanced library detection failed:`, err?.message || err);
}
}
}
// Resolve CollectionId → ItemId if needed (Jellyfin webhook payload may send CollectionId
// while config stores VirtualFolder ItemId as the key)
if (libraryId && !isTestNotification) {
const cachedLibs = libraryCache.get();
if (cachedLibs) {
const match = cachedLibs.find((lib) => lib.CollectionId === libraryId);
if (match) {
logger.debug(`🔄 Resolved CollectionId ${libraryId} → ItemId ${match.ItemId}`);
libraryId = match.ItemId;
}
}
}
let libraryChannelId = null;
let isAnimeLibrary = false;
// Check if this is a test notification - if so, use default channel
if (isTestNotification) {
libraryChannelId = process.env.JELLYFIN_CHANNEL_ID;
logger.info(`🧪 Test notification detected. Using default channel: ${libraryChannelId}`);
} else {
const notificationLibraries = getLibraryChannels();
const libraryKeys = Object.keys(notificationLibraries);
logger.debug(`Configured libraries: ${JSON.stringify(notificationLibraries)}`);
if (libraryKeys.length > 0 && libraryId) {
libraryChannelId = resolveTargetChannel(libraryId, notificationLibraries);
if (libraryChannelId === null) {
// resolveTargetChannel already logged the skip
if (res) {
return res.status(200).send("OK: Notification skipped for disabled library.");
}
return;
}
isAnimeLibrary = getLibraryAnimeFlag(libraryId, notificationLibraries);
logger.info(
`✅ Using channel: ${libraryChannelId} for configured library: ${libraryId}${isAnimeLibrary ? " [anime]" : ""}`
);
} else if (libraryKeys.length > 0 && !libraryId) {
// Libraries are configured but we couldn't detect which library this item belongs to
libraryChannelId = process.env.JELLYFIN_CHANNEL_ID;
logger.warn(
`⚠️ Could not detect library for item "${data.Name}". Using default channel: ${libraryChannelId}`
);
} else {
// No library filtering configured - use default channel
libraryChannelId = process.env.JELLYFIN_CHANNEL_ID;
logger.debug(`No library filtering configured. Using default channel: ${libraryChannelId}`);
}
}
if (data.ItemType === "Movie") {
const { ItemId } = data;
const isTestMovie = ItemId && ItemId.startsWith("test-");
const movieKey = isTestMovie ? `test:${ItemId}` : (buildIdentityKey(data) || `id:${ItemId}`);
if (sentNotifications.has(movieKey)) {
logger.info(
`[DEDUP] Duplicate movie notification suppressed for "${data.Name}" (key: ${movieKey})`
);
if (res) {
return res
.status(200)
.send(`OK: Duplicate movie notification skipped for ${data.Name}.`);
}
return;
}
await processAndSendNotification(
data,
client,
pendingRequests,
libraryChannelId,
0,
null,
0,
null,
isTestMovie,
onPendingRequestsChanged,
isAnimeLibrary
);
sentNotifications.set(movieKey, { level: 0 });
if (res) return res.status(200).send("OK: Movie notification sent.");
return; // Exit early to prevent fallthrough to unknown item type handler
}
if (
data.ItemType === "Series" ||
data.ItemType === "Season" ||
data.ItemType === "Episode"
) {
// For Series type, SeriesId is undefined, so use ItemId instead