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 | import axios, { AxiosError } from 'axios';
import Logger from './logger';
export interface TVDBEpisode {
id: number;
seriesId: number;
name: string;
aired: string;
runtime: number;
nameTranslations: string[];
overview: string;
image: string;
overviewTranslations: Array<{
language: string;
overview: string;
}>;
imageType: number;
seasonNumber: number;
number: number;
lastUpdated: string;
finaleType: string;
airsAfterSeason: number;
airsBeforeSeason: number;
airsBeforeEpisode: number;
thumbWidth: string;
thumbHeight: string;
companies: {
studio: null;
network: null;
production: null;
distributor: null;
special_effects: null;
};
seasons: {
id: number;
seriesId: number;
type: {
id: number;
name: string;
type: string;
alternateName: string | null;
};
number: number;
};
}
interface TVDBEpisodesResponse {
status: 'success' | 'error';
data: {
series: {
id: number;
name: string;
};
episodes: TVDBEpisode[];
};
}
interface TVDBConfig {
apiKey: string;
pin?: string;
}
interface TVDBArtwork {
id: number;
image: string;
thumbnail: string;
language: string | null;
type: number;
score: number;
width: number;
height: number;
includesText: boolean;
thumbnailWidth: number;
thumbnailHeight: number;
updatedAt: number;
status: {
id: number;
name: string | null;
};
tagOptions: null;
seasonId?: number;
}
interface TVDBCompany {
id: number;
name: string;
slug: string;
nameTranslations: string[];
overviewTranslations: string[];
aliases: Array<{
language: string;
name: string;
}>;
country: string;
primaryCompanyType: number;
activeDate: string | null;
inactiveDate: string | null;
companyType: {
companyTypeId: number;
companyTypeName: string;
};
parentCompany: {
id: number | null;
name: string | null;
relation: {
id: null;
typeName: null;
};
};
tagOptions: null;
}
interface TVDBCharacter {
id: number;
name: string;
peopleId: number;
seriesId: number;
series: null;
movie: null;
movieId: null;
episodeId: null;
type: number;
image: string;
sort: number;
isFeatured: boolean;
url: string;
nameTranslations: null;
overviewTranslations: null;
aliases: null;
peopleType: string;
personName: string;
tagOptions: null;
personImgURL: string;
}
interface TVDBSeason {
id: number;
seriesId: number;
type: {
id: number;
name: string;
type: string;
alternateName: string | null;
};
number: number;
nameTranslations: string[];
overviewTranslations: string[];
image?: string;
imageType?: number;
companies: {
studio: null;
network: null;
production: null;
distributor: null;
special_effects: null;
};
lastUpdated: string;
name?: string;
}
interface TVDBResponse {
status: 'success' | 'error';
data: {
id: number;
name: string;
slug: string;
image: string;
nameTranslations: string[];
overviewTranslations: string[];
aliases: Array<{
language: string;
name: string;
}>;
firstAired: string;
lastAired: string;
nextAired: string;
score: number;
status: {
id: number;
name: string;
recordType: string;
keepUpdated: boolean;
};
originalCountry: string;
originalLanguage: string;
defaultSeasonType: number;
isOrderRandomized: boolean;
lastUpdated: string;
averageRuntime: number;
episodes: null;
overview: string;
year: string;
artworks: TVDBArtwork[];
companies: TVDBCompany[];
originalNetwork: TVDBCompany;
latestNetwork: TVDBCompany;
genres: Array<{
id: number;
name: string;
slug: string;
}>;
contentRatings: Array<{
id: number;
name: string;
country: string;
description: string;
contentType: string;
order: number;
fullname: string | null;
}>;
characters: TVDBCharacter[];
seasons: TVDBSeason[];
seasonTypes: Array<{
id: number;
name: string;
type: string;
alternateName: string | null;
}>;
};
}
export class TVDBClient {
private token: string | null = null;
private tokenExpiry: number = 0;
private readonly apiKey: string;
private readonly baseUrl = 'https://api4.thetvdb.com/v4';
constructor(config: TVDBConfig) {
this.apiKey = config.apiKey;
}
private async authenticate(): Promise<void> {
try {
const response = await axios.post(`${this.baseUrl}/login`, {
apiKey: this.apiKey,
});
if (!response.data?.data?.token) {
throw new Error('Invalid authentication response');
}
const { token, expiresAt } = response.data.data;
this.token = token;
this.tokenExpiry = new Date(expiresAt).getTime();
Logger.debug('TVDB Authentication successful', { timestamp: true, prefix: 'TVDB' });
} catch (error) {
Logger.error('TVDB Authentication failed', { timestamp: true, prefix: 'TVDB' });
throw error;
}
}
private async ensureAuthenticated(): Promise<void> {
if (this.token && this.tokenExpiry > Date.now()) {
return;
}
await this.authenticate();
}
private async request<T, D = Record<string, unknown>>(
endpoint: string,
method: 'GET' | 'POST' = 'GET',
data?: D,
): Promise<T> {
await this.ensureAuthenticated();
try {
const response = await axios({
method,
url: `${this.baseUrl}${endpoint}`,
headers: {
Authorization: `Bearer ${this.token}`,
'Content-Type': 'application/json',
Accept: 'application/json',
},
data,
});
return response.data;
} catch (error) {
if (error instanceof AxiosError && error.response?.status === 401) {
Logger.warn('Token expired, reauthenticating', { timestamp: true, prefix: 'TVDB' });
await this.authenticate();
return this.request(endpoint, method, data);
}
const message = error instanceof Error ? error.message : 'Unknown error';
Logger.error(`Request failed: ${message}`, { timestamp: true, prefix: 'TVDB' });
throw error;
}
}
async searchAnime(query: string) {
Logger.debug(`Searching for anime: ${query}`, { timestamp: true, prefix: 'TVDB' });
return this.request<TVDBResponse>('/search', 'POST', {
query,
type: 'series',
filter: {
type: 'anime',
},
});
}
async getAnimeById(id: number) {
Logger.debug(`Fetching anime details: ${id}`, { timestamp: true, prefix: 'TVDB' });
return this.request<TVDBResponse>(`/series/${id}/extended`);
}
async getAnimeEpisodes(id: number, season?: number): Promise<TVDBEpisodesResponse> {
Logger.debug(`Fetching episodes for anime: ${id}, season: ${season || 'all'}`, {
timestamp: true,
prefix: 'TVDB',
});
const endpoint = season
? `/series/${id}/episodes/official/${season}`
: `/series/${id}/episodes/official`;
const response = await this.request<TVDBEpisodesResponse>(endpoint);
// Now fetch translations for each episode
if (response.data?.episodes) {
await Promise.all(
response.data.episodes.map(async (episode) => {
try {
// Fetch English translation
const engTranslation = await this.request<{ data: { overview: string } }>(
`/episodes/${episode.id}/translations/eng`,
);
// Fetch Japanese translation
const jpnTranslation = await this.request<{ data: { overview: string } }>(
`/episodes/${episode.id}/translations/jpn`,
);
episode.overviewTranslations = [
{ language: 'eng', overview: engTranslation.data.overview },
{ language: 'jpn', overview: jpnTranslation.data.overview },
];
} catch (error) {
Logger.error(`Failed to fetch translations for episode ${episode.id}: ${error}`, {
timestamp: true,
prefix: 'TVDB',
});
}
}),
);
}
return response;
}
}
export default TVDBClient;
|