/
info.js
209 lines (173 loc) · 6.24 KB
/
info.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
const axios = require('axios')
const cheerio = require('cheerio')
const match = require('match-sorter').default
const SEARCH_URI = 'https://myanimelist.net/search/prefix.json'
const getFromBorder = ($, t) => {
return $(`span:contains("${t}")`).parent().text().trim().split(' ').slice(1).join(' ').split('\n')[0].trim()
}
const getPictureUrl = (url) => {
const sizeRegex = /\/r\/\d*x\d*/
const parts = url.split('.')
const completeUrl = parts.slice(0, -1).join('.').replace(sizeRegex, '') + '.jpg'
return completeUrl
}
const parseCharacterOrStaff = (tr, isStaff = false) => {
const getPicture = (nbChild) => {
const src = tr.find(`td:nth-child(${nbChild})`).find('img').attr('data-srcset')
if (src && src.includes('1x') && src.includes('2x')) {
return getPictureUrl(src.split('1x, ')[1].replace(' 2x', ''))
} else {
// This most likely means that the seiyuu is not here.
return undefined
}
}
return JSON.parse(JSON.stringify({
link: tr.find('td:nth-child(1)').find('a').attr('href'),
picture: getPicture(1),
name: tr.find('td:nth-child(2)').text().trim().split('\n')[0],
role: tr.find('td:nth-child(2)').text().trim().split('\n')[2].trim(),
seiyuu: !isStaff ? {
link: tr.find('td:nth-child(3)').find('a').attr('href'),
picture: getPicture(3),
name: tr.find('td:nth-child(3)').find('a').text().trim()
} : undefined
}))
}
const getCharactersAndStaff = ($) => {
const results = {
characters: [],
staff: []
}
// Characters
const leftC = $('div.detail-characters-list').first().find('div.left-column')
const rightC = $('div.detail-characters-list').first().find('div.left-right')
const nbLeftC = leftC.children('table').length
const nbRightC = rightC.children('table').length
// Staff
const leftS = $('div.detail-characters-list').last().find('div.left-column')
const rightS = $('div.detail-characters-list').last().find('div.left-right')
const nbLeftS = leftS.children('table').length
const nbRightS = rightS.children('table').length
// Characters
for (let i = 1; i <= nbLeftC; ++i) {
results.characters.push(parseCharacterOrStaff(leftC.find(`table:nth-child(${i}) > tbody > tr`)))
}
for (let i = 1; i <= nbRightC; ++i) {
results.characters.push(parseCharacterOrStaff(rightC.find(`table:nth-child(${i}) > tbody > tr`)))
}
// Staff
for (let i = 1; i <= nbLeftS; ++i) {
results.staff.push(parseCharacterOrStaff(leftS.find(`table:nth-child(${i}) > tbody > tr`), true))
}
for (let i = 1; i <= nbRightS; ++i) {
results.staff.push(parseCharacterOrStaff(rightS.find(`table:nth-child(${i}) > tbody > tr`), true))
}
return results
}
const parsePage = (data) => {
const $ = cheerio.load(data)
const result = {}
result.title = $('span[itemprop="name"]').first().text()
result.synopsis = $('.js-scrollfix-bottom-rel span[itemprop="description"]').text()
result.picture = $('img.ac').attr('src')
const staffAndCharacters = getCharactersAndStaff($)
result.characters = staffAndCharacters.characters
result.staff = staffAndCharacters.staff
result.trailer = $('a.iframe.js-fancybox-video.video-unit.promotion').attr('href')
// Parsing left border.
result.englishTitle = getFromBorder($, 'English:')
result.japaneseTitle = getFromBorder($, 'Japanese:')
result.synonyms = getFromBorder($, 'Synonyms:')
result.type = getFromBorder($, 'Type:')
result.episodes = getFromBorder($, 'Episodes:')
result.status = getFromBorder($, 'Status:')
result.aired = getFromBorder($, 'Aired:')
result.premiered = getFromBorder($, 'Premiered:')
result.broadcast = getFromBorder($, 'Broadcast:')
result.producers = getFromBorder($, 'Producers:').split(', ')
result.studios = getFromBorder($, 'Studios:').split(', ')
result.source = getFromBorder($, 'Source:')
result.genres = getFromBorder($, 'Genres:').split(', ')
result.duration = getFromBorder($, 'Duration:')
result.rating = getFromBorder($, 'Rating:')
result.score = getFromBorder($, 'Score:').split(' ')[0].slice(0, -1)
result.scoreStats = getFromBorder($, 'Score:').split(' ').slice(1).join(' ').slice(1, -1)
result.ranked = getFromBorder($, 'Ranked:').slice(0, -1)
result.popularity = getFromBorder($, 'Popularity:')
result.members = getFromBorder($, 'Members:')
result.favorites = getFromBorder($, 'Favorites:')
return result
}
const getInfoFromURL = (url) => {
return new Promise((resolve, reject) => {
if (!url || typeof url !== 'string' || !url.toLocaleLowerCase().includes('myanimelist')) {
reject(new Error('[Mal-Scraper]: Invalid Url.'))
return
}
url = encodeURI(url)
axios.get(url)
.then(({ data }) => {
const res = parsePage(data)
res.id = +url.split(/\/+/)[3]
resolve(res)
})
.catch(/* istanbul ignore next */(err) => reject(err))
})
}
const getResultsFromSearch = (keyword) => {
return new Promise((resolve, reject) => {
if (!keyword) {
reject(new Error('[Mal-Scraper]: Received no keyword to search.'))
return
}
axios.get(SEARCH_URI, {
params: {
type: 'anime',
keyword
}
}).then(({ data }) => {
const items = []
data.categories.forEach((elem) => {
elem.items.forEach((item) => {
items.push(item)
})
})
resolve(items)
}).catch(/* istanbul ignore next */(err) => {
reject(err)
})
})
}
const getInfoFromName = (name, getBestMatch = true) => {
return new Promise((resolve, reject) => {
if (!name || typeof name !== 'string') {
reject(new Error('[Mal-Scraper]: Invalid name.'))
return
}
getResultsFromSearch(name)
.then(async (items) => {
if (!items.length) {
resolve(null)
return
}
try {
const bestMacth = getBestMatch
? match(items, name, { keys: ['name'] })[0]
: items[0]
const url = bestMacth ? bestMacth.url : items[0].url
const data = await getInfoFromURL(url)
data.url = url
resolve(data)
} catch (e) {
/* istanbul ignore next */
reject(e)
}
})
.catch(/* istanbul ignore next */(err) => reject(err))
})
}
module.exports = {
getInfoFromURL,
getResultsFromSearch,
getInfoFromName
}