-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
990 lines (820 loc) · 31.5 KB
/
server.js
File metadata and controls
990 lines (820 loc) · 31.5 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
// Movie Night API Server - SQLite Only (no data.json)
// Auto-deployed via FluxCD + GitHub Actions
require('dotenv').config();
const express = require('express');
const fetch = require('node-fetch');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Data Repository - abstracts persistence layer
// To switch backends, edit repository/index.js
const repo = require('./repository');
app.use(express.json());
app.use(express.static('public'));
// Trakt routes (after middleware)
const traktAuth = require('./trakt/auth');
traktAuth.registerRoutes(app);
// CORS for Stremio
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// ─── Helper Functions ────────────────────────────────────────────────────────
// Get current week number (ISO 8601)
const getWeekNumber = (d = new Date()) => {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
const weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
return `${d.getUTCFullYear()}-W${String(weekNo).padStart(2, '0')}`;
};
// Determine current phase based on day/time
const getCurrentPhase = () => {
const now = new Date();
const day = now.getDay(); // 0 = Sunday, 1 = Monday, etc.
const hour = now.getHours();
// Monday (1) - Thursday (4): Nomination
if (day >= 1 && day <= 4) {
return 'nomination';
}
// Friday (5) before 18:00: Voting
if (day === 5 && hour < 18) {
return 'voting';
}
// Friday 18:00 onwards - Sunday: Results
return 'results';
};
// Get voting deadline (Friday 18:00)
const getVotingDeadline = () => {
const now = new Date();
const friday = new Date(now);
const daysUntilFriday = (5 - now.getDay() + 7) % 7;
if (daysUntilFriday === 0 && now.getDay() === 5 && now.getHours() >= 18) {
friday.setDate(now.getDate() + 7);
} else {
friday.setDate(now.getDate() + daysUntilFriday);
}
friday.setHours(18, 0, 0, 0);
return friday.toISOString();
};
// ─── MDBList Ratings (IMDb / Rotten Tomatoes / Metacritic) ──────────────────
const ratingsCache = new Map(); // key: tmdbId, value: { data, timestamp }
const RATINGS_CACHE_TTL = 30 * 60 * 1000; // 30 minutes
app.get('/api/ratings/:tmdbId', async (req, res) => {
const { tmdbId } = req.params;
if (!process.env.MDBLIST_API_KEY) {
return res.json({ imdb: null, rt: null, rtAudience: null, mc: null });
}
// Check cache
const cached = ratingsCache.get(tmdbId);
if (cached && Date.now() - cached.timestamp < RATINGS_CACHE_TTL) {
return res.json(cached.data);
}
try {
const response = await fetch(
`https://mdblist.com/api/?apikey=${process.env.MDBLIST_API_KEY}&tm=${tmdbId}`
);
if (!response.ok) {
const result = { imdb: null, rt: null, rtAudience: null, mc: null };
ratingsCache.set(tmdbId, { data: result, timestamp: Date.now() });
return res.json(result);
}
const data = await response.json();
const ratings = data.ratings || [];
const imdbRating = ratings.find(r => r.source === 'imdb');
const rtRating = ratings.find(r => r.source === 'tomatoes');
const rtAudienceRating = ratings.find(r => r.source === 'tomatoesaudience');
const mcRating = ratings.find(r => r.source === 'metacritic');
const result = {
imdb: imdbRating?.value ?? null,
rt: rtRating?.value ?? null,
rtAudience: rtAudienceRating?.value ?? null,
mc: mcRating?.value ?? null
};
ratingsCache.set(tmdbId, { data: result, timestamp: Date.now() });
res.json(result);
} catch (error) {
console.error('MDBList ratings error:', error.message);
res.json({ imdb: null, rt: null, rtAudience: null, mc: null });
}
});
// ─── MDBList Integration ─────────────────────────────────────────────────────
const addToMDBList = async (tmdbId, imdbId, title) => {
if (!process.env.MDBLIST_API_KEY || !process.env.MDBLIST_LIST_ID) {
console.log('MDBList not configured - skipping');
return false;
}
try {
const movieId = imdbId || `tmdb:${tmdbId}`;
const url = `https://api.mdblist.com/lists/${process.env.MDBLIST_LIST_ID}/items`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': process.env.MDBLIST_API_KEY
},
body: JSON.stringify({ items: [movieId] })
});
if (response.ok) {
console.log(`✅ Added to MDBList: ${title} (${movieId})`);
return true;
} else {
const error = await response.text();
console.error(`❌ MDBList error for ${title}:`, error);
return false;
}
} catch (error) {
console.error('MDBList API error:', error);
return false;
}
};
// ─── Week Transition Logic ───────────────────────────────────────────────────
// Check if we need to archive the previous week's results
const checkWeekTransition = () => {
const currentWeek = getWeekNumber();
// Get previous week
const d = new Date();
d.setDate(d.getDate() - 7);
const lastWeek = getWeekNumber(d);
// Check if last week needs archiving
const lastWeekResult = repo.getWeekResults(lastWeek);
if (lastWeekResult) return; // Already archived
const lastWeekNominations = repo.getNominations(lastWeek);
if (lastWeekNominations.length === 0) return; // Nothing to archive
// Sort by vote count and archive
const sorted = lastWeekNominations.sort((a, b) => (b.vote_count || 0) - (a.vote_count || 0));
const first = sorted[0];
const second = sorted[1];
// Save results
repo.saveWeekResults(
lastWeek,
first?.tmdb_id, first?.title,
second?.tmdb_id, second?.title
);
// Add winners to MDBList
if (first) addToMDBList(first.tmdb_id, first.imdb_id, first.title);
if (second) addToMDBList(second.tmdb_id, second.imdb_id, second.title);
console.log(`📦 Archived week ${lastWeek}: ${first?.title} (1st), ${second?.title} (2nd)`);
};
// Format nomination for API response
const formatNomination = (n) => ({
id: n.id,
tmdbId: n.tmdb_id,
title: n.title,
year: n.year,
posterPath: n.poster_path,
backdropPath: n.backdrop_path,
overview: n.overview,
rating: n.rating,
imdbId: n.imdb_id,
proposedBy: n.proposed_by_name,
proposedAt: n.proposed_at
});
// ─── API Endpoints ───────────────────────────────────────────────────────────
// Get current state
app.get('/api/state', (req, res) => {
checkWeekTransition();
const week = getWeekNumber();
const nominations = repo.getNominations(week);
let phase = getCurrentPhase();
// Auto-advance to voting if all 4 nominated
if (phase === 'nomination' && nominations.length === 4) {
phase = 'voting';
}
res.json({
week,
phase,
votingDeadline: getVotingDeadline(),
nominations: nominations.map(formatNomination),
votes: repo.getVotesAsObject(week),
users: repo.getUsersAsObject()
});
});
// Get history
app.get('/api/history', (req, res) => {
const results = repo.getAllWeekResults();
// Convert to legacy format for compatibility
const history = results.map(r => ({
weekNumber: r.week,
firstPlace: r.first_place_tmdb ? { tmdbId: r.first_place_tmdb, title: r.first_place_title } : null,
secondPlace: r.second_place_tmdb ? { tmdbId: r.second_place_tmdb, title: r.second_place_title } : null
}));
res.json(history);
});
// TMDb browse endpoints
app.get('/api/browse/:category', async (req, res) => {
const { category } = req.params;
if (!process.env.TMDB_API_KEY) {
return res.status(500).json({ error: 'TMDb API key not configured' });
}
const genreIds = {
action: 28, comedy: 35, crime: 80, drama: 18, thriller: 53,
horror: 27, romance: 10749, scifi: 878, fantasy: 14,
animation: 16, family: 10751, mystery: 9648
};
const today = new Date().toISOString().split('T')[0];
const baseDiscover = `https://api.themoviedb.org/3/discover/movie?api_key=${process.env.TMDB_API_KEY}&with_release_type=4|5|6&release_date.lte=${today}®ion=DE`;
const categoryParams = {
trending: `&sort_by=popularity.desc&vote_count.gte=50`,
popular: `&sort_by=popularity.desc&vote_count.gte=20`,
topRated: `&sort_by=vote_average.desc&vote_count.gte=100`,
nowPlaying: `&sort_by=release_date.desc&vote_count.gte=10`,
action: `&with_genres=${genreIds.action}&sort_by=popularity.desc`,
comedy: `&with_genres=${genreIds.comedy}&sort_by=popularity.desc`,
drama: `&with_genres=${genreIds.drama}&sort_by=popularity.desc`,
horror: `&with_genres=${genreIds.horror}&sort_by=popularity.desc`,
scifi: `&with_genres=${genreIds.scifi}&sort_by=popularity.desc`,
thriller: `&with_genres=${genreIds.thriller}&sort_by=popularity.desc`,
romance: `&with_genres=${genreIds.romance}&sort_by=popularity.desc`,
animation: `&with_genres=${genreIds.animation}&sort_by=popularity.desc`,
family: `&with_genres=${genreIds.family}&sort_by=popularity.desc`
};
const params = categoryParams[category];
if (!params) {
return res.status(400).json({ error: 'Invalid category' });
}
try {
const response = await fetch(`${baseDiscover}${params}`);
const data = await response.json();
res.json(data.results || []);
} catch (error) {
console.error('TMDb browse error:', error);
res.status(500).json({ error: 'Failed to fetch movies' });
}
});
// Search movies
app.get('/api/search', async (req, res) => {
const { q } = req.query;
if (!q) {
return res.status(400).json({ error: 'Search query required' });
}
if (!process.env.TMDB_API_KEY) {
return res.status(500).json({ error: 'TMDb API key not configured' });
}
try {
const response = await fetch(
`https://api.themoviedb.org/3/search/movie?api_key=${process.env.TMDB_API_KEY}&query=${encodeURIComponent(q)}&include_adult=false`
);
const data = await response.json();
res.json(data.results || []);
} catch (error) {
console.error('TMDb search error:', error);
res.status(500).json({ error: 'Search failed' });
}
});
// Get movie details
app.get('/api/movie/:tmdbId', async (req, res) => {
const { tmdbId } = req.params;
if (!process.env.TMDB_API_KEY) {
return res.status(500).json({ error: 'TMDb API key not configured' });
}
try {
const response = await fetch(
`https://api.themoviedb.org/3/movie/${tmdbId}?api_key=${process.env.TMDB_API_KEY}&append_to_response=external_ids,videos`
);
const data = await response.json();
res.json(data);
} catch (error) {
console.error('TMDb movie details error:', error);
res.status(500).json({ error: 'Failed to fetch movie details' });
}
});
// Nominate a movie
app.post('/api/nominate', async (req, res) => {
const { tmdbId, user } = req.body;
if (!tmdbId || !user) {
return res.status(400).json({ error: 'Missing tmdbId or user' });
}
const week = getWeekNumber();
const nominations = repo.getNominations(week);
// Check if already nominated
const existing = repo.getNominationByUser(week, user);
if (existing) {
return res.status(400).json({ error: 'You already nominated a movie this week' });
}
// Check if 4 nominations reached
if (nominations.length >= 4) {
return res.status(400).json({ error: 'Maximum nominations reached' });
}
// Check if movie already nominated
if (nominations.some(n => n.tmdb_id === tmdbId)) {
return res.status(400).json({ error: 'Movie already nominated this week' });
}
try {
// Fetch movie details from TMDb
const response = await fetch(
`https://api.themoviedb.org/3/movie/${tmdbId}?api_key=${process.env.TMDB_API_KEY}&append_to_response=external_ids`
);
const movie = await response.json();
repo.addNomination(
week,
tmdbId,
movie.title,
movie.release_date?.split('-')[0],
movie.poster_path,
movie.backdrop_path,
movie.overview,
movie.vote_average,
movie.external_ids?.imdb_id,
user
);
res.json({ success: true, message: `${movie.title} nominated!` });
} catch (error) {
console.error('Nomination error:', error);
res.status(500).json({ error: 'Failed to nominate movie' });
}
});
// Withdraw nomination
app.post('/api/withdraw-nomination', (req, res) => {
const { user } = req.body;
if (!user) {
return res.status(400).json({ error: 'Missing user' });
}
const week = getWeekNumber();
try {
repo.removeNomination(week, user);
res.json({ success: true });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Vote for a movie
app.post('/api/vote', (req, res) => {
const { nominationId, user, vote } = req.body;
if (!nominationId || !user) {
return res.status(400).json({ error: 'Missing nominationId or user' });
}
const week = getWeekNumber();
// Check nomination exists
const nomination = repo.getNominationById(nominationId);
if (!nomination) {
return res.status(400).json({ error: 'Nomination not found' });
}
// Can't vote for own nomination
if (nomination.proposed_by_name === user) {
return res.status(400).json({ error: "Can't vote for your own nomination" });
}
try {
if (vote) {
repo.addVote(week, nominationId, user);
} else {
repo.removeVote(week, nominationId, user);
}
res.json({ success: true });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Get user votes
app.get('/api/votes/:user', (req, res) => {
const { user } = req.params;
const week = getWeekNumber();
const votes = repo.getUserVotes(week, user);
const votedIds = votes.map(v => v.nomination_id);
res.json(votedIds);
});
// Rate a watched movie
app.post('/api/rate', (req, res) => {
const { tmdbId, user, rating } = req.body;
if (!tmdbId || !user || rating === undefined) {
return res.status(400).json({ error: 'Missing tmdbId, user, or rating' });
}
try {
repo.updateWatchRating(user, tmdbId, rating);
res.json({ success: true });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Get user ratings
app.get('/api/user/:user/ratings', (req, res) => {
const { user } = req.params;
const history = repo.getWatchHistory(user);
const ratings = {};
history.forEach(h => {
if (h.rating) {
ratings[h.tmdb_id] = h.rating;
}
});
res.json(ratings);
});
// Update user icon
app.post('/api/user/icon', (req, res) => {
const { user, icon } = req.body;
if (!user || !icon) {
return res.status(400).json({ error: 'Missing user or icon' });
}
try {
repo.updateUserIcon(user, icon);
res.json({ success: true });
} catch (error) {
res.status(400).json({ error: 'User not found' });
}
});
// Set user PIN
app.post('/api/user/pin', (req, res) => {
const { user, pin } = req.body;
if (!user) {
return res.status(400).json({ error: 'Missing user' });
}
try {
repo.updateUserPin(user, pin || null);
res.json({ success: true });
} catch (error) {
res.status(400).json({ error: 'User not found' });
}
});
// Login (verify PIN)
app.post('/api/login', (req, res) => {
const { user, pin } = req.body;
if (!user) {
return res.status(400).json({ error: 'Missing user' });
}
const dbUser = repo.getUserByName(user);
if (!dbUser) {
return res.status(400).json({ error: 'User not found' });
}
// No PIN set - allow login
if (!dbUser.pin) {
return res.json({ success: true });
}
// Verify PIN
if (dbUser.pin === pin) {
return res.json({ success: true });
}
res.status(401).json({ error: 'Invalid PIN' });
});
// MDBList add
app.post('/api/mdblist/add', async (req, res) => {
const { tmdbId, imdbId, title } = req.body;
if (!tmdbId) {
return res.status(400).json({ error: 'Missing tmdbId' });
}
const success = await addToMDBList(tmdbId, imdbId, title);
res.json({ success });
});
// MDBList status
app.get('/api/mdblist/status', (req, res) => {
res.json({
configured: !!(process.env.MDBLIST_API_KEY && process.env.MDBLIST_LIST_ID),
listId: process.env.MDBLIST_LIST_ID || null
});
});
// ─── AI Picks ─────────────────────────────────────────────────────────────────
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
async function generateAiPicks(user) {
const traktApi = require('./trakt/api');
const db = require('./db/database');
let watchedMovies = [];
let watchedShows = [];
// Try Trakt for richer history
const traktAuth = db.getTraktAuth(user);
if (traktAuth) {
try {
const traktMovies = await traktApi.getWatchedMovies(user);
watchedMovies = (traktMovies || []).map(e => ({ title: e.movie.title, year: e.movie.year }));
const traktShows = await traktApi.getWatchedShows(user);
watchedShows = (traktShows || []).map(e => ({ title: e.show.title, year: e.show.year }));
} catch (e) {
console.error('Trakt fetch error for AI picks:', e.message);
}
}
// Fall back to local DB watch history
if (watchedMovies.length === 0) {
const localHistory = repo.getWatchHistory(user);
watchedMovies = localHistory.map(h => ({ title: h.title, year: null }));
}
if (watchedMovies.length === 0) {
return { categories: [], message: 'No watch history found. Watch some movies first!' };
}
const moviesList = watchedMovies.slice(0, 100).map(m => `${m.title}${m.year ? ` (${m.year})` : ''}`).join('\n');
const userPrompt = `Here is a user's movie watch history:
Movies watched:
${moviesList}
Based on this watch history, recommend movies the user would enjoy but has NOT already watched.
Return exactly 12 categories, each with exactly 15 movies. Do not return fewer than 15 movies per category.
Return ONLY valid JSON in this exact format:
{
"categories": [
{
"id": "picked_for_you",
"name": "Picked For You",
"emoji": "🎯",
"movies": [
{
"title": "Movie Title",
"year": 2022,
"reason": "Brief reason why they'd like it based on their history",
"tmdb_query": "exact title to search on TMDb"
}
]
}
]
}
The 12 categories must be exactly:
1. id: "picked_for_you", name: "Picked For You", emoji: "🎯" — personalized core recommendations based on their taste
2. id: "comfort_zone", name: "Your Comfort Zone", emoji: "🛋️" — safe bets very similar to films they already love
3. id: "expand_horizons", name: "Expand Your Horizons", emoji: "🌍" — films outside their usual genres they might enjoy
4. id: "hidden_gems", name: "Hidden Gems", emoji: "💎" — underrated or lesser-known films matching their taste
5. id: "critically_acclaimed", name: "Critically Acclaimed", emoji: "🏆" — highly rated, award-nominated films they have not seen
6. id: "guilty_pleasures", name: "Guilty Pleasures", emoji: "🍿" — fun, popcorn, crowd-pleasing films
7. id: "modern_classics", name: "Modern Classics", emoji: "🎬" — must-see films from the last 10-15 years they missed
8. id: "world_cinema", name: "World Cinema", emoji: "🌏" — international/foreign language films matching their taste
9. id: "you_missed_these", name: "You Missed These", emoji: "⏰" — older films (pre-2010) that are considered essential viewing matching their taste
10. id: "visually_stunning", name: "Visually Stunning", emoji: "🎨" — films known for exceptional cinematography, visuals, or art direction matching their taste
11. id: "starring_your_favorites", name: "Starring Your Favorites", emoji: "🎭" — films starring actors who appear frequently in the user's watch history
12. id: "documentaries", name: "Documentaries You'll Like", emoji: "📽️" — documentaries matching the user's interests based on their watch history`;
const aiResponse = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`,
'HTTP-Referer': 'https://movies.erix-homelab.site',
'X-Title': 'Movie Night AI Picks'
},
body: JSON.stringify({
model: 'google/gemini-2.5-flash',
messages: [
{
role: 'system',
content: 'You are a movie recommendation engine. Based on the user\'s watch history, recommend movies they would enjoy but have NOT already watched, organized into 12 specific categories. Return exactly 15 movies per category. Do not return fewer. Return ONLY valid JSON.'
},
{ role: 'user', content: userPrompt }
],
response_format: { type: 'json_object' }
})
});
if (!aiResponse.ok) {
const errText = await aiResponse.text();
console.error('OpenRouter error:', errText);
throw new Error('AI service error');
}
const aiData = await aiResponse.json();
const content = aiData.choices?.[0]?.message?.content;
if (!content) throw new Error('No response from AI');
let parsed;
try {
parsed = JSON.parse(content);
} catch (e) {
const match = content.match(/\{[\s\S]*\}/);
if (match) parsed = JSON.parse(match[0]);
else throw new Error('Failed to parse AI response');
}
const categories = parsed.categories || [];
// Enrich each movie in each category with TMDb data
const enrichedCategories = await Promise.all(categories.map(async (cat) => {
const movies = await Promise.all((cat.movies || []).map(async (rec) => {
try {
const query = rec.tmdb_query || rec.title;
const yearParam = rec.year ? `&year=${rec.year}` : '';
const tmdbRes = await fetch(
`https://api.themoviedb.org/3/search/movie?api_key=${process.env.TMDB_API_KEY}&query=${encodeURIComponent(query)}${yearParam}&include_adult=false`
);
const tmdbData = await tmdbRes.json();
const result = tmdbData.results?.[0];
if (!result) return null;
return {
...rec,
tmdb: {
id: result.id,
title: result.title,
poster_path: result.poster_path,
overview: result.overview,
vote_average: result.vote_average,
release_date: result.release_date
}
};
} catch (e) {
return null;
}
}));
return {
id: cat.id,
name: cat.name,
emoji: cat.emoji,
movies: movies.filter(Boolean)
};
}));
return { categories: enrichedCategories };
}
app.get('/api/ai-picks/:user', async (req, res) => {
const { user } = req.params;
const forceRefresh = req.query.refresh === '1';
if (!process.env.OPENROUTER_API_KEY) {
return res.status(500).json({ error: 'OpenRouter API key not configured' });
}
if (!process.env.TMDB_API_KEY) {
return res.status(500).json({ error: 'TMDb API key not configured' });
}
const cached = repo.getAiPicksCache(user);
const cacheAge = cached ? Date.now() - new Date(cached.generated_at).getTime() : Infinity;
const cacheValid = cached && cacheAge < CACHE_TTL_MS;
if (!forceRefresh && cacheValid) {
// Fresh cache: return immediately
return res.json({ ...JSON.parse(cached.data), generatedAt: cached.generated_at });
}
if (!forceRefresh && cached && cacheAge >= CACHE_TTL_MS) {
// Stale cache: return old data immediately, regenerate in background
res.json({ ...JSON.parse(cached.data), generatedAt: cached.generated_at });
generateAiPicks(user).then(result => {
repo.setAiPicksCache(user, JSON.stringify(result));
}).catch(err => console.error('Background AI picks refresh failed:', err));
return;
}
// No cache at all (first time): generate and wait
try {
const result = await generateAiPicks(user);
repo.setAiPicksCache(user, JSON.stringify(result));
res.json({ ...result, generatedAt: new Date().toISOString() });
} catch (error) {
console.error('AI picks error:', error);
res.status(500).json({ error: error.message || 'Failed to get AI picks' });
}
});
// ─── Stremio Addon Endpoints ─────────────────────────────────────────────────
const formatMetaPreview = (movie, metadata = {}) => ({
id: `tmdb:${movie.tmdb_id || movie.tmdbId}`,
type: 'movie',
name: movie.title,
poster: movie.poster_path ? `https://image.tmdb.org/t/p/w500${movie.poster_path}` : undefined,
description: movie.overview,
...metadata
});
// Stremio manifest
app.get('/manifest.json', (req, res) => {
res.json({
id: 'family.movie.night',
version: '1.0.0',
name: 'Family Movie Night',
description: 'Family voting history and watch tracking',
resources: ['catalog', 'meta'],
types: ['movie'],
catalogs: [
{ type: 'movie', id: 'nominations', name: "This Week's Nominations" },
{ type: 'movie', id: 'winners', name: 'Movie Night Winners' },
{ type: 'movie', id: 'watched', name: 'Watched Together' }
]
});
});
// Stremio catalog
app.get('/catalog/:type/:id.json', (req, res) => {
const { type, id } = req.params;
if (type !== 'movie') {
return res.status(400).json({ error: 'Only movie type supported' });
}
const week = getWeekNumber();
const metas = [];
try {
if (id === 'nominations') {
const nominations = repo.getNominations(week);
nominations.forEach(n => {
metas.push(formatMetaPreview(n, {
description: `${n.overview}\n\nNominated by: ${n.proposed_by_name}`
}));
});
} else if (id === 'winners') {
const results = repo.getAllWeekResults();
results.forEach(r => {
if (r.first_place_tmdb) {
metas.push({
id: `tmdb:${r.first_place_tmdb}`,
type: 'movie',
name: r.first_place_title,
description: `🏆 First Place - Week ${r.week}`
});
}
if (r.second_place_tmdb) {
metas.push({
id: `tmdb:${r.second_place_tmdb}`,
type: 'movie',
name: r.second_place_title,
description: `🥈 Second Place - Week ${r.week}`
});
}
});
} else if (id === 'watched') {
// Get all users' watch history
const users = repo.getUsers();
const watchedMap = {};
users.forEach(u => {
const history = repo.getWatchHistory(u.name);
history.forEach(h => {
if (!watchedMap[h.tmdb_id]) {
watchedMap[h.tmdb_id] = { ...h, watchers: [] };
}
watchedMap[h.tmdb_id].watchers.push(u.name);
});
});
Object.values(watchedMap).forEach(w => {
metas.push({
id: `tmdb:${w.tmdb_id}`,
type: 'movie',
name: w.title,
description: `Watched by: ${w.watchers.join(', ')}`
});
});
} else {
return res.status(404).json({ error: 'Catalog not found' });
}
res.json({ metas });
} catch (error) {
console.error('Catalog error:', error);
res.status(500).json({ error: 'Failed to fetch catalog' });
}
});
// Stremio meta
app.get('/meta/:type/:id.json', async (req, res) => {
const { type, id } = req.params;
if (type !== 'movie') {
return res.status(400).json({ error: 'Only movie type supported' });
}
const tmdbId = id.startsWith('tmdb:') ? id.substring(5) : id;
if (!process.env.TMDB_API_KEY) {
return res.status(500).json({ error: 'TMDB API key not configured' });
}
try {
const response = await fetch(
`https://api.themoviedb.org/3/movie/${tmdbId}?api_key=${process.env.TMDB_API_KEY}&append_to_response=external_ids,credits`
);
if (!response.ok) {
return res.status(404).json({ error: 'Movie not found' });
}
const movie = await response.json();
const week = getWeekNumber();
// Get custom metadata
const nominations = repo.getNominations(week);
const nomination = nominations.find(n => n.tmdb_id.toString() === tmdbId);
let customDescription = movie.overview;
if (nomination) {
customDescription += `\n\n📋 Nominated by: ${nomination.proposed_by_name}`;
customDescription += `\n🗳️ Votes: ${nomination.vote_count || 0}`;
}
res.json({
meta: {
id: `tmdb:${tmdbId}`,
type: 'movie',
name: movie.title,
poster: movie.poster_path ? `https://image.tmdb.org/t/p/w500${movie.poster_path}` : undefined,
background: movie.backdrop_path ? `https://image.tmdb.org/t/p/original${movie.backdrop_path}` : undefined,
description: customDescription,
releaseInfo: movie.release_date?.split('-')[0],
imdbRating: movie.vote_average?.toFixed(1),
runtime: movie.runtime ? `${movie.runtime} min` : undefined,
genres: movie.genres?.map(g => g.name)
}
});
} catch (error) {
console.error('Meta error:', error);
res.status(500).json({ error: 'Failed to fetch meta' });
}
});
// ─── Watch History Endpoints ─────────────────────────────────────────────────
app.post('/api/watched', async (req, res) => {
const { tmdbId, user, title } = req.body;
if (!tmdbId || !user) {
return res.status(400).json({ error: 'Missing tmdbId or user' });
}
const week = getWeekNumber();
try {
repo.markWatched(user, tmdbId, title, week);
res.json({ success: true });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
app.get('/api/watched/:user/:tmdbId', (req, res) => {
const { user, tmdbId } = req.params;
const watched = repo.hasWatched(user, parseInt(tmdbId));
res.json({ watched });
});
app.get('/api/watched/:user', (req, res) => {
const { user } = req.params;
const history = repo.getWatchHistory(user);
res.json(history.map(h => h.tmdb_id));
});
// ─── Export for external modules ─────────────────────────────────────────────
module.exports = {
getWeekNumber,
getCurrentPhase,
getVotingDeadline,
addToMDBList
};
// ─── Telegram Bot ────────────────────────────────────────────────────────────
if (process.env.TELEGRAM_BOT_TOKEN && process.env.TELEGRAM_GROUP_ID) {
console.log('🤖 Telegram bot enabled');
const telegramBot = require('./telegram/bot');
telegramBot.initBot();
telegramBot.startBot().then(() => {
console.log('🤖 Telegram bot started');
}).catch(err => {
console.error('Failed to start Telegram bot:', err);
});
}
// ─── Start Server ────────────────────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`Movie Night app running on http://localhost:${PORT}`);
if (process.env.MDBLIST_API_KEY && process.env.MDBLIST_LIST_ID) {
console.log(`✅ MDBList integration enabled (List: ${process.env.MDBLIST_LIST_ID})`);
}
});