-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
319 lines (254 loc) · 8.95 KB
/
index.js
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
var durableJsonLint = require('durable-json-lint'),
needle = require('needle'),
stream = require('stream');
var HOST = 'http://www.omdbapi.com/',
TYPES = [ 'movie', 'series', 'episode' ];
// Series have a different format to describe years, so account for that when we
/// format it. For example,
// "1989" == 1998
// "1989-" == { from: 1989, to: undefined }
// "1989-2014" == { from: 1989, to: 2014 }
function formatYear(year) {
var from, to;
year = year.split('–');
if (year.length === 2) {
from = +year[0];
if (year[1]) {
to = +year[1];
}
return { from: from, to: to };
}
return +year;
}
// Format strings of hours & minutes into minutes. For example,
// "1 h 30 min" == 90.
function formatRuntime(raw) {
var hours, minutes;
if (!raw) {
return null;
}
hours = raw.match(/(\d+) h/);
minutes = raw.match(/(\d+) min/);
hours = hours ? hours[1] : 0;
minutes = minutes ? +minutes[1] : 0;
return (hours * 60) + minutes;
}
// Convert votes from a US formatted string of a number to a Number.
function formatVotes(raw) {
return raw ? +raw.match(/\d/g).join('') : null;
}
// Remove all the strings found within brackets and split by comma.
function formatList(raw) {
var list;
if (!raw) {
return [];
}
list = raw.replace(/\(.+?\)/g, '').split(', ');
list = list.map(function (item) {
return item.trim();
});
return list;
}
// Try to find the win and nomination count, but also keep raw just in case.
function formatAwards(raw) {
var wins, nominations;
if (!raw) {
return { wins: 0, nominations: 0, text: '' };
}
wins = raw.match(/(\d+) wins?/i);
nominations = raw.match(/(\d+) nominations?/i);
return {
wins: wins ? +wins[1] : 0,
nominations: nominations ? +nominations[1] : 0,
text: raw
};
}
// Search for movies by titles.
module.exports.search = function (terms, done) {
var query = {};
if (typeof terms === 'string') {
query.s = terms;
} else {
query.s = terms.terms || terms.s;
query.y = terms.year || terms.y;
query.type = terms.type;
}
if (!query.s) {
return done(new Error('No search terms specified.'));
}
if (query.type) {
if (TYPES.indexOf(query.type) < 0) {
return done(new Error('Invalid type specified. Valid types are: ' +
TYPES.join(', ') + '.'));
}
}
if (query.y) {
query.y = parseInt(query.y, 10);
if (isNaN(query.y)) {
return done(new Error('Year is not an integer.'));
}
}
needle.request('get', HOST, query, function (err, res, movies) {
if (err) {
return done(err);
}
if (res.statusCode !== 200) {
return done(new Error('status code: ' + res.statusCode));
}
// If no movies are found, the API returns
// "{"Response":"False","Error":"Movie not found!"}" instead of an
// empty array. So in this case, return an empty array to be consistent.
if (movies.Response === 'False') {
return done(null, []);
}
// Fix the ugly capitalized naming and cast the year as a Number.
done(null, movies.Search.map(function (movie) {
return {
title: movie.Title,
year: formatYear(movie.Year),
imdb: movie.imdbID,
type: movie.Type,
poster: movie.Poster
};
}));
});
};
// Find a movie by title, title & year or IMDB ID. The second argument is
// optional and determines whether or not to return an extended plot synopsis.
module.exports.get = function (show, options, done) {
var query = {};
// If the third argument is omitted, treat the second argument as the
// callback.
if (!done) {
done = options;
options = {};
// If options is given, but is not an object, assume fullPlot: true
// for backwards compatibility.
} else if (options && typeof options !== 'object') {
options = { fullPlot: true };
}
query.plot = options.fullPlot ? 'full' : 'short';
// Include Rotten Tomatoes rating, if requested.
if (options.tomatoes) {
query.tomatoes = true;
}
// Select query based on explicit IMDB ID, explicit title, title & year,
// IMDB ID and title, respectively.
if (show.imdb) {
query.i = show.imdb;
} else if (show.title) {
query.t = show.title;
// In order to search with a year, a title must be present.
if (show.year) {
query.y = show.year;
}
if (show.type) {
query.type = show.type;
if (TYPES.indexOf(query.type) < 0) {
return done(new Error('Invalid type specified. Valid types ' +
'are: ' + TYPES.join(', ') + '.'));
}
}
// Assume anything beginning with "tt" and ending with digits is an
// IMDB ID.
} else if (/^tt\d+$/.test(show)) {
query.i = show;
// Finally, assume options is a string repesenting the title.
} else {
query.t = show;
}
needle.request('get', HOST, query, function (err, res, movie) {
if (err) {
return done(err);
}
if (res.statusCode !== 200) {
return done(new Error('status code: ' + res.statusCode));
}
// Needle was unable to parse the JSON. Try durable-json-lint.
if (typeof movie === 'string') {
try {
movie = JSON.parse(durableJsonLint(movie).json);
} catch (e) {
return done(new Error('Malformed JSON.'));
}
}
// The movie being searched for could not be found.
if (!movie || movie.Response === 'False') {
return done();
}
// Replace 'N/A' strings with null for simple checks in the return
// value.
Object.keys(movie).forEach(function (key) {
if (movie[key] === 'N/A') {
movie[key] = null;
}
});
// Beautify and normalize the ugly results the API returns.
done(null, {
title: movie.Title,
year: formatYear(movie.Year),
rated: movie.Rated,
season: movie.Season ? +movie.Season : null,
episode: movie.Episode ? +movie.Episode : null,
totalSeasons: movie.totalSeasons ? + movie.totalSeasons : null,
// Cast the API's release date as a native JavaScript Date type.
released: movie.Released ? new Date(movie.Released) : null,
// Return runtime as minutes casted as a Number instead of an
// arbitrary string.
runtime: formatRuntime(movie.Runtime),
countries: formatList(movie.Country),
genres: formatList(movie.Genre),
director: movie.Director,
writers: formatList(movie.Writer),
actors: formatList(movie.Actors),
plot: movie.Plot,
// A hotlink to a JPG of the movie poster on IMDB.
poster: movie.Poster,
imdb: {
id: movie.imdbID,
rating: movie.imdbRating ? +movie.imdbRating : null,
votes: formatVotes(movie.imdbVotes)
},
// Determine tomatoRatings existance by the presense of tomatoMeter.
tomato: !movie.tomatoMeter ? undefined : {
meter: +movie.tomatoMeter,
image: movie.tomatoImage,
rating: +movie.tomatoRating,
reviews: +movie.tomatoReviews,
fresh: +movie.tomatoFresh,
rotten: +movie.tomatoRotten,
consensus: movie.tomatoConsensus,
userMeter: +movie.tomatoUserMeter,
userRating: +movie.tomatoUserRating,
userReviews: +movie.tomatoUserReviews,
url: movie.tomatoURL,
dvdReleased: movie.DVD ? new Date(movie.DVD) : null
},
metacritic: movie.Metascore ? +movie.Metascore : null,
awards: formatAwards(movie.Awards),
type: movie.Type
});
});
};
// Get a Readable Stream with the jpg image data of the poster to the movie,
// identified by title, title & year or IMDB ID.
module.exports.poster = function (show) {
var out = new stream.PassThrough(),
req;
module.exports.get(show, false, function (err, res) {
if (err) {
out.emit('error', err);
} else if (!res) {
out.emit('error', new Error('Movie not found'));
} else if (!res.poster) {
out.emit('error', new Error('Poster not found'));
} else {
req = needle.get(res.poster);
req.on('error', function (err) {
out.emit('error', err);
});
req.pipe(out);
}
});
return out;
};