Created
November 23, 2018 17:54
-
-
Save ssysm/f5edbe06f2b7c127de42bb3a2e8bc9cc to your computer and use it in GitHub Desktop.
Niconico Live
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require('axios'); | |
const cherrio = require('cheerio'); | |
const WebSocket = require('ws'); | |
//请求生放链接 | |
axios.get('http://live2.nicovideo.jp/watch/lv316496097') | |
.then(res => res.data) | |
.then(data => { | |
//parse HTML | |
const $ = cherrio.load(data); | |
//获取页面配置 | |
const config = JSON.parse($('#embedded-data').attr('data-props')); | |
keepAlive({ | |
//Socket链接 | |
socketURL: config.site.relive.webSocketUrl, | |
//广播ID | |
broadcastId: config.program.broadcastId | |
}); | |
}) | |
//Promise错误 | |
.catch(e => { | |
console.error(e); | |
}); | |
//WebSocket部分 | |
function keepAlive({ | |
socketURL, | |
broadcastId | |
}) { | |
//打开Socket | |
const socket = new WebSocket(socketURL); | |
//打开Socket后发送请求流数据 | |
socket.on('open', () => { | |
console.log('Socket Opened'); | |
socket.send(JSON.stringify({ | |
type: 'watch', | |
body: { | |
command: 'getpermit', | |
requirement: { | |
broadcastId, | |
route: '', | |
stream: { | |
protocol: 'hls', | |
requireNewStream: true, | |
priorStreamQuality: 'high', | |
isLowLatency: true | |
}, | |
room: { | |
isCommentable: true, | |
protocol: 'webSocket' | |
} | |
} | |
} | |
})); | |
}); | |
//保证心跳包和时间回响被应答 | |
socket.on('message', (data) => { | |
data = JSON.parse(data); | |
//just for debug | |
//console.log(data); | |
if (data.type == "ping") { | |
//应答心跳包 | |
socket.send(JSON.stringify({ | |
type: 'pong', | |
body: {} | |
})); | |
console.log('Heartbeat packet sent'); | |
} else if (data.type) { | |
switch (data.body.command) { | |
//回响时间 | |
case 'servertime': | |
socket.send(JSON.stringify({ | |
type: 'watch', | |
body: { | |
command: 'watching', | |
params: [broadcastId, '-1', '0'] | |
} | |
})); | |
console.log('Time response answered'); | |
break; | |
//Console出m3u8播放列表 | |
case 'currentstream': | |
console.log('Got stream playlist at ' + data.body.currentStream.uri); | |
break; | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment