-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.ts
509 lines (479 loc) · 16.7 KB
/
helpers.ts
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
import * as coda from "@codahq/packs-sdk";
/* -------------------------------------------------------------------------- */
/* Config */
/* -------------------------------------------------------------------------- */
const IMDB_BASE_URL = "https://tv-api.com/en/API/";
const TMDB_BASE_URL = "https://api.themoviedb.org/3/";
const TMDB_IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w780/";
const IMDB_TITLE_ID_REGEX = new RegExp("^ttd+$"); // tt followed by 1 or more digits
const IMDB_PERSON_ID_REGEX = new RegExp("^nmd+$"); // nm followed by 1 or more digits
/* -------------------------------------------------------------------------- */
/* Helper Functions */
/* -------------------------------------------------------------------------- */
/**
* Builds an API request URL using Coda's fancy templating syntax for custom auth
* (https://coda.github.io/packs-sdk/reference/sdk/interfaces/CustomAuthentication/)
* which is needed because the tv-api.com API requires the API Key to be delivered
* as part of the URL path (not a query string parameter). For example (with k_12345678
* as the api key): https://tv-api.com/en/API/SearchMovie/k_12345678/incendies
*/
export async function imdbApiFetch(
context: coda.ExecutionContext,
endpoint: string,
query: string,
options?: string[]
) {
// Build the URL
let url =
IMDB_BASE_URL +
endpoint +
"/{{imdbApiKey-" +
context.invocationToken +
"}}/" +
encodeURIComponent(query);
// Add options to it, if any
if (options?.length) {
url += "/";
options.forEach((option) => {
url += option + ",";
});
}
const response = await context.fetcher.fetch({
method: "GET",
url: url,
cacheTtlSecs: 60 * 60 * 24,
});
return response;
}
/**
* Fetches data from the TMDb API
* @param context
* @param endpoint Main endpoint
* @param id TMDB ID of the movie, series, etc.
* @param subEndpoint Additional URL path after ID (e.g. "watch/providers")
* @param params URL parameters (e.g. language, external_source for searching IMDB IDs)
* @returns Promise resolving to the response
*/
export async function tmdbApiFetch(
context: coda.ExecutionContext,
endpoint: "movie" | "tv" | "find" | "watch/providers/regions", // comes before the id in the URL
id?: string,
subEndpoint?: string, // comes after the movie in the URL
params?: { [key: string]: string }
) {
// Build the URL
let url = TMDB_BASE_URL + endpoint;
if (id) url += "/" + id;
if (subEndpoint) url += "/" + subEndpoint;
params = {
...params,
api_key: "{{tmdbApiKey-" + context.invocationToken + "}}",
};
url = coda.withQueryParams(url, params);
const response = await context.fetcher.fetch({
method: "GET",
url,
cacheTtlSecs: 60 * 60 * 24,
});
// console.log(JSON.stringify(response, null, 2));
return response;
}
/**
* Convenience function to get initial data from TMDB based on IMDb ID
*/
export async function searchTmbdByImdbId(
context: coda.ExecutionContext,
imdbId: string
) {
return tmdbApiFetch(
context,
"find",
imdbId,
undefined, // no sub-endpoint
{ external_source: "imdb_id" }
);
}
/**
* Build Coda-schema-ready object for streaming providers for a given TMDB ID
*/
async function getWatchProviders(
context: coda.ExecutionContext,
tmdbId: string,
mediaType: "movie" | "tv",
countryCode: string
) {
const streamingResult = await tmdbApiFetch(
context,
mediaType,
tmdbId,
"watch/providers"
);
// We're just interested in the local providers
const localProviders = streamingResult?.body?.results[countryCode];
if (!localProviders) return null;
return {
stream: localProviders.flatrate
? localProviders.flatrate.map((provider) => ({
name: provider.provider_name,
country: countryCode,
}))
: [],
buy: localProviders.buy
? localProviders.buy.map((provider) => ({
name: provider.provider_name,
country: countryCode,
}))
: [],
rent: localProviders.rent
? localProviders.rent.map((provider) => ({
name: provider.provider_name,
country: countryCode,
}))
: [],
link: localProviders.link,
};
}
/**
* Build Coda-schema-ready object for an array of people (actors, directors, etc.)
* @param people Array of person objects from IMDb response
* @param imageSource Special circumstance where a long list of actors includes images; we
* don't usually want the full actor list, but want to query it to pull images for the main stars
*/
export function buildPeopleRecord(
people: { id: string; name: string }[],
imageSource?: {
id: string;
image: string;
name: string;
asCharacter: string;
}[]
):
| {
Name: string;
ImdbLink: string;
ImdbId: string;
Photo?: string | undefined;
}[]
| undefined {
console.log("People:", JSON.stringify(people));
// return undefined if there are no people
if (!people || !people.length || !Array.isArray(people)) return undefined;
// otherwise, process into People object
return people.map((person) => {
// grab the photo from the imageSource array if it exists
let photo: string | undefined;
if (imageSource && Array.isArray(imageSource) && imageSource.length) {
photo = imageSource.find(
(sourceRecord) => sourceRecord.id === person.id
)?.image;
}
return {
Name: person.name,
ImdbLink: `https://imdb.com/name/${person.id}/`,
ImdbId: person.id,
Photo: photo,
};
});
}
function age(birthDate: string, deathDate?: string) {
const birthDateObject = new Date(birthDate);
const endDateObject = deathDate ? new Date(deathDate) : new Date();
const age = endDateObject.getFullYear() - birthDateObject.getFullYear();
const m = endDateObject.getMonth() - birthDateObject.getMonth();
if (
m < 0 ||
(m === 0 && endDateObject.getDate() < birthDateObject.getDate())
) {
return age - 1;
}
return age;
}
/* -------------------------------------------------------------------------- */
/* Execute Functions for Formulas */
/* -------------------------------------------------------------------------- */
export async function getMovie(
context: coda.ExecutionContext,
query: string,
countryCode: string = "US"
) {
let imdbId: string;
// First, let's see if the user supplied an IMDb ID, or a regular search term
if (IMDB_TITLE_ID_REGEX.test(query)) {
imdbId = query;
} else {
// We start with a name search, to try to nail down an imdb ID that we can use to
// fetch all our other data.
const nameSearchResponse = await imdbApiFetch(
context,
"SearchMovie",
query
);
// console.log(
// "Name search response:",
// JSON.stringify(nameSearchResponse.body, null, 2)
// );
if (nameSearchResponse.body.errorMessage)
throw new coda.UserVisibleError(
"Error: ",
nameSearchResponse.body.errorMessage
);
if (
!nameSearchResponse.body.results ||
!nameSearchResponse.body.results.length
)
throw new coda.UserVisibleError("Couldn't find a movie with that title");
// We're always going to grab the top search result
const nameSearchResult = nameSearchResponse?.body?.results[0];
imdbId = nameSearchResult?.id;
}
// Now gather more details by hitting the IMDB API again, as well as the TMDB API
const [imdbDetailResponse, tmdbDetailResponse] = await Promise.all([
// Include Ratings with the detail request
imdbApiFetch(context, "Title", imdbId, ["Ratings,Trailer"]),
searchTmbdByImdbId(context, imdbId),
]);
const imdbDetails = imdbDetailResponse.body;
const tmdbDetails = tmdbDetailResponse.body.movie_results[0];
// console.log("imdbDetails: " + JSON.stringify(imdbDetails, null, 2));
// console.log("tmdbDetails: " + JSON.stringify(tmdbDetails, null, 2));
// Get straeaming providers
let watchProviders: {
stream?: any;
buy?: any;
rent?: any;
link?: any;
} | null = {};
if (tmdbDetails) {
watchProviders = await getWatchProviders(
context,
tmdbDetails?.id,
"movie",
countryCode
);
}
const nonDigitCharacterPattern = /\D/g; // for converting box office data to numbers
return {
// IMDB-derived fields (detail API response)
ImdbId: imdbDetails?.id,
Description: imdbDetails?.description,
Title: imdbDetails?.title,
VerticalPoster: imdbDetails?.image,
Year: imdbDetails?.year,
Runtime: imdbDetails?.runtimeMins + " minutes",
Director: buildPeopleRecord(imdbDetails?.directorList),
Plot: imdbDetails?.plot,
TrailerLink: imdbDetails?.trailer?.link,
ImdbLink: "https://imdb.com/title/" + imdbId,
ImdbRating: imdbDetails?.imDbRating,
Metacritic: imdbDetails?.metacriticRating,
RottenTomatoes: imdbDetails?.ratings?.rottenTomatoes,
ContentRating: imdbDetails?.contentRating,
Writer: buildPeopleRecord(imdbDetails?.writerList),
Starring: buildPeopleRecord(imdbDetails?.starList, imdbDetails?.actorList),
Genres: imdbDetails?.genres ? imdbDetails.genres.split(", ") : [],
Countries: imdbDetails?.countries ? imdbDetails.countries.split(", ") : [],
Companies: imdbDetails?.companies ? imdbDetails.companies.split(", ") : [],
BoxOffice: {
Budget: imdbDetails?.boxOffice?.budget?.replace(
nonDigitCharacterPattern,
""
) as number,
USAGross: imdbDetails?.boxOffice?.grossUSA?.replace(
nonDigitCharacterPattern,
""
) as number,
GlobalGross: imdbDetails?.boxOffice?.cumulativeWorldwideGross?.replace(
nonDigitCharacterPattern,
""
) as number,
USAOpeningWeekend: imdbDetails?.boxOffice?.openingWeekendUSA?.replace(
nonDigitCharacterPattern,
""
) as number,
},
// TMDB-derived fields
HorizontalPoster: TMDB_IMAGE_BASE_URL + tmdbDetails?.backdrop_path,
WatchLinks: watchProviders?.link,
Stream: watchProviders?.stream,
Buy: watchProviders?.buy,
Rent: watchProviders?.rent,
};
}
export async function getSeries(
context: coda.ExecutionContext,
query: string,
countryCode: string = "US"
) {
let imdbId: string;
// First, let's see if the user supplied an IMDb ID, or a regular search term
if (IMDB_TITLE_ID_REGEX.test(query)) {
imdbId = query;
} else {
// We start with a name search, to try to nail down an imdb ID that we can use to
// fetch all our other data.
const nameSearchResponse = await imdbApiFetch(
context,
"SearchSeries",
query
);
if (nameSearchResponse.body.errorMessage)
throw new coda.UserVisibleError(
"Error: ",
nameSearchResponse.body.errorMessage
);
if (
!nameSearchResponse.body.results ||
!nameSearchResponse.body.results.length
)
throw new coda.UserVisibleError(
"Couldn't find a TV show with that title"
);
// We're always going to grab the top search result
const nameSearchResult = nameSearchResponse?.body?.results[0];
imdbId = nameSearchResult?.id;
}
// Now gather more details by hitting the IMDB API again, and hit the TMDB API
// to get basic TMDB details including the TMDB id
const [imdbDetailResponse, tmdbSearchResponse] = await Promise.all([
// Include Ratings and Trailer with the detail request
imdbApiFetch(context, "Title", imdbId, ["Ratings,Trailer"]),
searchTmbdByImdbId(context, imdbId),
]);
const imdbDetails = imdbDetailResponse.body;
const tmdbSearchDetails = tmdbSearchResponse.body.tv_results[0];
console.log("imdbDetails: " + JSON.stringify(imdbDetails, null, 2));
console.log(
"tmdbSearchDetails: " + JSON.stringify(tmdbSearchDetails, null, 2)
);
// Get streaming providers and additional TMDB details
let watchProviders: { [key: string]: any } | null = {}; // TODO: type this
let tmdbDetailResponse;
let seasons: { [key: string]: any }[] = [{}]; // TODO: type this
if (tmdbSearchDetails) {
[watchProviders, tmdbDetailResponse] = await Promise.all([
getWatchProviders(context, tmdbSearchDetails?.id, "tv", countryCode),
tmdbApiFetch(context, "tv", tmdbSearchDetails?.id),
]);
}
const tmdbDetails = tmdbDetailResponse?.body;
if (tmdbDetails.seasons) {
seasons = tmdbDetails.seasons.map((season) => {
return {
SeasonNumber: season.season_number,
SeasonName: season.name,
EpisodeCount: season.episode_count,
AirDate: season.air_date,
};
});
}
return {
// IMDB-derived fields (detail API response)
ImdbId: imdbId,
Description: imdbDetails.description,
Title: imdbDetails.title,
VerticalPoster: imdbDetails.image,
FullTitle: imdbDetails?.fullTitle,
Creators: buildPeopleRecord(imdbDetails?.tvSeriesInfo?.creatorList),
Years: {
StartYear: imdbDetails?.year,
EndYear: imdbDetails?.tvSeriesInfo?.yearEnd,
Years: `${imdbDetails?.year}-${imdbDetails?.tvSeriesInfo?.yearEnd}`,
},
ImdbLink: "https://imdb.com/title/" + imdbId,
ContentRating: imdbDetails?.contentRating,
ImdbRating: imdbDetails?.imDbRating,
Metacritic: imdbDetails?.metacriticRating,
RottenTomatoes: imdbDetails?.ratings?.rottenTomatoes,
Plot: imdbDetails?.plot,
Starring: buildPeopleRecord(imdbDetails?.starList, imdbDetails?.actorList),
Genres: imdbDetails?.genres ? imdbDetails.genres.split(", ") : [],
Countries: imdbDetails?.countries ? imdbDetails.countries.split(", ") : [],
Companies: imdbDetails?.companies ? imdbDetails.companies.split(", ") : [],
TrailerLink: imdbDetails?.trailer?.link,
// TMDB-derived fields
HorizontalPoster: TMDB_IMAGE_BASE_URL + tmdbSearchDetails?.backdrop_path,
WatchLinks: watchProviders?.link,
Stream: watchProviders?.stream,
Buy: watchProviders?.buy,
Rent: watchProviders?.rent,
Seasons: seasons,
Networks: tmdbDetails?.networks
? tmdbDetails.networks.map((network) => network.name)
: [],
NextEpisodeAirDate: tmdbDetails.next_episode_to_air?.air_date,
Status: tmdbDetails.status,
};
}
export async function getPerson(context: coda.ExecutionContext, query: string) {
let imdbId: string;
// First, let's see if the user supplied an IMDb ID, or a regular search term
if (IMDB_PERSON_ID_REGEX.test(query)) {
imdbId = query;
console.log("IMDB ID supplied");
} else {
// We start with a name search, to try to nail down an imdb ID that we can use to
// fetch all our other data.
const nameSearchResponse = await imdbApiFetch(context, "SearchName", query);
if (nameSearchResponse.body.errorMessage)
throw new coda.UserVisibleError(
"Error: ",
nameSearchResponse.body.errorMessage
);
if (
!nameSearchResponse.body.results ||
!nameSearchResponse.body.results.length
)
throw new coda.UserVisibleError("Couldn't find a person with that name");
// We're always going to grab the top search result
const nameSearchResult = nameSearchResponse?.body?.results[0];
imdbId = nameSearchResult?.id;
}
// Now gather more details by hitting the IMDB API again
const imdbDetailResponse = await imdbApiFetch(context, "Name", imdbId);
const imdbDetails = imdbDetailResponse.body;
let knownFor: [{ [key: string]: any }?] = [];
for (const item of imdbDetails?.knownFor) {
knownFor.push({
Summary: `${item.role}, ${item.fullTitle}`,
Title: item.title,
Role: item.role,
Year: item.year,
ImdbId: item.id,
ImdbLink: "https://imdb.com/title/" + item.id,
Poster: item.image,
});
}
return {
Name: imdbDetails?.name,
Description: knownFor[0]?.Summary,
Photo: imdbDetails?.image,
Roles: imdbDetails?.role?.split(", "),
KnownFor: knownFor,
Bio: imdbDetails?.summary,
BirthDate: imdbDetails?.birthDate,
DeathDate: imdbDetails?.deathDate,
Age: age(imdbDetails?.birthDate, imdbDetails?.deathDate),
Height: imdbDetails?.height,
Awards: imdbDetails?.awards,
ImdbLink: "https://imdb.com/name/" + imdbId,
ImdbId: imdbId,
};
}
/* -------------------------------------------------------------------------- */
/* Autocomplete Functions */
/* -------------------------------------------------------------------------- */
export async function autocompleteCountryCode(
context: coda.ExecutionContext,
search: string
) {
let response = await tmdbApiFetch(context, "watch/providers/regions");
let results = response.body.results;
// Generate an array of autocomplete objects, using the native_name field as the
// label and its country code for the value.
return coda.autocompleteSearchObjects(
search,
results,
"native_name",
"iso_3166_1"
);
}