-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathhtmlParser.js
More file actions
612 lines (583 loc) · 16.7 KB
/
Copy pathhtmlParser.js
File metadata and controls
612 lines (583 loc) · 16.7 KB
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
const cheerio = require('cheerio')
const scrapeIt = require('scrape-it')
const urlHelper = require('url')
const linez = require('linez')
const Ajv = require('ajv')
const JSON5 = require('json5')
// add search-result Schema
const ajv = new Ajv()
ajv.addSchema(require('../schemas/search-result.json'), 'search-result')
ajv.addSchema(require('../schemas/album-product.json'), 'album-product')
ajv.addSchema(require('../schemas/album-info.json'), 'album-info')
ajv.addSchema(require('../schemas/tag-result.json'), 'tag-result')
ajv.addSchema(require('../schemas/track-info.json'), 'track-info')
linez.configure({
newlines: ['\n', '\r\n', '\r']
})
const removeMultipleSpace = function (text) {
return text.replace(/\s{2,}/g, ' ')
}
const removeNewLine = function (text) {
text = linez(text).lines.map(function (line) {
return line.text.trim()
}).join(' ')
return removeMultipleSpace(text)
}
const assignProps = function (objFrom, objTo, propNames) {
propNames.forEach(function (propName) {
objTo[propName] = objFrom[propName]
})
return objTo
}
// parse search results
exports.parseSearchResults = function (html) {
const $ = cheerio.load(html)
const data = scrapeIt.scrapeHTML($, {
results: {
listItem: '.result-items li',
data: {
type: {
selector: '.itemtype',
convert: function (text) {
return text.toLowerCase()
}
},
name: { selector: '.heading' },
url: { selector: '.itemurl' },
imageUrl: { selector: '.art img', attr: 'src' },
tags: {
selector: '.tags',
convert: function (text) {
const tags = text.replace('tags:', '').replace(/\s/g, '')
return tags.length > 1 ? tags.split(',') : []
}
},
genre: {
selector: '.genre',
convert: function (text) {
return removeMultipleSpace(text.replace('genre:', ''))
}
},
subhead: {
selector: '.subhead',
convert: function (text) {
return removeMultipleSpace(text)
}
},
releaseDate: {
selector: '.released',
convert: function (text) {
return text.replace('released ', '')
}
},
numTracks: {
selector: '.length',
convert: function (text) {
const info = text.split(',')
if (info.length === 2) {
return parseInt(info[0].replace(' tracks', ''))
}
}
},
numMinutes: {
selector: '.length',
convert: function (text) {
const info = text.split(',')
if (info.length === 2) {
return parseInt(info[1].replace(' minutes', ''))
}
}
}
}
}
})
return data.results.reduce(function (results, result) {
// basic properties
let object = assignProps(result, {}, ['type', 'name', 'url', 'imageUrl', 'tags'])
// specific properties
switch (result.type) {
case 'artist':
// genre
object.genre = result.genre
// location
object.location = removeMultipleSpace(result.subhead).trim()
break
case 'album':
// album's specific properties
object = assignProps(result, object, ['releaseDate', 'numTracks', 'numMinutes'])
// artist
object.artist = result.subhead.replace('by ', '').trim()
break
case 'track':
// released date
object.releaseDate = result.releaseDate
// album & artist
if (result.subhead) {
const info = result.subhead.trim().split(' by ')
if (info.length > 0) {
object.album = removeNewLine(info[0]).replace('location', '').replace(/^from /, '')
info.shift()
object.artist = removeNewLine(info.join(' by '))
}
}
break
case 'fan':
// genre
object.genre = result.genre
break
}
// validate through JSON schema
if (ajv.validate('search-result', object)) {
results.push(object)
} else { // TODO add a flag to log only when debugging
console.error('Validation error on search result: ', ajv.errorsText(), object, ajv.errors)
}
return results
}, [])
}
exports.extractAlbumUrlsFromDataBlob = function (html) {
const $ = cheerio.load(html)
const data = scrapeIt.scrapeHTML($, {
data: {
selector: '#pagedata',
attr: 'data-blob'
}
})
const jsonRaw = JSON5.parse(data.data)
const albums = []
for (const collection of jsonRaw.hub.tabs[0].collections) {
for (const item of collection.items) {
const album = {
name: item.title,
artist: item.artist,
url: item.tralbum_url,
artist_url: item.band_url
}
albums.push(album)
}
}
return albums
}
// parse tag results
exports.parseTagResults = function (html) {
const data = { results: this.extractAlbumUrlsFromDataBlob(html) }
return data.results.reduce(function (results, result) {
const object = assignProps(result, {}, ['name', 'artist', 'url', 'artist_url'])
if (ajv.validate('tag-result', object)) {
results.push(object)
} else {
console.error('Validation error on tag result: ', ajv.errorsText(), object, ajv.errors)
}
return results
}, [])
}
// parse album urls
exports.parseAlbumUrls = function (html, artistUrl) {
const $ = cheerio.load(html)
const data = scrapeIt.scrapeHTML($, {
albumLinks: {
listItem: 'a',
data: {
url: {
attr: 'href',
convert: function (href) {
if (/^\/(track|album)\/(.+)$/.exec(href)) {
return new urlHelper.URL(href, artistUrl).toString()
}
}
}
}
}
})
return data.albumLinks.reduce(function (albumUrls, albumLink) {
const url = albumLink.url
if (url) {
if (albumUrls.indexOf(url) === -1) {
albumUrls.push(url)
}
}
return albumUrls
}, [])
}
exports.parseArtistUrls = function (html, labelUrl) {
const $ = cheerio.load(html)
const data = scrapeIt.scrapeHTML($, {
artistLinks: {
listItem: 'a',
data: {
url: {
attr: 'href',
convert: function (href) {
if (/tab=artists*$/.exec(href)) {
return new urlHelper.URL(href, labelUrl).toString()
}
}
}
}
}
})
return data.artistLinks.reduce(function (artistUrls, artistLink) {
const url = artistLink.url
if (url) {
if (artistUrls.indexOf(url) === -1) {
artistUrls.push(url)
}
}
return artistUrls
}, [])
}
exports.extractJavascriptObjectVariable = function (html, variableName) {
const regex = new RegExp('var ' + variableName + '\\s*=\\s*(\\{[\\s\\S]*?\\})\\s*;')
const matches = html.match(regex)
if (matches && matches.length === 2) {
return matches[1]
}
}
// parse album info
exports.parseAlbumInfo = function (html, albumUrl) {
const $ = cheerio.load(html)
const data = scrapeIt.scrapeHTML($, {
album: {
selector: 'body',
data: {
artist: { selector: '#name-section span' },
title: { selector: '#name-section .trackTitle' },
imageUrl: {
selector: '#tralbumArt img',
attr: 'src',
convert: function (src) {
if (src) {
return src.replace(/_\d{1,3}\./, '_2.') // use small version
}
}
},
tags: {
listItem: '.tag',
data: {
name: {
convert: function (tag) {
return tag
}
}
}
},
tracks: {
listItem: 'table#track_table tr.track_row_view',
data: {
name: {
selector: 'span.track-title'
},
url: {
selector: '.info_link a',
attr: 'href',
convert: function (href) {
if (!href) return null
return new urlHelper.URL(href, albumUrl).toString()
}
},
duration: {
selector: '.time',
convert: function (duration) {
if (!duration) return null
return duration
}
}
}
},
nonPlayableTracks: {
listItem: 'table#track_table tr.track_row_view',
data: {
name: {
selector: '.title>span:not(.time)'
}
}
}
}
}
})
for (const nonPlayableTrack of data.album.nonPlayableTracks) {
data.album.tracks.push(nonPlayableTrack)
};
const object = assignProps(data.album, {}, ['tags', 'artist', 'title', 'imageUrl', 'tracks'])
// Remove undefined/null properties.
// remove non-playable tracks that would have been caught in "tracks" (in case of preview albums)
object.tracks = object.tracks.filter(x => x.name !== '')
for (let i = 0; i < object.tracks.length; i++) {
// Remove tracks properties.
for (const key in object.tracks[i]) {
if (Object.prototype.hasOwnProperty.call(object.tracks[i], key)) {
if (!object.tracks[i][key]) { delete object.tracks[i][key] }
}
}
}
// Parse raw.
const scriptWithRaw = $('script[data-tralbum]')
if (scriptWithRaw.length > 0) {
object.raw = scriptWithRaw.data('tralbum')
} else {
let raw = this.extractJavascriptObjectVariable(html, 'TralbumData')
// The only javascript in the variable is the concatenation of the base url
// with the current album path. We nned to do it yourself.
// Ex:
// url: "http://musique.coeurdepirate.com" + "/album/blonde",
raw = raw ? raw.replace('" + "', '') : ''
try {
object.raw = JSON5.parse(raw)
} catch (error) {
console.error(error)
}
}
// Parse pageData.
const scriptWithPageData = $('script[type="application/ld+json"]')
if (scriptWithPageData.length > 0) {
object.pageData = JSON5.parse(scriptWithPageData.text())
}
object.url = albumUrl
// validate through JSON schema
if (ajv.validate('album-info', object)) {
return object
} else { // TODO add a flag to log only when debugging
console.error('Validation error on album info: ', ajv.errorsText(), object)
return null
}
}
exports.parseTrackInfo = function (html, trackUrl) {
const $ = cheerio.load(html)
const object = {}
const scriptWithRaw = $('script[data-tralbum]')
// console.log(scriptWithRaw)
if (scriptWithRaw.length > 0) {
object.raw = scriptWithRaw.data('tralbum')
}
object.title = object.raw.trackinfo[0].title
object.url = trackUrl
object.trackId = object.raw.trackinfo[0].track_id
if (ajv.validate('track-info', object)) {
return object
} else {
console.error('Validation error on track info: ', ajv.errorsText(), object)
}
}
exports.parseArtistInfo = function (html, artistUrl) {
const $ = cheerio.load(html)
const data = scrapeIt.scrapeHTML($, {
name: '#band-name-location .title',
location: '#band-name-location .location',
coverImage: {
selector: '.bio-pic a',
attr: 'href'
},
bannerImage: {
selector: '.desktop-header a img',
attr: 'src'
},
description: 'p#bio-text',
albums: {
listItem: '.music-grid-item',
data: {
url: {
selector: 'a',
attr: 'href',
convert: href => artistUrl + href
},
coverImageSrc: {
selector: 'img',
attr: 'src'
},
coverImageOriginal: {
selector: 'img',
attr: 'data-original'
},
title: '.title'
}
},
discographyAlbums: {
listItem: '#discography ul li',
data: {
url: {
selector: 'a',
attr: 'href',
convert: href => artistUrl + href
},
coverImage: {
selector: 'img',
attr: 'src'
},
title: '.trackTitle a'
}
},
shows: {
listItem: '#showography ul li',
data: {
date: '.showDate',
venue: '.showVenue a',
venueUrl: {
selector: '.showVenue a',
attr: 'href'
},
location: '.showLoc'
}
},
bandLinks: {
listItem: '#band-links li',
data: {
name: 'a',
url: {
selector: 'a',
attr: 'href'
}
}
}
})
const mapAlbums = album => ({
url: album.url,
title: album.title,
coverImage: album.coverImageOriginal || album.coverImageSrc
})
const albums = data.albums.map(mapAlbums)
const mergedAlbums = [...new Set([...albums, ...data.discographyAlbums])]
// Parse raw.
const scriptWithRaw = $('script[data-tralbum]')
if (scriptWithRaw.length > 0) {
data.raw = scriptWithRaw.data('band')
} else {
let raw = this.extractJavascriptObjectVariable(html, 'BandData')
// The only javascript in the variable is the concatenation of the base url
// with the current album path. We nned to do it yourself.
// Ex:
// url: "http://musique.coeurdepirate.com" + "/album/blonde",
raw = raw ? raw.replace('" + "', '') : ''
try {
data.raw = JSON5.parse(raw)
} catch (error) {
console.error(error)
}
}
return {
name: data.name,
location: data.location,
description: data.description,
coverImage: data.coverImage,
bannerImage: data.bannerImage,
albums: mergedAlbums,
shows: data.shows,
bandLinks: data.bandLinks,
raw: data.raw
}
}
// parse album products
exports.parseAlbumProducts = function (html, albumUrl) {
const albumInfo = this.parseAlbumInfo(html, albumUrl)
const $ = cheerio.load(html)
const data = scrapeIt.scrapeHTML($, {
products: {
listItem: '.buyItem',
data: {
imageUrls: {
listItem: '.popupImageGallery img',
data: {
url: { attr: 'src' }
}
},
name: {
selector: '.buyItemPackageTitle',
convert: removeNewLine
},
nameFallback: { // fallback
selector: '.hd.lowHeadroom',
convert: removeNewLine
},
format: {
selector: '.buyItemPackageTitle'
},
formatFallback: { // fallback
selector: '.merchtype'
},
priceInCents: {
selector: '.ft span.base-text-color',
convert: function (text) {
const matches = text.match(/(\d+)([.,]?)(\d{0,2})/)
if (matches) {
return parseInt(matches[1] + (matches[3] || '00'))
} else {
return null
}
}
},
// currency
currency: {
selector: '.ft span.secondaryText',
eq: 0
},
offerMore: {
selector: '.ft span.secondaryText',
eq: 1,
convert: function (text) {
return text.toLowerCase() === 'or more'
}
},
soldOut: {
selector: '.notable',
convert: function (text) {
return text.toLowerCase() === 'sold out'
}
},
nameYourPrice: {
selector: '.ft span.secondaryText',
convert: function (text) {
return text.toLowerCase() === 'name your price'
}
},
description: {
selector: '.bd',
convert: function (text) {
return removeNewLine(text.trim())
}
}
}
}
})
return data.products.reduce(function (products, product) {
// basic properties
const object = assignProps(product, {}, ['description', 'soldOut', 'nameYourPrice', 'offerMore', 'nameYourPrice'])
// url
object.url = albumUrl
// format
object.format = product.format || product.formatFallback || 'Other'
// name
if (object.format.match(/digital\s(track|album)/i)) {
// digital have a different name
object.name = albumInfo.title
} else {
object.name = product.name || product.nameFallback
}
// imageUrls
if (product.imageUrls.length === 0) {
object.imageUrls = [albumInfo.imageUrl]
} else {
object.imageUrls = product.imageUrls.map(function (imageUrl) {
return imageUrl.url
})
}
// price
if (product.soldOut) {
object.priceInCents = null
object.currency = null
} else if (product.nameYourPrice) {
object.priceInCents = 0
object.currency = null
} else {
object.priceInCents = product.priceInCents
object.currency = product.currency
}
// artist
object.artist = albumInfo.artist
// validate through JSON schema
if (ajv.validate('album-product', object)) {
products.push(object)
} else { // TODO add a flag to log only when debugging
console.error('Error: ', ajv.errorsText(), object, JSON.stringify(ajv.errors))
}
return products
}, [])
}