-
Notifications
You must be signed in to change notification settings - Fork 7
/
review.js
347 lines (289 loc) · 10.1 KB
/
review.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
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
var Search = require('./search')
, request = require('superagent')
, util = require('util')
, EventEmitter = require('events').EventEmitter
, q = require('q')
, cheerio = require('cheerio')
, jsdiff = require('diff')
, _ = require('lodash');
// global constants
var VERSION = require('./package').version;
var BASE_URL = 'http://pitchfork.com';
var INVALID_REVIEW_ERROR = new Error("Review cannot be found without a 'url' and 'name'!");
var PAGE_NOT_FOUND_ERROR = new Error("Page Not Found!")
function clean_year(yearText) {
var re = /(\d+)/;
var result = re.exec(yearText);
if (result) {
return result[0];
} else {
return '';
}
}
/**
* helper function that finds the best matching string
*
* @params {String}, { Array of {String} }
*
*/
function get_best_match(str, str_list){
// initialize variables
var bestMatchAmount = Infinity
, ties = []
, currentBestMatch;
str_list.forEach(function(item){
// takes last best match
var currentItemDiff = jsdiff.diffChars(str, item);
if ( currentItemDiff.length <= bestMatchAmount ) {
// if there's a match tie
if (currentItemDiff.length == bestMatchAmount) {
// save ties in array
ties.push(item);
// TODO: deal with ties more intelligently than 'last tie wins'
}
bestMatchAmount = currentItemDiff.length;
currentBestMatch = item;
}
})
return currentBestMatch;
}
/**
* A Review instance
* @constructor
* @params attributes {Object} - an object of attributes.
* (note: 'url' and 'name' are required )
*/
function Review(attributes){
if (!attributes || typeof attributes.url == "undefined" || typeof attributes.name == "undefined") {
throw INVALID_REVIEW_ERROR;
}
var self = this;
this.attributes = attributes;
this.url = attributes.url;
this.name = attributes.name.trim();
this.matched_artist = this.name.split(' - ')[0];
this.matched_album = this.name.split(' - ')[1];
this.attributes.artist = this.matched_artist.trim();
this.attributes.album = this.matched_album ? this.matched_album.trim() : "";
this.fullUrl = [BASE_URL, this.url].join("");
// fetches on initialization and saves to .promise
this.promise = this.fetch()
this.page = attributes.page || false;
}
/**
* Grabs the HTML of the review from Pitchfork
*
* @public
* @type {Promise}
*/
Review.prototype.fetch = function(){
var dfd = q.defer()
, self = this;
function pretty_print_editorial(rawHtml){
return rawHtml
.html()
.toString()
.replace(/\<\/p\>/,"\n\n")
.replace(/\<p\>/,"")
.replace(/\<br\>/, "\n")
.replace(/\<br\>\<br\>/, "\n");
}
/**
* Parses the HTML received after fetch and sets attributes
* of a single-album review.
*
*/
function parseHtml(opts){
if (opts) {
var multi = opts.multi || false;
}
// set multi-album attributes
if (multi && !self.page) {
var titles = [];
var queryTitle = self.search.query.album;
self.$('.review-meta h2').each(function(idx, el){
titles.push(el.children[0].data)
})
var bestTitleMatch = get_best_match(queryTitle, titles);
var indexOfMatch = titles.indexOf(bestTitleMatch);
// set attributes
self.attributes.title = bestTitleMatch.trim();
self.attributes.multi = true;
var label_year = self.$('.review-meta h3')
.eq(indexOfMatch)
.text()
.split(";");
self.attributes.label = self.$('.review-detail .label-list li')
.children[0]
.text();
self.attributes.year = label_year[1]
.trim();
self.attributes.score = parseFloat(
self.$('.review-meta')
.find('.score')
.eq(indexOfMatch)
.text());
self.attributes.cover = self.$('.review-meta')
.find('.artwork img')
.eq(indexOfMatch)
.attr('src');
self.attributes.author = self.$('.review-meta h4')
.eq(indexOfMatch)
.find('address')
.text();
self.attributes.date = self.$('.review-meta h4')
.eq(indexOfMatch)
.find('.pub-date')
.text();
} else if (multi && self.page) {
var titles = [];
self.$('.review-meta h2').each(function(idx, el){
titles.push(el.children[0].data)
})
// set attributes
self.attributes.titles = titles
self.attributes.multi = true;
self.attributes.labels = [];
self.attributes.years = [];
self.attributes.scores = [];
self.attributes.covers = [];
/**
*
* For consistency, multi-albums with generate the same
* attributes as single albums by setting the first album
* in the collection's values for their label, year, cover.
* The exception is 'score' which is a mathematical average
* of the entire collection's scores.
*
*/
titles.forEach(function(title, idx){
var label_year = self.$('.review-meta h3')
.eq(idx)
.text()
.split(";");
self.attributes.labels.push(
label_year[0]
.trim()
);
self.attributes.label = self.attributes.labels[0];
self.attributes.years.push(
label_year[1]
.trim()
);
self.attributes.year = self.attributes.years[0];
self.attributes.scores.push(
parseFloat(
self.$('.review-meta')
.find('.score')
.eq(idx)
.text()
)
);
// multi-album score is an average of all scores
self.attributes.score = (function(scores){
var sum = 0;
scores.forEach(function(score){
sum += score;
})
return (sum/scores.length)
})(self.attributes.scores)
self.attributes.covers.push(
self.$('.review-meta')
.find('.artwork img')
.eq(idx)
.attr('src')
);
self.attributes.cover = self.attributes.covers[0]
self.attributes.author = self.$('.review-meta h4')
.eq(idx)
.find('address')
.text();
self.attributes.date = self.$('.review-meta h4')
.eq(idx)
.find('.pub-date')
.text();
})
} else {
// set single-album attributes
self.attributes.title = self.fullTitle.trim();
var label = self.$('.single-album-tombstone__meta .single-album-tombstone__meta-labels li:nth-child(1)').text();
var yearText = self.$('.single-album-tombstone__meta .single-album-tombstone__meta-year').text();
self.attributes.label = label.trim();
self.attributes.year = clean_year(yearText);
self.attributes.score = parseFloat(self.$(".score").text().trim());
self.attributes.cover = self.$(".single-album-tombstone__art img").attr("src");
self.attributes.author = self.$(".authors-detail__item .authors-detail__display-name").text()
self.attributes.date = self.$(".pub-date").text();
}
// TODO: replace breaks
self.attributes.editorial = {
html: self.$(".review-detail__text").html(),
text: self.$(".review-detail__text").text(),
abstract: self.$(".review-detail__abstract").text().trim()
}
}
request.get(this.fullUrl)
.end(function(res){
self.html = res.text;
self.$ = cheerio.load(self.html);
// set attributes from html
self.fullTitle = self.$("title").text().trim();
// TODO parse other attributes;
if (self.fullTitle.search("Page Not Found") != -1) {
return dfd.reject(PAGE_NOT_FOUND_ERROR);
} else {
if (self.$('.review-multi').length != 0) {
parseHtml({multi: true});
} else {
parseHtml();
}
return dfd.resolve(self)
}
})
return dfd.promise;
}
Review.prototype.truncated = function(){
var to = {}
_.each(this.attributes, function(val, key){
if ( val.constructor === Object ) {
return to['text'] = val.text.slice(0, 300)+"...";
} else {
return to[key] = val;
}
})
return to;
}
Review.prototype.verbose = function(){
var vo = {}
var cache = []
var self = this;
for (key in self) {
if ( typeof self[key] === 'object' && self[key] !== null ) {
if ( cache.indexOf(self[key]) !== -1) {
return;
} else {
cache.push(self[key]);
return vo[key] = self[key];
}
}
}
cache = null;
return vo;
}
Review.prototype.text_pretty_print = function(){
var text = [];
text.push("TITLE: "+this.fullTitle)
text.push("ARTIST: "+this.attributes.artist)
text.push("ALBUM: "+this.attributes.title)
text.push("SCORE: "+this.attributes.score.toString())
text.push("YEAR: "+this.attributes.year)
text.push("LABEL: "+this.attributes.label)
text.push("AUTHOR: "+this.attributes.author)
text.push("DATE: "+this.attributes.date)
text.push(this.attributes.editorial.text.replace("\n","\n\n"))
return text.join("\n\n\n")
}
// Review.prototype.toString = function(){
// return this.attributes;
// }
module.exports = Review;