File size: 6,937 Bytes
1fa2c88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cache from '../cache.js';
import config from '../config.js';

export default class Tmdb {

  static id = 'tmdb';
  static name = 'The Movie Database';

  #cleanTmdbId(id) {
    return id.replace(/^tmdb-/, '');
  }

  #getSearchTitle(title) {
    // Special handling for UFC events
    const ufcMatch = title.match(/UFC Fight Night (\d+):/i) || title.match(/UFC (\d+):/i);
    if (ufcMatch) {
      return `UFC ${ufcMatch[1]}`;
    }
    return title;
  }

  async getMovieById(id, language){
    if (id.startsWith('tmdb-')) {
      try {
        const cleanId = this.#cleanTmdbId(id);
        const movie = await this.#request('GET', `/3/movie/${cleanId}`, {
          query: {
            language: language || 'en-US'
          }
        }, {
          key: `movie:${cleanId}:${language || '-'}`,
          ttl: 3600*3
        });

        return {
          name: this.#getSearchTitle(language ? movie.title || movie.original_title : movie.original_title || movie.title),
          originalName: language ? movie.title || movie.original_title : movie.original_title || movie.title,
          year: parseInt(`${movie.release_date}`.split('-').shift()),
          imdb_id: movie.imdb_id || id,
          type: 'movie',
          stremioId: id,
          id,
        };
      } catch (err) {
        console.log(`Failed to fetch movie directly with TMDB ID ${id}:`, err.message);
      }
    }
    
    // Fallback to IMDb lookup
    const searchId = await this.#request('GET', `/3/find/${id}`, {
      query: {
        external_source: 'imdb_id',
        language: language || 'en-US'
      }
    }, {
      key: `searchId:${id}:${language || '-'}`,
      ttl: 3600*3
    });
    
    if (!searchId.movie_results?.[0]) {
      throw new Error(`Movie not found: ${id}`);
    }
    
    const meta = searchId.movie_results[0];

    return {
      name: this.#getSearchTitle(language ? meta.title || meta.original_title : meta.original_title || meta.title),
      originalName: language ? meta.title || meta.original_title : meta.original_title || meta.title,
      year: parseInt(`${meta.release_date}`.split('-').shift()),
      imdb_id: id,
      type: 'movie',
      stremioId: id,
      id,
    };
  }

  async getEpisodeById(id, season, episode, language){
    if (id.startsWith('tmdb-')) {
      try {
        const cleanId = this.#cleanTmdbId(id);
        const show = await this.#request('GET', `/3/tv/${cleanId}`, {
          query: {
            language: language || 'en-US'
          }
        }, {
          key: `tv:${cleanId}:${language || '-'}`,
          ttl: 3600*3
        });

        const episodes = [];
        show.seasons.forEach(s => {
          for(let e = 1; e <= s.episode_count; e++){
            episodes.push({
              season: s.season_number,
              episode: e,
              stremioId: `${id}:${s.season_number}:${e}`
            });
          }
        });

        return {
          name: this.#getSearchTitle(language ? show.name || show.original_name : show.original_name || show.name),
          originalName: language ? show.name || show.original_name : show.original_name || show.name,
          year: parseInt(`${show.first_air_date}`.split('-').shift()),
          imdb_id: show.external_ids?.imdb_id || id,
          type: 'series',
          stremioId: `${id}:${season}:${episode}`,
          id,
          season,
          episode,
          episodes
        };
      } catch (err) {
        console.log(`Failed to fetch show directly with TMDB ID ${id}:`, err.message);
      }
    }

    const searchId = await this.#request('GET', `/3/find/${id}`, {
      query: {
        external_source: 'imdb_id'
      }
    }, {
      key: `searchId:${id}`,
      ttl: 3600*3
    });

    if (!searchId.tv_results?.[0]) {
      throw new Error(`TV series not found: ${id}`);
    }

    const meta = await this.#request('GET', `/3/tv/${searchId.tv_results[0].id}`, {
      query: {
        language: language || 'en-US'
      }
    }, {
      key: `${id}:${language}`,
      ttl: 3600*3
    });

    const episodes = [];
    meta.seasons.forEach(s => {
      for(let e = 1; e <= s.episode_count; e++){
        episodes.push({
          season: s.season_number,
          episode: e,
          stremioId: `${id}:${s.season_number}:${e}`
        });
      }
    });

    return {
      name: this.#getSearchTitle(language ? meta.name || meta.original_name : meta.original_name || meta.name),
      originalName: language ? meta.name || meta.original_name : meta.original_name || meta.name,
      year: parseInt(`${meta.first_air_date}`.split('-').shift()),
      imdb_id: id,
      type: 'series',
      stremioId: `${id}:${season}:${episode}`,
      id,
      season,
      episode,
      episodes
    };
  }

  async getLanguages(){
    return [{value: '', label: '🌎Original (Recommended)'}].concat(
      ...config.languages
        .map(language => ({value: language.iso639, label: language.label}))
        .filter(language => language.value)
    );
  }

  async #request(method, path, opts = {}, cacheOpts = {}) {
    const apiKey = config.tmdbAccessToken;

    // Normalize cache options
    cacheOpts = {
      key: '',
      ttl: 0,
      ...cacheOpts
    };

    // Check cache first
    if (cacheOpts.key) {
      const cached = await cache.get(`tmdb:${cacheOpts.key}`);
      if (cached) return cached;
    }

    // Clean up the path - remove any trailing slashes
    path = path.replace(/\/+$/, '');

    // Prepare query parameters including API key
    const queryParams = new URLSearchParams({
      api_key: apiKey,
      ...(opts.query || {})
    });

    // Build the complete URL
    const url = `https://api.themoviedb.org${path}?${queryParams}`;

    // Prepare request options
    const requestOpts = {
      method,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=utf-8',
        ...opts.headers
      }
    };

    // Debug log the full URL
    console.log('TMDB Request URL:', url);
    console.log('TMDB Request Headers:', requestOpts.headers);

    try {
      const res = await fetch(url, requestOpts);
      const data = await res.json();

      // Debug log the response
      console.log('TMDB Response Status:', res.status);
      console.log('TMDB Response Data:', JSON.stringify(data, null, 2));

      if (!res.ok) {
        console.error('TMDB API Error:', {
          status: res.status,
          url: url,
          headers: requestOpts.headers,
          response: data
        });
        throw new Error(`TMDB API error: ${data.status_message || 'Unknown error'}`);
      }

      // Cache successful response if needed
      if (cacheOpts.key && cacheOpts.ttl > 0) {
        await cache.set(`tmdb:${cacheOpts.key}`, data, {ttl: cacheOpts.ttl});
      }

      return data;
    } catch (error) {
      console.error('TMDB Request failed:', error);
      throw error;
    }
  }
}