-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathjellyfinPoller.js
More file actions
229 lines (193 loc) · 7.38 KB
/
jellyfinPoller.js
File metadata and controls
229 lines (193 loc) · 7.38 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
import * as jellyfinApi from "./api/jellyfin.js";
import { processAndSendNotification } from "./jellyfinWebhook.js";
import logger from "./utils/logger.js";
import {
fetchLibraryMap,
resolveConfigLibraryId,
getLibraryChannels,
resolveTargetChannel,
getLibraryAnimeFlag,
deduplicator,
} from "./jellyfin/libraryResolver.js";
class JellyfinPoller {
constructor() {
this.intervalId = null;
this.isRunning = false;
this.client = null;
this.pendingRequests = null;
}
/**
* Start the polling service
* @param {Object} discordClient - Discord.js client instance
* @param {Map} pendingRequests - Map of pending user requests
*/
start(discordClient, pendingRequests) {
if (this.isRunning) {
logger.warn("Jellyfin polling service is already running");
return;
}
const enabled = process.env.JELLYFIN_POLLING_ENABLED === "true";
if (!enabled) {
logger.info("Jellyfin polling is disabled in configuration");
return;
}
const apiKey = process.env.JELLYFIN_API_KEY;
const baseUrl = process.env.JELLYFIN_BASE_URL;
const serverId = process.env.JELLYFIN_SERVER_ID;
if (!apiKey || !baseUrl || !serverId) {
logger.error(
"Jellyfin polling requires JELLYFIN_API_KEY, JELLYFIN_BASE_URL, and JELLYFIN_SERVER_ID"
);
return;
}
this.client = discordClient;
this.pendingRequests = pendingRequests;
this.isRunning = true;
const interval = parseInt(
process.env.JELLYFIN_POLLING_INTERVAL || "300000",
10
);
logger.info(
`🔄 Jellyfin polling service started (interval: ${interval / 1000}s)`
);
// Run immediately on start
this.poll();
// Then run at intervals
this.intervalId = setInterval(() => this.poll(), interval);
}
/**
* Stop the polling service
*/
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
this.isRunning = false;
this.client = null;
this.pendingRequests = null;
logger.info("⏹️ Jellyfin polling service stopped");
}
/**
* Perform a single poll operation
*/
async poll() {
try {
const apiKey = process.env.JELLYFIN_API_KEY;
const baseUrl = process.env.JELLYFIN_BASE_URL;
const serverId = process.env.JELLYFIN_SERVER_ID;
logger.info("🔍 Polling Jellyfin for recently added items...");
const { libraries, libraryIds, libraryIdMap } = await fetchLibraryMap();
// Build a full libraryMap (id → object) for findLibraryId fallback
const libraryObjectMap = new Map();
for (const lib of libraries) {
libraryObjectMap.set(lib.CollectionId, lib);
if (lib.ItemId !== lib.CollectionId) libraryObjectMap.set(lib.ItemId, lib);
}
logger.info(
`📚 Found ${libraries.length} libraries: ${libraries.map((l) => l.Name).join(", ")}`
);
logger.info(
`📚 Virtual Folder IDs: ${libraries.map((l) => `${l.Name}=${l.ItemId}`).join(", ")}`
);
logger.info(
`📚 Collection IDs: ${libraries.map((l) => `${l.Name}=${l.CollectionId || l.ItemId}`).join(", ")}`
);
const items = await jellyfinApi.fetchRecentlyAdded(apiKey, baseUrl, 50);
if (items.length === 0) {
logger.info("No recently added items found");
return;
}
logger.info(`📦 Found ${items.length} recently added items`);
// Log first few items for debugging
items.slice(0, 3).forEach((item) => {
logger.info(
` - ${item.Type}: ${item.Name} (ID: ${item.Id}, ParentId: ${item.ParentId})`
);
});
// Debug: Log full first item to see what fields we have
if (items.length > 0) {
logger.info(
`🔍 DEBUG - First item full data: ${JSON.stringify(items[0], null, 2)}`
);
}
// Get notification type filters
const notifyMovies = process.env.JELLYFIN_NOTIFY_MOVIES !== "false";
const notifySeries = process.env.JELLYFIN_NOTIFY_SERIES !== "false";
const notifySeasons = process.env.JELLYFIN_NOTIFY_SEASONS !== "false";
const notifyEpisodes = process.env.JELLYFIN_NOTIFY_EPISODES !== "false";
const libraryChannels = getLibraryChannels();
const defaultChannelId = process.env.JELLYFIN_CHANNEL_ID;
logger.info(`📚 Library channels configured: ${JSON.stringify(libraryChannels)}`);
logger.info(`📢 Default channel: ${defaultChannelId}`);
for (const item of items) {
const itemId = item.Id;
const itemType = item.Type;
// Check if we should notify for this type
if (
(itemType === "Movie" && !notifyMovies) ||
(itemType === "Series" && !notifySeries) ||
(itemType === "Season" && !notifySeasons) ||
(itemType === "Episode" && !notifyEpisodes)
) {
logger.debug(`Skipping ${itemType} notification (disabled in config)`);
continue;
}
// Deduplication
if (deduplicator.checkAndRecord(itemId)) {
logger.info(`⏭️ Skipping ${itemType} "${item.Name}" - already notified recently`);
continue;
}
// Resolve library ID
let libraryId = null;
logger.info(
`🔎 Item "${item.Name}" (${itemType}) - ParentId from /Items/Latest: ${item.ParentId}`
);
if (item.ParentId && libraryIds.has(item.ParentId)) {
libraryId = item.ParentId;
logger.info(`✅ ParentId matched a known library: ${libraryId}`);
} else if (item.ParentId) {
logger.info(`⚠️ ParentId ${item.ParentId} not in library set, traversing up...`);
libraryId = await jellyfinApi.findLibraryId(itemId, apiKey, baseUrl, libraryObjectMap);
} else {
logger.info(`⚠️ No ParentId provided, traversing up from item ${itemId}...`);
libraryId = await jellyfinApi.findLibraryId(itemId, apiKey, baseUrl, libraryObjectMap);
}
logger.info(`🔍 Processing ${itemType} "${item.Name}" - Detected LibraryId: ${libraryId}`);
const configLibraryId = resolveConfigLibraryId(libraryId, libraryIdMap);
const targetChannelId = resolveTargetChannel(configLibraryId, libraryChannels);
if (!targetChannelId) {
logger.error(`No channel resolved for "${item.Name}" (libraryId: ${configLibraryId}) — set JELLYFIN_CHANNEL_ID or configure library channels`);
continue;
}
const isAnimeLibrary = getLibraryAnimeFlag(configLibraryId, libraryChannels);
logger.info(`✅ Will send to channel: ${targetChannelId}${isAnimeLibrary ? " [anime]" : ""}`);
const webhookData = jellyfinApi.transformToWebhookFormat(item, baseUrl, serverId);
try {
await processAndSendNotification(
webhookData,
this.client,
this.pendingRequests,
targetChannelId,
0,
null,
0,
null,
false,
null,
isAnimeLibrary
);
logger.info(`✅ Sent notification for ${itemType}: ${item.Name}`);
} catch (err) {
logger.error(`Failed to send notification for ${itemId}:`, err);
}
}
// Cleanup old deduplicator entries
deduplicator.cleanup();
} catch (err) {
logger.error("Error during Jellyfin polling:", err);
}
}
}
// Export singleton instance
export const jellyfinPoller = new JellyfinPoller();