mikmc commited on
Commit
b5b8d8d
·
verified ·
1 Parent(s): 9d4aaef

Upload 5 files

Browse files
cache/catalog_cache.json ADDED
The diff for this file is too large to render. See raw diff
 
cache/meta_cache.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
index.js ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { addonBuilder, serveHTTP } = require('stremio-addon-sdk');
2
+ const axios = require('axios');
3
+ const fs = require('fs').promises;
4
+ const path = require('path');
5
+ const winston = require('winston');
6
+ const schedule = require('node-schedule');
7
+
8
+ // Logger configuration
9
+ const logger = winston.createLogger({
10
+ level: 'debug',
11
+ format: winston.format.combine(
12
+ winston.format.timestamp(),
13
+ winston.format.printf(({ level, message, timestamp }) => `${timestamp} ${level}: ${message}`)
14
+ ),
15
+ transports: [
16
+ new winston.transports.Console(),
17
+ new winston.transports.File({ filename: 'addon.log' })
18
+ ]
19
+ });
20
+
21
+ const TMDB_API_KEY = 'f051e7366c6105ad4f9aafe4733d9dae';
22
+ const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
23
+ const CACHE_DIR = path.join(__dirname, 'cache');
24
+ const CATALOG_CACHE_FILE = path.join(CACHE_DIR, 'catalog_cache.json');
25
+ const META_CACHE_FILE = path.join(CACHE_DIR, 'meta_cache.json');
26
+
27
+ let catalogCache = {};
28
+ let metaCache = {};
29
+
30
+ // Manifest with separate catalogs for movies and TV shows
31
+ const manifest = {
32
+ id: 'org.stremio.billy-connolly-catalog',
33
+ version: '1.0.0',
34
+ name: 'The Big Yin',
35
+ description: 'Stremio Add-on catalog showcasing movies and shows featuring Billy Connolly',
36
+ catalogs: [
37
+ {
38
+ type: 'Easynews',
39
+ id: 'billy-connolly-movies',
40
+ name: 'Billy Connolly Movies',
41
+ extra: [{ name: 'genre', isRequired: false }, { name: 'search', isRequired: false }]
42
+ },
43
+ {
44
+ type: 'Easynews',
45
+ id: 'billy-connolly-tv',
46
+ name: 'Billy Connolly TV Shows',
47
+ extra: [{ name: 'genre', isRequired: false }, { name: 'search', isRequired: false }]
48
+ }
49
+ ],
50
+ resources: ['catalog', 'meta'],
51
+ types: ['movie', 'series'],
52
+ idPrefixes: ['tmdb']
53
+ };
54
+
55
+ const builder = new addonBuilder(manifest);
56
+
57
+ async function ensureCacheDirectory() {
58
+ try {
59
+ await fs.mkdir(CACHE_DIR, { recursive: true });
60
+ logger.debug('Cache directory ensured');
61
+ } catch (error) {
62
+ logger.error('Error creating cache directory:', error);
63
+ }
64
+ }
65
+
66
+ async function loadCache() {
67
+ try {
68
+ const catalogData = await fs.readFile(CATALOG_CACHE_FILE, 'utf8');
69
+ catalogCache = JSON.parse(catalogData);
70
+ logger.debug(`Catalog cache loaded. Items: ${catalogCache.data ? catalogCache.data.length : 0}`);
71
+ } catch (error) {
72
+ logger.info('No existing catalog cache found. Will create a new one.');
73
+ }
74
+
75
+ try {
76
+ const metaData = await fs.readFile(META_CACHE_FILE, 'utf8');
77
+ metaCache = JSON.parse(metaData);
78
+ logger.debug(`Meta cache loaded. Items: ${Object.keys(metaCache).length}`);
79
+ } catch (error) {
80
+ logger.info('No existing meta cache found. Will create a new one.');
81
+ }
82
+ }
83
+
84
+ async function saveCache() {
85
+ try {
86
+ await fs.writeFile(CATALOG_CACHE_FILE, JSON.stringify(catalogCache));
87
+ await fs.writeFile(META_CACHE_FILE, JSON.stringify(metaCache));
88
+ logger.debug('Cache saved successfully');
89
+ } catch (error) {
90
+ logger.error('Error saving cache:', error);
91
+ }
92
+ }
93
+
94
+ async function fetchBillyConnollyCatalog() {
95
+ try {
96
+ const url = `${TMDB_BASE_URL}/person/9188/combined_credits?api_key=${TMDB_API_KEY}&language=en-GB`;
97
+ logger.debug(`Requesting TMDB: ${url}`);
98
+
99
+ const response = await axios.get(url);
100
+ const { cast } = response.data;
101
+
102
+ // Sort items by release date, descending (most recent first)
103
+ const sortedCast = cast.sort((a, b) => (b.release_date || b.first_air_date || '').localeCompare(a.release_date || a.first_air_date || ''));
104
+
105
+ logger.info(`Total Billy Connolly credits fetched: ${sortedCast.length}`);
106
+ return sortedCast;
107
+ } catch (error) {
108
+ logger.error('Error fetching Billy Connolly credits:', error);
109
+ return [];
110
+ }
111
+ }
112
+
113
+ async function fetchItemMetadata(itemIds) {
114
+ try {
115
+ const fetchMetadataPromises = itemIds.map(id => {
116
+ const url = `${TMDB_BASE_URL}/movie/${id}?api_key=${TMDB_API_KEY}`;
117
+ return axios.get(url).then(response => response.data);
118
+ });
119
+
120
+ const itemsData = await Promise.all(fetchMetadataPromises);
121
+ logger.debug(`Fetched metadata for ${itemsData.length} items`);
122
+ return itemsData;
123
+ } catch (error) {
124
+ logger.error('Error fetching item metadata:', error);
125
+ return [];
126
+ }
127
+ }
128
+
129
+ async function updateCatalogAndMetaCache() {
130
+ logger.info('Updating catalog and meta cache...');
131
+ try {
132
+ const items = await fetchBillyConnollyCatalog();
133
+ catalogCache = {
134
+ timestamp: Date.now(),
135
+ data: items
136
+ };
137
+
138
+ const itemIds = items.map(item => item.id);
139
+ const itemMetadata = await fetchItemMetadata(itemIds);
140
+
141
+ metaCache = itemMetadata.reduce((cache, itemData) => {
142
+ if (itemData.id) {
143
+ cache[itemData.id] = {
144
+ timestamp: Date.now(),
145
+ data: itemData
146
+ };
147
+ }
148
+ return cache;
149
+ }, {});
150
+
151
+ await saveCache();
152
+ logger.info(`Catalog and meta cache updated. Items: ${items.length}`);
153
+ } catch (error) {
154
+ logger.error('Error updating catalog and meta cache:', error);
155
+ }
156
+ }
157
+
158
+ builder.defineCatalogHandler(async (args) => {
159
+ const catalogId = args.id;
160
+ const genreFilter = args.extra?.genre || '';
161
+ const searchQuery = args.extra?.search || '';
162
+ logger.debug(`Catalog request received. ID: ${catalogId}, Genre: "${genreFilter}", Query: "${searchQuery}"`);
163
+
164
+ // Filter movies or TV shows based on catalog ID
165
+ let results = (catalogId === 'billy-connolly-movies')
166
+ ? catalogCache.data.filter(item => item.media_type === 'movie')
167
+ : catalogCache.data.filter(item => item.media_type === 'tv');
168
+
169
+ // Filter by search query if provided
170
+ if (searchQuery) {
171
+ results = results.filter(item =>
172
+ (item.title || item.name).toLowerCase().includes(searchQuery.toLowerCase())
173
+ );
174
+ }
175
+
176
+ // Filter by genre if provided
177
+ if (genreFilter) {
178
+ results = results.filter(item => item.genre_ids && item.genre_ids.includes(genreFilter));
179
+ }
180
+
181
+ const metas = results.map(item => ({
182
+ id: `tmdb-${item.id}`,
183
+ type: item.media_type === 'movie' ? 'movie' : 'series',
184
+ name: item.title || item.name,
185
+ poster: item.poster_path ? `https://image.tmdb.org/t/p/w500${item.poster_path}` : null,
186
+ description: item.overview || 'No description available',
187
+ releaseInfo: item.release_date ? item.release_date.split('-')[0] : item.first_air_date ? item.first_air_date.split('-')[0] : 'Unknown',
188
+ genre: item.genre_ids ? item.genre_ids.map(id => id) : []
189
+ }));
190
+
191
+ logger.info(`Catalog request processed. ID: ${catalogId}, Results: ${metas.length}`);
192
+ return { metas };
193
+ });
194
+
195
+ builder.defineMetaHandler(async (args) => {
196
+ const id = args.id.split('-')[1];
197
+ logger.debug(`Meta request received for item ID: ${id}`);
198
+
199
+ if (!metaCache[id]) {
200
+ logger.warn(`Meta data not found in cache for ID: ${id}`);
201
+ return { meta: { id: args.id, type: 'movie', name: 'Unknown Title', description: 'No description available' } };
202
+ }
203
+
204
+ const { data } = metaCache[id];
205
+ const { title, poster_path, backdrop_path, overview, release_date, genres, runtime, vote_average } = data;
206
+
207
+ return {
208
+ meta: {
209
+ id: args.id,
210
+ type: 'movie',
211
+ name: title || 'Unknown Title',
212
+ poster: poster_path ? `https://image.tmdb.org/t/p/w500${poster_path}` : null,
213
+ background: backdrop_path ? `https://image.tmdb.org/t/p/w1280${backdrop_path}` : null,
214
+ description: overview || 'No description available',
215
+ releaseInfo: release_date ? release_date.split('-')[0] : 'Unknown',
216
+ genre: genres && Array.isArray(genres) ? genres.map(g => g.name) : [],
217
+ runtime: runtime ? `${runtime} min` : 'Unknown',
218
+ rating: vote_average ? vote_average.toFixed(1) : 'N/A'
219
+ }
220
+ };
221
+ });
222
+
223
+ async function startServer() {
224
+ await ensureCacheDirectory();
225
+ await loadCache();
226
+
227
+ async function refreshCache() {
228
+ logger.info('Scheduled update: Refreshing catalog and meta cache');
229
+ await updateCatalogAndMetaCache();
230
+ }
231
+
232
+ // Schedule cache refresh every day at midnight
233
+ schedule.scheduleJob('0 0 * * *', refreshCache);
234
+
235
+ // Initial cache refresh if needed
236
+ if (!catalogCache.timestamp || Date.now() - catalogCache.timestamp > 24 * 60 * 60 * 1000) {
237
+ logger.info('Initial cache refresh needed');
238
+ await refreshCache();
239
+ } else {
240
+ logger.info('Cache is up to date. Next refresh scheduled for midnight');
241
+ }
242
+
243
+ const interface = builder.getInterface();
244
+ const port = process.env.PORT || 5655;
245
+
246
+ logger.info(`Starting Stremio Add-on server on port ${port}`);
247
+ serveHTTP(interface, { port });
248
+ }
249
+
250
+ startServer();
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "stremio-ufc-addon",
3
+ "version": "1.2.0",
4
+ "description": "Stremio Add-on to showcase UFC movies from TMDB with daily updates",
5
+ "main": "addon.js",
6
+ "scripts": {
7
+ "start": "node index.js"
8
+ },
9
+ "keywords": [
10
+ "stremio",
11
+ "addon",
12
+ "ufc",
13
+ "movies"
14
+ ],
15
+ "author": "Your Name",
16
+ "license": "MIT",
17
+ "dependencies": {
18
+ "stremio-addon-sdk": "^1.6.10",
19
+ "axios": "^0.27.2",
20
+ "winston": "^3.8.2",
21
+ "node-schedule": "^2.1.0"
22
+ },
23
+ "engines": {
24
+ "node": ">=14.0.0"
25
+ }
26
+ }