forked from booblyboo/stremio-dramavery-local
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
339 lines (304 loc) · 10.7 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
const pUrl = require('url')
const { config, proxy, persist } = require('internal')
const needle = require('needle')
const cheerio = require('cheerio')
const async = require('async')
const { scrape } = require('./lib/scraper')
const defaults = {
name: 'Drama Very',
prefix: 'dramavery_',
origin: '',
endpoint: 'https://asianrun.com',
icon: 'https://www.viewasian.tv/themes/ViewAsian/images/logo.png',
categories: []
}
let endpoint = defaults.endpoint
const episodes = {}
const videoUrls = {}
const headers = {
'accept': 'application/json, text/plain, */*',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'referer': endpoint,
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
function setEndpoint(str) {
if (str) {
let host = str
if (host.endsWith('/index.php'))
host = host.replace('/index.php', '/')
if (!host.endsWith('/'))
host += '/'
endpoint = host
const origin = endpoint.replace(pUrl.parse(endpoint).path, '')
headers['origin'] = origin.slice(0, -1)
headers['referer'] = endpoint
}
return true
}
setEndpoint(defaults.endpoint)
function retrieveManifest() {
function manifest() {
return {
id: 'org.' + defaults.name.toLowerCase().replace(/[^a-z]+/g,''),
version: '1.0.0',
name: defaults.name,
description: 'Free Korean, Chinese, HK, Thailand movies and series.',
resources: ['stream', 'meta', 'catalog', 'subtitles'],
types: ['series', 'asian'],
idPrefixes: [defaults.prefix],
icon: defaults.icon,
catalogs: [
{
id: defaults.prefix + 'catalog',
type: 'asian',
name: defaults.name,
genres: ['movie', 'drama', 'kshow', 'korean', 'chinese', 'hk drama', 'thailand'],
extra: [{ name: 'genres' }, { name: 'skip' }, { name: 'search' }]
}
]
}
}
return new Promise((resolve, reject) => {
resolve(manifest())
})
}
const subtitles = []
const dbs = {}
let metas = {}
async function retrieveRouter() {
const manifest = await retrieveManifest()
const { addonBuilder, getInterface, getRouter } = require('stremio-addon-sdk')
const builder = new addonBuilder(manifest)
builder.defineCatalogHandler(args => {
return new Promise(async (resolve, reject) => {
const extra = args.extra || {}
if (extra.search) {
const sHeaders = JSON.parse(JSON.stringify(headers))
sHeaders['x-requested-with'] = 'XMLHttpRequest',
sHeaders['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
needle.post(defaults.endpoint + '/ajax/film/search/', { query: extra.search }, { headers: sHeaders }, (err, resp, body) => {
if (!err && (((body || {}).suggestions || []).length)) {
const results = []
body.suggestions.forEach(el => {
const poster = el.image
const id = el.image.split('/')[4]
metas[id] = {
id: defaults.prefix + id,
name: el.vietnam || el.english + (el.year ? el.year.replace(' ', ' ') : ''),
poster,
background: poster.replace('/poster/', '/banner/').replace('?type=small', '?type=banner'),
type: 'series',
href: el.link
}
results.push(metas[id])
})
resolve({ metas: results })
} else {
reject(defaults.name + ' - No results or unexpected response from search api')
}
})
} else {
const genre = extra.genre || 'drama'
const skip = parseInt(extra.skip || 0)
let page
if (skip)
page = (skip / 48) + 1
const tag = genre + (skip ? ':' + page : '')
if (!dbs[tag]) {
needle.get(defaults.endpoint + '/' + genre + '/' + (skip ? 'page-' +page + '/' : ''), { headers }, (err, resp, body) => {
if (!err && body) {
const $ = cheerio.load(body)
const results = []
$('.col-xlg-2 .item .inner').each((ij, el) => {
const poster = $(el).find('img').attr('src')
const id = poster.split('/')[4]
metas[id] = {
id: defaults.prefix + id,
name: $(el).attr('title'),
poster,
background: poster.replace('/poster/', '/banner/').replace('?type=small', '?type=banner'),
href: $(el).attr('href'),
type: 'series'
}
results.push(id)
})
if (results.length) {
dbs[tag] = results
resolve({ metas: results.map(id => { return metas[id] || {} }), cacheMaxAge: 86400 })
} else
reject(defaults.name + ' - Unexpected catalog response')
} else
reject(defaults.name + ' - Invalid catalog response')
})
} else {
resolve({ metas: dbs[tag].map(id => { return metas[id] || {} }), cacheMaxAge: 86400 })
}
}
})
})
builder.defineMetaHandler(args => {
return new Promise(async (resolve, reject) => {
let id = args.id.replace(defaults.prefix, '')
if (metas[id]) {
if ((metas[id].videos || []).length)
resolve({ meta: metas[id] })
else {
needle.get(metas[id].href + 'watch/', { headers }, (err, resp, body) => {
if (!err && body) {
const $ = cheerio.load(body)
const eps = []
let releasedTime = Date.now()
$('a.btn.btn-rounded').each((ij, el) => {
const epNum = $(el).text().trim()
if (!isNaN(epNum)) {
const ep = parseInt(epNum)
releasedTime -= 86400000
episodes[args.id + ':1:' + ep] = $(el).attr('href')
eps.push({
season: 1,
number: ep,
name: 'Episode ' + ep,
released: new Date(releasedTime).toISOString()
})
}
})
metas[id].videos = eps
resolve({ meta: metas[id] })
} else {
reject(defaults.name + ' - Could not get videos for meta')
}
})
}
} else
reject(defaults.name + ' - Could not get meta')
})
})
builder.defineStreamHandler(args => {
return new Promise(async (resolve, reject) => {
let videoHref = episodes[args.id]
if (videoHref) {
needle.get(videoHref, { headers }, (err, resp, body) => {
if (!err && body) {
const $ = cheerio.load(body)
let iframeHref = $('iframe#player-content').attr('src')
if (iframeHref.startsWith('//'))
iframeHref = 'https:' + iframeHref
if (iframeHref) {
function getKvid(cb) {
const phantom = require('phantom')
phantom.load({
clearMemory: true,
agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
headers: {
referer: videoHref,
origin: endpoint
}
}, null, null, function(phInstance, page) {
let kVid = false
let secondUrl = false
page.on('onResourceRequested', function(req, netReq) {
if (!kVid && (req.url.includes('/streaming.php') || req.url.includes('/embed.php') || req.url.includes('/ajax.php'))) {
kVid = req.url
} else if (!secondUrl && req.url.includes('player?url=')) {
// this case seems to have been removed
// secondUrl = req.url
}
})
page.open(iframeHref).then(async (status, body) => {
if (!kVid && secondUrl && secondUrl != iframeHref) {
iframeHref = secondUrl
phantom.close(phInstance, page, () => {
getKvid(cb)
})
} else if (!kVid) {
// i doubt this particular part ever worked
// but.. meh
page.evaluate(function() {
return $('iframe.iframe-video').attr('src')
}).then(inf => {
phantom.close(phInstance, page, () => {})
cb(inf || false)
}).catch(function(err) {
phantom.close(phInstance, page, () => {})
cb(false)
})
} else {
phantom.close(phInstance, page, () => {})
cb(kVid)
}
}, function(err) {
console.log(defaults.name + ' phantomjs error:')
console.log(err)
cb(false)
phantom.close(phInstance, page, () => {})
})
})
}
getKvid(nextIframe => {
if (nextIframe) {
const newHeaders = {
'referer': 'https://embed.watchasian.to/',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
'x-requested-with': 'XMLHttpRequest',
}
needle.get(nextIframe, { headers: newHeaders }, (err, resp, body) => {
if (!err && body) {
let respObj
try {
respObj = JSON.parse(body)
} catch(e) {}
if (((respObj || {}).source || []).length) {
const streams = []
let streamCount = 0
respObj.source.concat(respObj.source_bk || []).forEach(el => {
if (el.file && !streams.includes(el.file)) {
let label = el.label
if (label.toLowerCase().includes('hls p')) {
streamCount++
label = 'HLS'
if (streamCount > 1)
label += ' ' + streamCount
}
streams.push({
name: el.file.includes('redirector.googlevideo.com') ? 'Google Video' : 'Standard Server',
title: label,
url: proxy.addProxy(el.file, { headers: { referer: nextIframe, origin: 'https://k-vid.net' } })
})
}
})
if (streams.length)
resolve({ streams })
else
reject(defaults.name + ' - Did not find any videos for request')
} else
reject(defaults.name + ' - Could not parse json for streams')
} else
reject(defaults.name + ' - Unexpected second iframe response')
})
} else {
reject(defaults.name + ' - Could not get second iframe url')
}
})
} else
reject(defaults.name + ' - Unexpected video page response body')
} else {
reject(defaults.name + ' - Unexpected video response')
}
})
} else {
reject(defaults.name + ' - Unable to get details on episode for url: ' + args.id.replace(defaults.prefix, ''))
}
})
})
builder.defineSubtitlesHandler(args => {
return new Promise((resolve, reject) => {
resolve({ subtitles: subtitles[args.id] || [] })
})
})
const addonInterface = getInterface(builder)
return getRouter(addonInterface)
}
module.exports = retrieveRouter()