magnetHandler.processUrl = function(uri, readyCb) { var self = this this.destroy(); console.log('clearing temp folder'); child = exec("rm -rf /mnt/pendrive/torrent-stream") console.log('fetching metadata'); this.engine = peerflix(uri, { connections: 15, dht: 10, port: 0, tmp: this.downloadFolder, buffer: (1.5 * 1024 * 1024).toString() }); this.engine.server.on('listening', function(){ if(self.engine) { console.log('metadata fetched, bufering'); playUrl = 'http://127.0.0.1:'+self.engine.server.address().port var interval = setInterval(function(i) { console.log(self.getProgress(), i); if (self.getProgress() > 1) { readyCb(playUrl, self.engine.server.index); clearInterval(interval) } }, 3000); } }); }
ipcMain.on("load-magnet", (e, infoHash) => { console.log("infoHash", infoHash); const engine = peerflix("magnet:?xt=urn:btih:" + infoHash, { connections: os.cpus().length > 1 ? 100 : 30, path: "./data", port: 3549 }); engine.on("ready", function() { e.sender.send("magnet-ready"); }); engine.server.on("listening", function () { if (!engine.server.address()) { return; } const port = engine.server.address().port; console.log(port); const href = "http://" + address() + ":" + port + "/"; console.log("Server is listening on " + href); }); engine.server.once("error", function (err) { engine.server.listen(0); console.log(err); }); });
readTorrent(torrent_url, function (err, torrent) { win.debug('Preloading torrent:', torrent); var tmpFilename = torrent.infoHash; tmpFilename = tmpFilename.replace(/([^a-zA-Z0-9-_])/g, '_'); // +'-'+ (new Date()*1); var tmpFile = path.join(App.settings.tmpLocation, tmpFilename); subtitles = torrent.subtitle; var version = require('semver').parse(App.settings.version); var torrentVersion = ''; torrentVersion += version.major; torrentVersion += version.minor; torrentVersion += version.patch; torrentVersion += version.prerelease.length ? version.prerelease[0] : 0; var torrentPeerId = '-PT'; torrentPeerId += torrentVersion; torrentPeerId += '-'; torrentPeerId += crypto.pseudoRandomBytes(6).toString('hex'); win.debug('Preloading movie to %s', tmpFile); preload_engine = peerflix(torrent_url, { connections: parseInt(Settings.connectionLimit, 10) || 100, // Max amount of peers to be connected to. dht: parseInt(Settings.dhtLimit, 10) || 50, port: 0, tmp: App.settings.tmpLocation, path: tmpFile, // we'll have a different file name for each stream also if it's same torrent in same session index: torrent.file_index, id: torrentPeerId }); });
StreamInstance.prototype.start = function() { this.started = true; this.engine = peerflix(this.magnet, { port: 8888, path: this.tmpPath } ); // Creates the tmp directory if it doesn't exist. this.engine.on('ready', function() { console.log('Take a seat! The video will now start streaming on localhost:8888.'); }); }
.spread((torrentInfo, port) => { let engine = peerflix(torrentInfo, { tracker: true, port, tmp: temp, buffer: (1.5 * 1024 * 1024).toString(), connections: 200 }); this.streams[engine.infoHash] = engine; engine['stream-port'] = port; return engine })
handlemagnet: function (filePath, torrent) { clearTimeout(safeMagetTID); var deferred = Q.defer(), error = false, engine = peerflix(torrent, { list: true }); // just list files, this won't start the torrent server // lets wait max a minute // because engine does not report any error on wrong magnet links /*jshint -W120 */ var currentTID = safeMagetTID = setTimeout(function () { engine.destroy(); handlers.handleError('TorrentCache.handlemagnet() error: timed out', torrent); }, MAGNET_RESOLVE_TIMEOUT); var resolve = function () { // maybe somehow new magnet was pasted in while loading this one if (currentTID !== safeMagetTID) { return; } if (error) { return handlers.handleError('TorrentCache.handlemagnet() error: ' + error, torrent); } deferred.resolve(filePath); }; var destroyEngine = function () { engine.destroy(); engine = null; }; engine.on('ready', function () { var resolvedTorrentPath = engine.path; clearTimeout(currentTID); if (resolvedTorrentPath) { // copy resolved path to cache so it will be awailable next time Common.copyFile(resolvedTorrentPath + '.torrent', filePath, function (err) { if (err) { error = err; } resolve(); destroyEngine(); }); } else { error = 'TorrentCache.handlemagnet() engine returned no file'; destroyEngine(); } }); return deferred.promise; },
readTorrent(torrent, function(err, torrent) { if (err) return res.send(400, { error: 'torrent link could not be parsed' }); if (engine) stop(); engine = peerflix(torrent, { connections: 100, path: createTempFilename(), buffer: (3 * 1024 * 1024).toString() }); engine.server.on('listening', function() { omx.play('http://127.0.0.1:' + engine.server.address().port + '/'); res.send(200); }); });
readTorrent(path, function(err, torrent) { if (err) return next(); var engine = peerflix(torrent, grabOpts(ctx.options, 'peerflix-')); engine.server.once('listening', function() { ctx.options.playlist[0] = { path: 'http://'+internalIp()+':'+engine.server.address().port, type: 'video/mp4', media: { metadata: { title: engine.server.index.name } } }; next(); }); });
AppDispatcher.register(action => { switch(action.type) { case AppConstants.FETCH_TORRENT: torrent = Object.assign({}, torrent, { isFetching: true }); TorrentStore.emitChange(); break; case AppConstants.RECEIVED_TORRENT: torrent = Object.assign({}, torrent, { error: false, isFetching: false, torrent: action.torrent, loadingStream: true, engine: peerflix(action.torrent.magnet || action.torrent.file , { tmp: os.tmpdir() }) }); TorrentStore.emitChange(); break; case AppConstants.ERROR_FETCH_TORRENT: torrent = Object.assign({}, torrent, { error: true, isFetching: false }); TorrentStore.emitChange(); break; case AppConstants.TORRENT_STREAM_READY: torrent = Object.assign({}, torrent, { loadingStream: false, streamUrl: action.url }); TorrentStore.emitChange(); break; case AppConstants.CLEAN_ALL: case AppConstants.CLEAN_TORRENT: if(torrent.engine) { torrent.engine.destroy(); } torrent = Object.assign({}, torrentDefaults); TorrentStore.emitChange(); break; default: // nothing } });
readTorrent(path, function(err, torrent) { if (err) { debug('error reading torrent: %o', err); return next(); } if (!ctx.options['peerflix-port']) ctx.options['peerflix-port'] = port; var engine = peerflix(torrent, grabOpts(ctx.options, 'peerflix-')); var ip = ctx.options.myip || internalIp.v4.sync(); engine.server.once('listening', function() { debug('started webserver on address %s using port %s', ip, engine.server.address().port); ctx.options.playlist[0] = { path: 'http://' + ip + ':' + engine.server.address().port, type: 'video/mp4', media: { metadata: { title: engine.server.index.name } } }; next(); }); });
var playTorrent = function(torrent, callback, statsCallback) { // Create a unique file to cache the video (with a microtimestamp) to prevent read conflicts var tmpFilename = typeof torrent === 'string' ? torrent.match(/magnet:\?xt=urn:[a-z0-9]+:([a-z0-9]{32})/i)[1] : torrent.infoHash; tmpFilename = tmpFilename.replace(/([^a-zA-Z0-9-_])/g, '_') +'-'+ (new Date()*1) +'.mp4'; var tmpFile = path.join(tmpDir, tmpFilename); // Set random port var port = randomPortNumber(49152, 65534); var engine = peerflix(torrent, { // Set the custom temp file path: tmpFile, buffer: (1.5 * 1024 * 1024).toString(), port: port, connections: 60, uploads: 5 }); var started = Date.now(); var wires = engine.swarm.wires; var swarm = engine.swarm; var loadedTimeout, fireStart = false, timeout = false; var active = function(wire) { return !wire.peerChoking; }; // Listen on port engine.server.on('listening', function() { if (loadedTimeout) clearTimeout(loadedTimeout); var href = getVideoUrl(engine.server.address().port); var loadingStats = function () { // Downloaded (size and percentage) var now = swarm.downloaded, total = engine.torrent.length, targetLoadedSize = minSizeLoaded > total ? total : minSizeLoaded, targetLoadedPercent = minPercentageLoaded * total / 100, targetLoaded = Math.max(targetLoadedPercent, targetLoadedSize), percentUntilStart = now / targetLoaded * 100, runtime = Math.floor((Date.now() - started) / 1000); // Check if loaded enough to start if (now > targetLoaded && !fireStart) { if (typeof callback === 'function') { callback(false, href); } fireStart = true; } // If downloading, send stats if (now < total && !timeout) { // If download choked (no peers), send timeout for restart if (runtime > 40 && !wires.length) { timeout = true; } // Send streaming stats callback if (typeof statsCallback == 'function') { statsCallback({ percent: percentUntilStart, started: fireStart, speed: bytes(swarm.downloadSpeed()), active: swarm.wires.filter(active).length, peers: wires.length, timeout: timeout }); } loadedTimeout = setTimeout(loadingStats, 500); } else { // If complete, send complete stat once statsCallback({ started: fireStart, percent: 100, complete: true }); } }; loadingStats(); }); engine.server.once('error', function() { if (loadedTimeout) clearTimeout(loadedTimeout); engine.server.listen(0); }); engine.server.on('connection', function(socket) { socket.setTimeout(36000000); }); engine.on('error', function() { if (loadedTimeout) clearTimeout(loadedTimeout); if (typeof callback === 'function') { callback(true, null); } }); // Destroy engine and remove video window.destroyVideo = function() { var defer = Q.defer(); if (loadedTimeout) { clearTimeout(loadedTimeout); } engine.remove(function() { engine.destroy(function() { defer.resolve(true); }); }); return defer.promise; }; };
var handleTorrent = function(torrent, stateModel) { var tmpFilename = torrent.info.infoHash; tmpFilename = tmpFilename.replace(/([^a-zA-Z0-9-_])/g, '_');// +'-'+ (new Date()*1); var tmpFile = path.join(App.settings.tmpLocation, tmpFilename); win.debug('Streaming movie to %s', tmpFile); // TODO-PORT: This happens on the server engine = peerflix(torrent.info, { connections: parseInt(Settings.connectionLimit, 10) || 100, // Max amount of peers to be connected to. dht: parseInt(Settings.dhtLimit, 10) || 50, port: parseInt(Settings.streamPort, 10) || 0, tmp: App.settings.tmpLocation, path: tmpFile, // we'll have a different file name for each stream also if it's same torrent in same session buffer: (1.5 * 1024 * 1024).toString(), // create a buffer on torrent-stream index: torrent.file_index }); engine.swarm.piecesGot = 0; engine.on('verify', function(index) { engine.swarm.piecesGot += 1; }); // TODO-PORT: Replace engine with some websocket type thing var streamInfo = new App.Model.StreamInfo({engine: engine}); // Fix for loading modal streamInfo.updateStats(engine); // TODO-PORT: wont need to poll, should listen for events on socket statsUpdater = setInterval(_.bind(streamInfo.updateStats, streamInfo, engine), 3000); stateModel.set('streamInfo', streamInfo); stateModel.set('state', 'connecting'); // TODO-PORT: Dont need to do this on the client watchState(stateModel); var checkReady = function() { if(stateModel.get('state') === 'ready') { streamInfo.set(torrent); // we need subtitle in the player streamInfo.set('subtitle', subtitles != null ? subtitles : torrent.subtitle); App.vent.trigger('stream:ready', streamInfo); stateModel.destroy(); } }; // TODO-PORT when we get http responce from server engine.server.on('listening', function(){ if(engine) { // TODO-PORT This wont really change much, use url from result json streamInfo.set('src', 'http://127.0.0.1:' + engine.server.address().port + '/'); streamInfo.set('type', 'video/mp4'); // TEST for custom NW //streamInfo.set('type', mime.lookup(engine.server.index.name)); // TODO-PORT need to hookup websocket instead here to listen for events. streamInfo stuff needs to move down here stateModel.on('change:state', checkReady); checkReady(); } }); // TODO-PORT servers job // not used anymore engine.on('ready', function() {}); engine.on('uninterested', function() { if (engine) { engine.swarm.pause(); } }); engine.on('interested', function() { if (engine) { engine.swarm.resume(); } }); };
var handleTorrent = function (torrent, stateModel) { var tmpFilename = torrent.info.infoHash; tmpFilename = tmpFilename.replace(/([^a-zA-Z0-9-_])/g, '_'); // +'-'+ (new Date()*1); var tmpFile = path.join(App.settings.tmpLocation, tmpFilename); subtitles = torrent.subtitle; var version = require('semver').parse(App.settings.version); var torrentVersion = ''; torrentVersion += version.major; torrentVersion += version.minor; torrentVersion += version.patch; torrentVersion += version.prerelease.length ? version.prerelease[0] : 0; var torrentPeerId = '-PT'; torrentPeerId += torrentVersion; torrentPeerId += '-'; torrentPeerId += crypto.pseudoRandomBytes(6).toString('hex'); win.debug('Streaming movie to %s', tmpFile); engine = peerflix(torrent.info, { connections: parseInt(Settings.connectionLimit, 10) || 100, // Max amount of peers to be connected to. dht: parseInt(Settings.dhtLimit, 10) || 50, port: parseInt(Settings.streamPort, 10) || 0, tmp: App.settings.tmpLocation, path: tmpFile, // we'll have a different file name for each stream also if it's same torrent in same session buffer: (1.5 * 1024 * 1024).toString(), // create a buffer on torrent-stream index: torrent.file_index, id: torrentPeerId }); engine.swarm.piecesGot = 0; engine.on('verify', function (index) { engine.swarm.piecesGot += 1; }); var streamInfo = new App.Model.StreamInfo({ engine: engine }); // Fix for loading modal streamInfo.updateStats(engine); streamInfo.set('torrent', torrent); streamInfo.set('title', torrent.title); streamInfo.set('player', torrent.device); statsUpdater = setInterval(_.bind(streamInfo.updateStats, streamInfo, engine), 1000); stateModel.set('streamInfo', streamInfo); stateModel.set('state', 'connecting'); watchState(stateModel); var checkReady = function () { if (stateModel.get('state') === 'ready') { if (stateModel.get('state') === 'ready' && stateModel.get('streamInfo').get('player') !== 'local') { stateModel.set('state', 'playingExternally'); } streamInfo.set(torrent); // we need subtitle in the player streamInfo.set('subtitle', subtitles != null ? subtitles : torrent.subtitle); App.vent.trigger('stream:ready', streamInfo); stateModel.destroy(); } }; App.vent.on('subtitle:downloaded', function (sub) { if (sub) { stateModel.get('streamInfo').set('subFile', sub); App.vent.trigger('subtitle:convert', { path: sub, language: torrent.defaultSubtitle }, function (err, res) { if (err) { win.error('error converting subtitles', err); stateModel.get('streamInfo').set('subFile', null); } else { App.Subtitles.Server.start(res); } }); } downloadedSubtitles = true; }); engine.server.on('listening', function () { if (engine) { streamInfo.set('src', 'http://127.0.0.1:' + engine.server.address().port + '/'); streamInfo.set('type', 'video/mp4'); // TEST for custom NW //streamInfo.set('type', mime.lookup(engine.server.index.name)); stateModel.on('change:state', checkReady); checkReady(); } }); // not used anymore engine.on('ready', function () {}); engine.on('uninterested', function () { if (engine) { engine.swarm.pause(); } }); engine.on('interested', function () { if (engine) { engine.swarm.resume(); } }); };
var playTorrent = window.playTorrent = function (torrent, subs, movieModel, callback, progressCallback) { videoStreamer ? $(document).trigger('videoExit') : null; // Create a unique file to cache the video (with a microtimestamp) to prevent read conflicts var tmpFolder = path.join(os.tmpDir(), 'Popcorn-Time') var tmpFilename = ( torrent.toLowerCase().split('/').pop().split('.torrent').shift() ).slice(0,100); tmpFilename = tmpFilename.replace(/([^a-zA-Z0-9-_])/g, '_') + '.mp4'; var tmpFile = path.join(tmpFolder, tmpFilename); var numCores = (os.cpus().length > 0) ? os.cpus().length : 1; var numConnections = 100; // Start Peerflix var peerflix = require('peerflix'); videoStreamer = peerflix(torrent, { // Set the custom temp file path: tmpFile, //port: 554, buffer: (1.5 * 1024 * 1024).toString(), connections: numConnections }, function (err, flix) { if (err) throw err; var started = Date.now(), loadedTimeout; flix.server.on('listening', function () { var href = 'http://127.0.0.1:' + flix.server.address().port + '/'; loadedTimeout ? clearTimeout(loadedTimeout) : null; var checkLoadingProgress = function () { var now = flix.downloaded, total = flix.selected.length, // There's a minimum size before we start playing the video. // Some movies need quite a few frames to play properly, or else the user gets another (shittier) loading screen on the video player. targetLoadedSize = MIN_SIZE_LOADED > total ? total : MIN_SIZE_LOADED, targetLoadedPercent = MIN_PERCENTAGE_LOADED * total / 100.0, targetLoaded = Math.max(targetLoadedPercent, targetLoadedSize), percent = now / targetLoaded * 100.0; if (now > targetLoaded) { if (typeof window.spawnVideoPlayer === 'function') { window.spawnVideoPlayer(href, subs, movieModel); } if (typeof callback === 'function') { callback(href, subs, movieModel); } } else { typeof progressCallback == 'function' ? progressCallback( percent, now, total) : null; loadedTimeout = setTimeout(checkLoadingProgress, 500); } }; checkLoadingProgress(); $(document).on('videoExit', function() { if (loadedTimeout) { clearTimeout(loadedTimeout); } // Keep the sidebar open $("body").addClass("sidebar-open").removeClass("loading"); // Stop processes flix.clearCache(); flix.destroy(); videoStreamer = null; // Unbind the event handler $(document).off('videoExit'); flix = null; }); }); }); };
temp.mkdir(function(err, path) { if (err) { alert("can t create temp dir, please report the problem!") } else { tmpFolder = path; } if (id) { torObj.id = id; videoStreamer = peerflix(torrent.info || torrent, { connections: 150, path: tmpFolder, index: parseInt(id), analysed: true }); } else { //player.cleanTracks(); videoStreamer = peerflix(torrent.info || torrent, { connections: 150, path: tmpFolder, gui: win.window, analysed: false }); } if(isMagnet) { videoStreamer.analysed = false; } else { videoStreamer.analysed = true; } streamInfo = new app.updateStats(videoStreamer); statsUpdater = setInterval(___.bind(app.updateStats, streamInfo, videoStreamer), 1000); stateModel.streamInfo = streamInfo; watchState(stateModel); var checkReady = function() { if (stateModel.state === 'ready') { // we need subtitle in the player streamInfo.title = torrent.title; stateModel.state = 'ready'; try { stateModel.destroy(); } catch (err) {} } }; videoStreamer.server.on('listening', function() { if (!videoStreamer || videoStreamer == null) { return; } torrentPlaying = true; streamInfo.src = 'http://' + ipaddress + ':' + videoStreamer.server.address().port + '/'; streamInfo.type = 'video/mp4'; var item = {}; try { item.name = videoStreamer.server.index.name; } catch (err) {} item.obj = videoStreamer; torrentsArr.push(item); console.log('peerlifx listening on http://' + ipaddress + ':' + videoStreamer.server.address().port + '/') checkReady(); }); // not used anymore videoStreamer.on('ready', function() { console.log("READYYYYYYYYYYYYYY", videoStreamer,streamInfo) // if(!videoStreamer.analysed && videoStreamer.torrent && videoStreamer.torrent.files){ // try { // analyseTorrent(videoStreamer.torrent.files); // return; // } catch(err) { // } // } }); videoStreamer.on('uninterested', function() { if (videoStreamer) { videoStreamer.swarm.pause(); } }); videoStreamer.on('interested', function() { if (videoStreamer) { videoStreamer.swarm.resume(); } }); });
function getTorrent(link) { try { initPlayer(); stopTorrent(); var videoStreamer = null; // Create a unique file to cache the video (with a microtimestamp) to prevent read conflicts var tmpFilename = ( link.toLowerCase().split('/').pop().split('.torrent').shift() ).slice(0,100); tmpFilename = tmpFilename.replace(/([^a-zA-Z0-9-_])/g, '_').replace(/ /g,'_') + '.mp4'; var tmpFile = path.join(tmpFolder, tmpFilename); var numCores = (os.cpus().length > 0) ? os.cpus().length : 1; var numConnections = 100; $('.mejs-overlay-button').hide(); $('#preloadTorrent').empty().remove(); $('.mejs-container').append('<div id="preloadTorrent" \ style="position: absolute;top: 45%;margin: 0 50%;color: white;font-size: 12px;text-align: center;z-index: 10000;width: 450px;right: 50%;left: -225px;"> \ <p><b id="preloadProgress">Connexion... merci de patienter</b></p> \ <progress value="5" min="0" max="100">0%</progress> \ </div>'); videoStreamer = popcornflix(link, { // Set the custom temp file //path: tmpFile, dht: true, verify: true, //port: 554, buffer: (1.5 * 1024 * 1024).toString(), connections: numConnections }, function (err, flix) { if (err) throw err; var started = Date.now(), refresh = true; loadedTimeout; flix.server.on('listening', function () { var href = 'http://'+ipaddress+':' + flix.server.address().port + '/'; loadedTimeout ? clearTimeout(loadedTimeout) : null; var item = {}; item.name = flix.selected.name; item.obj = flix; torrentsArr.push(item); var maxTry = 90; var tried = 0; var checkLoadingProgress = function () { try { var now = flix.downloaded, total = flix.selected.length, // There's a minimum size before we start playing the video. // Some movies need quite a few frames to play properly, or else the user gets another (shittier) loading screen on the video player. targetLoadedSize = MIN_SIZE_LOADED > total ? total : MIN_SIZE_LOADED, targetLoadedPercent = MIN_PERCENTAGE_LOADED * total / 100.0, targetLoaded = Math.max(targetLoadedPercent, targetLoadedSize), percent = (now / targetLoaded * 100.0).toFixed(2); var downloaded = bytesToSize(flix.downloaded, 2); var downloadRate = bytesToSize(flix.speed(), 2); if (now > targetLoaded) { clearTimeout(loadedTimeout); $('#preloadTorrent').remove(); var stream = {}; playFromHttp = true; stream.link = href; stream.next = ''; stream.title = flix.selected.name; startPlay(stream); } else { if (percent > 0) { $('#preloadProgress').empty().append('Chargement '+ percent +' % effectué à '+ downloadRate +'/s'); $('#preloadTorrent progress').attr('value',percent).text(percent); } else { tried += 1; if (tried === 90) { clearTimeout(loadedTimeout); $('#preloadProgress').empty().append('Connexion impossible, mauvais torrent...'); setTimeout(stopTorrent,5000); } else { $('#preloadProgress').empty().append('Connexion... merci de patienter (essai '+tried+'/'+maxTry+')'); } } if (refresh === true) { loadedTimeout = setTimeout(checkLoadingProgress, 1000); } } } catch(err) { console.log(err) } } checkLoadingProgress(); }); }); }catch(err) { console.log(err); } }
var handleTorrent = function(torrent, stateModel) { var tmpFilename = torrent.info.infoHash; tmpFilename = tmpFilename.replace(/([^a-zA-Z0-9-_])/g, '_') +'-'+ (new Date()*1); var tmpFile = path.join(App.settings.tmpLocation, tmpFilename); engine = peerflix(torrent.info, { connections: Settings.connectionLimit, // Max amount of peers to be connected to. dht: Settings.dhtLimit, path: tmpFile, // we'll have a different file name for each stream also if it's same torrent in same session buffer: (1.5 * 1024 * 1024).toString() // create a buffer on torrent-stream }); var streamInfo = new App.Model.StreamInfo({engine: engine}); statsUpdater = setInterval(_.bind(streamInfo.updateStats, streamInfo, engine), 1000); stateModel.set('streamInfo', streamInfo); watchState(stateModel); var checkReady = function() { if(stateModel.get('state') === 'ready') { // we need subtitle in the player streamInfo.set('subtitle', subtitles != null ? subtitles : torrent.subtitle); streamInfo.set('defaultSubtitle', torrent.defaultSubtitle); streamInfo.set('title', torrent.title); // add few info streamInfo.set('show_id', torrent.show_id); streamInfo.set('episode', torrent.episode); streamInfo.set('season', torrent.season); App.vent.trigger('stream:ready', streamInfo); stateModel.destroy(); } }; engine.server.on('listening', function(){ streamInfo.set('src', 'http://localhost:' + engine.server.address().port + '/'); streamInfo.set('type', 'video/mp4'); // TEST for custom NW //streamInfo.set('type', mime.lookup(engine.server.index.name)); stateModel.on('change:state', checkReady); checkReady(); }); // not used anymore engine.on('ready', function() {}); engine.on('uninterested', function() { if (engine) { engine.swarm.pause(); } }); engine.on('interested', function() { if (engine) { engine.swarm.resume(); } }); };
var playTorrent = function (infoHash) { var torrent; enginePort = 3549 //popcorn-time use 8888 so let's change it to 3549 which means [flix] in telephone numbers :P subPort = 3550 var randPort = Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152; //Choose port between 49152 and 65535 if (engine) { if (!engine.swarm._destroyed) { console.log("The engine is already starded!"); return; } } engine = peerflix( "magnet:?xt=urn:btih:" + infoHash, { connections: os.cpus().length > 1 ? 100 : 30, path: './data', port: enginePort }); var started = Date.now(); var wires = engine.swarm.wires; var swarm = engine.swarm; engine.on('ready', function() { console.log(engine.torrent); console.log(engine.tracker); subManager = subtitle(subPort); subManager.searchSubtitles(engine.torrent.name, function (success) { if(!success) { engine.skipSubtitles = true; } engine.langFound = success; }); NA.trackEvent('Player', 'Play torrent', engine.torrent.infoHash + " - " + engine.torrent.name, function (err, resp) {}); }); engine.server.on('listening', function () { if (!engine.server.address()) return; var port = engine.server.address().port; console.log(port); var href = 'http://' + address() + ':' + port + '/'; console.log('Server is listening on ' + href); }); var statsLog = function () { var runtime = Math.floor((Date.now() - started) / 1000); console.log(utilities.toBytes(swarm.downloaded) + " - " + runtime + " - " + swarm.queued); if (!swarm._destroyed) { setTimeout(statsLog, 500); } }; statsLog(); engine.server.once('error', function (err) { engine.server.listen(0); console.log(err); }); //engine.server.listen(enginePort); }
readTorrent(path, function(err, torrent) { if (err) { debug('error reading torrent: %o', err); return next(); } if (!ctx.options['peerflix-port']) ctx.options['peerflix-port'] = port; var engine = peerflix(torrent, grabOpts(ctx.options, 'peerflix-')); var ip = ctx.options.myip || internalIp(); var hotswaps = 0; var verified = 0; var invalid = 0; var wires = engine.swarm.wires; var swarm = engine.swarm; var active = function(wire) { debug("peerChoking"); return !wire.peerChoking; }; engine.on('verify', function() { debug('verify'); verified++; engine.swarm.piecesGot += 1; }); engine.on('invalid-piece', function() { debug('invalidpiece'); invalid++; }); var onready = function() { //mostrar algo ya que el motor ya inicio debug('We are ready'); }; if (engine.torrent) onready(); else engine.on('ready', onready); engine.on('hotswap', function() { debug('hotswap'); hotswaps++; }); engine.server.once('listening', function() { debug('started webserver on address %s using port %s', ip, engine.server.address().port); var filename = engine.server.index.name.split('/').pop().replace(/\{|\}/g, ''); var filelength = engine.server.index.length; debug(util.format("(%d bytes) %s", filelength, filename)); var updateStatus = function(){ var unchoked = engine.swarm.wires.filter(active); debug(util.format("Peers: %d/%d; Speed: %d KB/s; Downloaded: %d MB",unchoked.length, wires.length, (swarm.downloadSpeed()/1024).toFixed(2), (swarm.downloaded/1024/1024).toFixed(2))); }; interval = setInterval(updateStatus,250); ctx.options.playlist[0] = { path: 'http://' + ip + ':' + engine.server.address().port, type: 'video/mp4', media: { metadata: { title: engine.server.index.name } } }; next(); }); });