我正在研究一个个人项目,该项目基本上需要一个磁力链接,开始下载文件,然后在浏览器的torrent中呈现视频。我正在使用一个名为torrent-stream的npm模块来完成大多数操作。创建可读流并开始编写文件后,我想向客户端发送带有视频URL的套接字消息,以便客户端可以呈现html5视频元素并开始流式传输视频。
我遇到的问题是,一旦客户端渲染了视频元素并尝试找到源mp4,我会在视频文件上找不到404错误。关于此的任何建议将受到高度赞赏。 :)
控制器功能:
uploadVideo: function (req, res) {
var torrentStream = require('torrent-stream');
var mkdirp = require('mkdirp');
var rootPath = process.cwd();
var magnetLink = req.param('magnet_link');
var fs = require('fs');
var engine = torrentStream(magnetLink);
engine.on('ready', function() {
engine.files.forEach(function(file) {
var fileName = file.name;
var filePath = file.path;
console.log(fileName + ' - ' + filePath);
var stream = file.createReadStream();
mkdirp(rootPath + '/assets/videos/' + fileName, function (err) {
if (err) {
console.log(err);
} else {
var videoPath = rootPath + '/assets/videos/' + fileName + '/video.mp4';
var writer = fs.createWriteStream(videoPath);
var videoSent = false;
stream.on('data', function (data) {
writer.write(data);
if (!videoSent) {
fs.exists(videoPath, function(exists) {
if (exists) {
sails.sockets.broadcast(req.param('room'), 'video_ready', {videoPath: '/videos/' + fileName + '/video.mp4'});
videoSent = true;
}
});
}
});
// stream is readable stream to containing the file content
}
});
});
});
res.json({status: 'downloading'});
}
客户端JavaScript:
$(document).ready(function () {
io.socket.on('connect', function () {
console.log('mrah');
io.socket.get('/join', {roomName: 'cowboybebop'});
io.socket.on('message', function (data) {
console.log(data);
});
io.socket.on('video_ready', function (data) {
var video = $('<video width="320" height="240" controls>\
<source src="' + data.videoPath + '" type="video/mp4">\
Your browser does not support the video tag.\
</video>');
$('body').append(video);
});
});
$('form').submit(function (e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: '/upload-torrent',
method: 'POST',
data: formData
}).success(function (data) {
console.log(data);
}).error(function (err) {
console.log(err);
});
});
});
表格:
<form action="/upload-torrent" method="POST">
<input name="magnet_link" type="text" value="magnet:?xt=urn:btih:565DB305A27FFB321FCC7B064AFD7BD73AEDDA2B&dn=bbb_sunflower_1080p_60fps_normal.mp4&tr=udp%3a%2f%2ftracker.openbittorrent.com%3a80%2fannounce&tr=udp%3a%2f%2ftracker.publicbt.com%3a80%2fannounce&ws=http%3a%2f%2fdistribution.bbb3d.renderfarming.net%2fvideo%2fmp4%2fbbb_sunflower_1080p_60fps_normal.mp4"/>
<input type="hidden" name="room" value="cowboybebop">
<input type="submit" value="Link Torrent">