mafintosh / torrent-stream

The low level streaming torrent engine that peerflix uses
MIT License
1.94k stars 227 forks source link

Error destroying stream? #146

Open noelfelix opened 8 years ago

noelfelix commented 8 years ago

Not sure if this has anything to do with torrent-stream, but I've made a little test app that uses the engine to process torrent search results. I had a front end button that signals the first get route, which triggers disconnect and destroy the stream.

Two issues. One is I frequently end up with what seems like multiple streams (double or triple console.log statements), and when attempting to access the new route aka the next link in the filtered search results, I get an error: can't set headers after they are sent.

Any help would be appreciated, either way thank you for this, it has been great to work with and learn some node/express.

app.get('/dwqohf4389yfyhkhqf9o78yghfukqffh823f', function(req, res){
    eventEmitter.emit('disconnect');
    eventEmitter.on('destroyed', function(){
        res.send({disconnect: true});
    });
});

app.get('/wqd2rifh4gfglkg098prejj4g9jgjrelkgjq/:searchID/:videoID', function(req, res){
    console.log("Hit from: " + req.connection.remoteAddress);
    if(req.params.videoID === '0') {
        filteredResults = [];

        var buildList = function(filteredResults, currentPage){
            kickass({
                q: req.params.searchID,
                field: 'seeders',
                order: 'desc',
                page: currentPage
            }, function(err, response){
                response.list.sort(function(cur, next){
                    return (next.seeds + next.peers * .25) - (cur.seeds + cur.peers * .25);
                });

                if(response.total_results != "0"){
                    var i = 0;
                    var length = filteredResults.length;
                    var totalResults = response.total_results;

                    for(i; length < 20 && i < response.list.length && response.list[i].seeds > 9 && ((currentPage - 1) * 25 + i + 1) <= response.total_results; i++){
                        if(response.list[i].title && response.list[i].title.toLowerCase().indexOf("3d") == -1
                            && (~response.list[i].title.toLowerCase().indexOf("264") || ~response.list[i].title.toLowerCase().indexOf("mp4") || ~response.list[i].title.toLowerCase().indexOf("mkv"))){
                            filteredResults.push(response.list[i].hash);
                            length++;
                        }
                    }
                    if(i){
                        if(length < 20 && response.list[i-1].seeds > 9 && ((currentPage - 1) * 25 + i) <= response.total_results){
                            buildList(filteredResults, currentPage + 1);
                        } else {
                            eventEmitter.emit('listBuilt');
                        }
                    }
                }
            });
        }
        buildList(filteredResults, 1);
    } else {
        eventEmitter.emit('listBuilt');
    }

    var engineFire = function(){
        eventEmitter.on('disconnect', function(){
            if(engine){
                engine.remove(function(){
                    engine.destroy(function(){
                        res.end();
                        eventEmitter.emit('destroyed');
                    });
                });
            } else {
                eventEmitter.emit('destroyed')
            }
        });
        if(filteredResults.length > 0){
            console.log("here");
            var engine = torrentStream('magnet:?xt=urn:btih:' + filteredResults[parseInt(req.params.videoID)], {connections: 10000,
                                                                        uploads: 0,
                                                                        trackers: trackers});

            engine.on('ready', function() {
                var theFile = null;
                var fileSize = 0;
                engine.files.forEach(function(file) {
                    console.log(file.name + ': ' + file.length);
                    if(file.length > fileSize && file.length){
                        theFile = file;
                        fileSize = file.length;
                    }
                });
                console.log(theFile.name);
                if(theFile){
                    res.writeHead(200, {
                        "Content-Type": "video/mp4"
                    });
                    theFile.createReadStream().pipe(res);
                } else res.send("invalid file type");
            });
        } else res.send("<h1>TRY AGAIN</h1>");
    }
    eventEmitter.on('listBuilt', engineFire);
})