-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
403 lines (384 loc) · 10.3 KB
/
index.ts
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
import fetch from 'node-fetch'
import { parse } from 'node-html-parser'
import internal from 'stream'
import Timeout = NodeJS.Timeout
interface NiconicoAPIData {
media: {
delivery: {
movie: {
session: {
videos: string[]
audios: string[]
heartbeatLifetime: number
recipeId: string
priority: number
urls: {
isWellKnownPort: boolean
isSsl: boolean
[key: string]: any
}[]
token: string
signature: string
contentId: string
authTypes: {
http: string
}
contentKeyTimeout: number
serviceUserId: string
playerId: string
[key: string]: any
}
[key: string]: any
}
[key: string]: any
}
[key: string]: any
}
video: OriginalVideoInfo
owner: OwnerInfo
[key: string]: any
}
export interface OwnerInfo {
id: number
nickname: string
iconUrl: string
channel: string | null
live: {
id: string
title: string
url: string
begunAt: string
isVideoLive: boolean
videoLiveOnAirStartTime: string | null
thumbnailUrl: string | null
} | null
isVideoPublic: boolean
isMylistsPublic: boolean
videoLiveNotice: null
viewer: number | null
}
interface OriginalVideoInfo {
id: string
title: string
description: string
count: {
view: number
comment: number
mylist: number
like: number
}
duration: number
thumbnail: {
url: string
middleUrl: string
largeUrl: string
player: string
ogp: string
}
rating: {
isAdult: boolean
}
registerdAt: string
isPrivate: boolean
isDeleted: boolean
isNoBanner: boolean
isAuthenticationRequired: boolean
isEmbedPlayerAllowed: boolean
viewer: null
watchableUserTypeForPayment: string
commentableUserTypeForPayment: string
[key: string]: any
}
export interface VideoInfo extends OriginalVideoInfo {
owner: OwnerInfo
}
interface HeartBeatData {
session: {
content_type: string
content_src_id_sets: {
content_src_ids: {
src_id_to_mux: {
video_src_ids: string[]
audio_src_ids: string[]
}
}[]
}[]
timing_constraint: string
keep_method: {
heartbeat: {
lifetime: number
}
}
recipe_id: string
priority: number
protocol: {
name: string
parameters: {
http_parameters: {
parameters: {
http_output_download_parameters: {
use_well_known_port: 'yes' | 'no'
use_ssl: 'yes' | 'no'
transfer_preset: string
}
}
}
}
}
content_uri: string
session_operation_auth: {
session_operation_auth_by_signature: {
token: string
signature: string
}
}
content_id: string
content_auth: {
auth_type: string
content_key_timeout: number
service_id: string
service_user_id: string
}
client_info: {
player_id: string
}
}
}
interface NiconicoAPIResponceSession {
session: HeartBeatData['session'] & {
id: string
}
}
type DownloadQuality = 'high' | 'middle' | 'low'
const niconicoRegexp = RegExp(
// https://github.com/ytdl-org/youtube-dl/blob/a8035827177d6b59aca03bd717acb6a9bdd75ada/youtube_dl/extractor/niconico.py#L162
'https?://(?:www\\.|secure\\.|sp\\.)?nicovideo\\.jp/watch/(?<id>(?:[a-z]{2})?[0-9]+)'
)
const headers = {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin': 'https://www.nicovideo.jp',
Connection: 'keep-alive',
'Content-Type': 'application/json',
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36 Edg/89.0.774.45',
Accept: '*/*',
'Accept-Encoding': 'gzip, deflate, br',
Origin: 'https://www.nicovideo.jp',
'Sec-Fetch-Site': 'cross-site',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Dest': 'empty',
Referer: 'https://www.nicovideo.jp/',
'Accept-Language': 'ja,en;q=0.9,en-GB;q=0.8,en-US;q=0.7',
}
export function isValidURL(url: string): boolean {
return niconicoRegexp.test(url)
}
class NiconicoDL {
private videoURL: string
private data: NiconicoAPIData | undefined
private heartBeat: Timeout | undefined
private result: NiconicoAPIResponceSession | undefined
private heartBeatBeforeTime: number = 0
private readonly quality: DownloadQuality
constructor(url: string, quality: DownloadQuality = 'high') {
if (!isValidURL(url)) {
throw Error('Invalid url')
}
this.videoURL = url
this.quality = quality
}
async getVideoInfo(): Promise<VideoInfo> {
const videoSiteDom = parse(
await (await fetch(this.videoURL, { headers })).text()
)
const matchResult = videoSiteDom
.querySelectorAll('div')
.filter((a) => a.rawAttributes.id === 'js-initial-watch-data')
if (matchResult.length === 0) {
throw Error('Failed get video site html...')
}
const patterns = {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
''': "'",
'`': '`',
}
const fixedString = matchResult[0].rawAttributes['data-api-data'].replace(
/&(lt|gt|amp|quot|#x27|#x60);/g,
function (match: string): string {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return patterns[match]
}
)
this.data = JSON.parse(fixedString) as NiconicoAPIData
return Object.assign(this.data.video, {
owner: this.data.owner,
}) as VideoInfo
}
async prepareHeartBeat(): Promise<HeartBeatData> {
if (!this.data) {
await this.getVideoInfo()
}
const session = (this.data as NiconicoAPIData).media.delivery.movie.session
// 720p or 360p
let videoQualityNum = 0
// acc_64kbps or acc_192kbps
let audioQualityNum = 0
if (this.quality === 'low') {
// 360p_low
videoQualityNum = session.videos.length - 1
// acc_64kbps
audioQualityNum = session.audios.length - 1
} else {
session.videos.forEach((video, index) => {
if (
(video.includes('720') && this.quality === 'high') ||
(video.includes('480') && this.quality === 'middle')
) {
videoQualityNum = index
}
})
}
return {
session: {
content_type: 'movie',
content_src_id_sets: [
{
content_src_ids: [
{
src_id_to_mux: {
video_src_ids: [session.videos[videoQualityNum]],
audio_src_ids: [session.audios[audioQualityNum]],
},
},
],
},
],
timing_constraint: 'unlimited',
keep_method: {
heartbeat: {
lifetime: session.heartbeatLifetime,
},
},
recipe_id: session.recipeId,
priority: session.priority,
protocol: {
name: 'http',
parameters: {
http_parameters: {
parameters: {
http_output_download_parameters: {
use_well_known_port: session.urls[0].isWellKnownPort
? 'yes'
: 'no',
use_ssl: session.urls[0].isSsl ? 'yes' : 'no',
transfer_preset: '',
},
},
},
},
},
content_uri: '',
session_operation_auth: {
session_operation_auth_by_signature: {
token: session.token,
signature: session.signature,
},
},
content_id: session.contentId,
content_auth: {
auth_type: session.authTypes.http,
content_key_timeout: session.contentKeyTimeout,
service_id: 'nicovideo',
service_user_id: session.serviceUserId,
},
client_info: {
player_id: session.playerId,
},
},
}
}
async startHeartBeat(): Promise<void> {
const heartBeatData = await this.prepareHeartBeat()
this.result = (
JSON.parse(
await (
await fetch('https://api.dmc.nico/api/sessions?_format=json', {
method: 'POST',
headers,
body: JSON.stringify(heartBeatData),
})
).text()
) as { data: NiconicoAPIResponceSession }
).data
const session_id = this.result.session.id
this.heartBeatBeforeTime = Math.floor(new Date().getTime() / 1000)
// eslint-disable-next-line @typescript-eslint/no-misused-promises
this.heartBeat = setInterval(async () => {
const now = Math.floor(new Date().getTime() / 1000)
if (now > this.heartBeatBeforeTime + 30) {
const res = await fetch(
`https://api.dmc.nico/api/sessions/${session_id}?_format=json&_method=PUT`,
{
method: 'POST',
headers,
body: JSON.stringify(this.result),
}
)
if (res.status == 201 || res.status == 200) {
this.result = (
JSON.parse(await res.text()) as { data: NiconicoAPIResponceSession }
).data
} else {
throw Error
}
this.heartBeatBeforeTime = now
}
}, 1000)
}
async getDownloadLink(): Promise<string> {
if (!this.heartBeat) {
await this.startHeartBeat()
}
return (this.result as NiconicoAPIResponceSession).session.content_uri
}
async download(
newTypeStream: true,
autoStopHeartBeat?: boolean
): Promise<internal.Readable>
async download(
newTypeStream: false,
autoStopHeartBeat?: boolean
): Promise<NodeJS.ReadableStream>
async download(): Promise<NodeJS.ReadableStream>
async download(
newTypeStream: boolean = false,
autoStopHeartBeat: boolean = true
) {
const url = await this.getDownloadLink()
const mp4Headers = Object.assign(headers, { 'Content-Type': 'video/mp4' })
const res = await fetch(url, {
headers: mp4Headers,
})
let binary: internal.Readable | NodeJS.ReadableStream = res.body
if (newTypeStream) {
binary = new internal.Readable().wrap(binary)
}
if (autoStopHeartBeat) {
binary.on('finish', () => {
// automatically stop heartbeat
this.stop()
})
}
return binary
}
stop(): void {
if (this.heartBeat) {
clearInterval(this.heartBeat)
}
}
}
export default NiconicoDL