summaryrefslogtreecommitdiffstats
path: root/lib/helpers.js
blob: 5a60932ff902d3460a0d6900ba2e8e84c8ca4897 (plain)
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
var Show = require('../models/Show')
var eztv = require('./eztv')
var providers = [eztv];
var async = require('async')
var Trakt = require('trakt')
var trakt = new Trakt({
	api_key: '7b7b93f7f00f8e4b488dcb3c5baa81e1619bb074'
})
var config = require('../config')
var URI = require('URIjs')

var TTL = config.scrapeTtl;

var helpers = {

	// resize image
	resizeImage: function(imageUrl, width) {
		var uri = URI(imageUrl),
			ext = uri.suffix(),
			file = uri.filename().split('.' + ext)[0];

		// Don't resize images that don't come from trakt
		//  eg. YTS Movie Covers
		if (uri.domain() !== 'trakt.us') {
			return imageUrl;
		}

		var existingIndex = 0;
		if ((existingIndex = file.search('-\\d\\d\\d$')) !== -1) {
			file = file.slice(0, existingIndex);
		}

		if (file === 'poster-dark') {
			return 'images/posterholder.png'.toString();
		} else {
			return uri.filename(file + '-' + width + '.' + ext).toString();
		}
	},

	// Source: http://stackoverflow.com/a/1714899/192024
	buildQuerystring: function(obj) {
		var str = []
		for (var p in obj)
			if (obj.hasOwnProperty(p))
				str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
		return str.join('&')
	},

	// Source: http://phpjs.org/functions/preg_quote/
	preg_quote: function(str, delimiter) {
		return String(str)
			.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
	},

	// Determine if a given string matches a given pattern.
	// Inspired by PHP from Laravel 4.1
	str_is: function(pattern, value) {
		if (pattern == value) return true
		if (pattern == '*') return true

		pattern = this.preg_quote(pattern, '/')

		// Asterisks are translated into zero-or-more regular expression wildcards
		// to make it convenient to check if the strings starts with the given
		// pattern such as "library/*", making any string check convenient.
		var regex = new RegExp('^' + pattern.replace('\\*', '.*') + '$')

		return !!value.match(regex);
	},

	// Source: http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/comment-page-1/
	stringToCamel: function(str) {
		return str.replace(/(\-[a-z])/g, function($1) {
			return $1.toUpperCase().replace('-', '')
		})
	},


	extractShowInfo: function(show, callback) {

		var that = this;
		console.log("extractShowInfo " + show.show + " " + show.imdb_id);
		var thisShow = {};
		var thisEpisodes = [];
		var thisEpisode = {};
		var numSeasons = 0;

		var imdb = show.imdb_id;

		eztv.getAllEpisodes(show, function(err, data) {
			thisShow = data;

			if (!data) return callback(null, show);
			if (!show.show) return callback(null, show);

			console.log("Looking for " + show.show);

			var dateBased = data.dateBased;
			delete data.dateBased;

			numSeasons = Object.keys(data).length; //Subtract dateBased key

			// upate with right torrent link
			if (!dateBased) {
				async.each(Object.keys(data), function(season, cb) {
						try {
							trakt.request('show', 'season', {
								title: imdb,
								season: season
							}, function(err, seasonData) {
								for (var episodeData in seasonData) {
									episodeData = seasonData[episodeData];
									if (typeof(data[season]) != 'undefined' && typeof(data[season][episodeData.episode]) != 'undefined') {
										// hardcode the 720 for this source
										// TODO: Should add it from eztv_x
										thisEpisode = {
											tvdb_id: episodeData.tvdb_id,
											season: episodeData.season,
											episode: episodeData.episode,
											title: episodeData.title,
											overview: episodeData.overview,
											date_based: false,
											first_aired: episodeData.first_aired_utc,
											watched: {
												watched: false
											},
											torrents: []
										};
										thisEpisode.torrents = data[season][episodeData.episode];
										thisEpisode.torrents[0] = data[season][episodeData.episode]["480p"] ? data[season][episodeData.episode]["480p"] : data[season][episodeData.episode]["720p"]; // Prevents breaking the app
										thisEpisodes.push(thisEpisode);
									}
								}
								cb();
							});
						} catch (err) {
							console.error("Error:", err)
							return cb();
						}
					},
					function(err, res) {
						// Only change "lastUpdated" date if there are new episodes
						Show.find({
							imdb_id: imdb
						}, function(err, show) {
							if (err) return callback(err, null);
							if (show.episodes != thisEpisodes) {
								Show.update({
										imdb_id: imdb
									}, {
										$set: {
											episodes: thisEpisodes,
											last_updated: +new Date(),
											num_seasons: numSeasons
										}
									},
									function(err, show) {
										return callback(err, null);
									});
							} else {
								return callback(null, show);
							}
						});

					});
			} else {

				try {

					trakt.request('show', 'summary', {
						title: imdb,
						extended: "full"
					}, function(err, show) {
						if (!show) return callback(null, show);
						else {
							var seasons = show.seasons;
							async.each(seasons, function(season, cbs) {
								var episodes = season.episodes;
								async.each(episodes, function(episode, cbe) {
										var aired = episode.first_aired_iso;
										if (aired) {
											var year_aired = aired.substring(0, aired.indexOf("-"));
											var date_aired = aired.substring(aired.indexOf("-") + 1, aired.indexOf("T")).replace("-", "/");
											if (typeof(data[year_aired]) != 'undefined' && typeof(data[year_aired][date_aired]) != 'undefined') {
												thisEpisode = {
													tvdb_id: episode.tvdb_id,
													season: episode.season,
													episode: episode.episode,
													title: episode.title,
													overview: episode.overview,
													first_aired: episode.first_aired_utc,
													date_based: true,
													year: year_aired,
													day_aired: date_aired,
													watched: {
														watched: false
													},
													torrents: []
												};
												thisEpisode.torrents = data[year_aired][date_aired];
												thisEpisode.torrents[0] = data[year_aired][date_aired]["480p"] ? data[year_aired][date_aired]["480p"] : data[year_aired][date_aired]["720p"]; // Prevents breaking the app
												thisEpisodes.push(thisEpisode);
											}
										}
										return cbe();
									},
									function(err, res) {
										return cbs()
									})
							}, function(err, res) {
								// Only change "lastUpdated" date if there are new episodes
								Show.find({
									imdb_id: imdb
								}, function(err, show) {
									if (err) return callback(err, null);
									if (show.episodes != thisEpisodes) {
										Show.update({
												imdb_id: imdb
											}, {
												$set: {
													episodes: thisEpisodes,
													last_updated: +new Date(),
													num_seasons: numSeasons
												}
											},
											function(err, show) {
												return callback(err, null);
											});
									} else {
										return callback(null, show);
									}
								});

							});
						}
					});

				} catch (err) {
					console.error("Error:", err);
					return callback(err, null);
				}

			}

		});
	},


	refreshDatabase: function() {
		var allShows = [];
		var that = this;
		async.each(providers, function(provider, cb) {
			provider.getAllShows(function(err, shows) {
				if (err) return console.error(err);
				allShows.push(shows);
				cb();
			});
		}, function(error) {
			// 2 process?
			async.mapLimit(allShows[0], 2, helpers.extractTrakt, function(err, results) {
				console.log("Update complete");
				config.lastRefresh = new Date;
			});
		});
	},

	extractTrakt: function(show, callback) {
		var that = this;
		var slug = show.slug;
		try {
			console.log("Extracting " + show.show);
			Show.findOne({
				slug: slug
			}, function(err, doc) {

				if (err || !doc) {
					console.log("New Show");
					try {
						trakt.request('show', 'summary', {
							title: slug
						}, function(err, data) {
							if (!err && data) {


								// make sure trakt returned something valid
								if (!data.imdb_id) {
									return callback(null, show);
								}

								data.images.lowres = helpers.resizeImage(data.images.poster, 300)
								data.images.fanart = helpers.resizeImage(data.images.fanart, 940);

								// ok show exist
								var newShow = new Show({
									_id: data.imdb_id,
									imdb_id: data.imdb_id,
									tvdb_id: data.tvdb_id,
									title: data.title,
									year: data.year,
									images: data.images,
									slug: slug,
									synopsis: data.overview,
									runtime: data.runtime,
									rating: data.ratings,
									genres: data.genres,
									country: data.country,
									network: data.network,
									air_day: data.air_day,
									air_time: data.air_time,
									status: data.status,
									num_seasons: 0,
									last_updated: 0
								});

								newShow.save(function(err, newDocs) {
									show.imdb_id = data.imdb_id;
									helpers.extractShowInfo(show, function(err, show) {
										return callback(err, show);
									});
								});
							} else {
								return callback(null, show);
							}
						})
					} catch (err) {
						console.error("Error:", err)
						return callback(null, show);
					}
				} else {
					console.log("Existing Show: Checking TTL");
					// compare with current time
					var now = +new Date();
					if ((now - doc.last_updated) > TTL) {
						console.log("TTL expired, updating info");
						show.imdb_id = doc.imdb_id;
						//TODO: Change this to just get new rating or something
						try {
							trakt.request('show', 'summary', {
								title: slug
							}, function(err, data) {
								if (!err && data) {
									Show.update({
											_id: doc._id
										}, {
											$set: {
												rating: data.ratings,
												status: data.status
											}
										},
										function(err, doc1) {
											helpers.extractShowInfo(show, function(err, show) {
												return callback(err, show);
											});
										});
								}
							});
						} catch (err) {
							console.error("Error:", err)
							return callback(err, null);
						}
					} else {
						return callback(null, show);
					}
				}
			});

		} catch (err) {
			console.error("Error:", err)
			return callback(err, null);
		}

	},


}

module.exports = helpers;

// trakt error catcher
trakt.on('error', function(err) {
	console.log(err);
});