Created
October 1, 2012 07:40
-
-
Save pwmckenna/3810135 to your computer and use it in GitHub Desktop.
use Btapp.func and jQuery.Deferred objects to simplify tracker scraping
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
/** | |
Usage: | |
scrape(hash).then(function(infos) { | |
//we have the scrape info for our favorite trackers | |
}); | |
**/ | |
var btapp = new Btapp; | |
var scrape = (function() { | |
// First off get a function wrapper that we can call at any time | |
var func = btapp.func('tracker', 'scrape'); | |
// It's not really necessary to have all these, but udp is cheap | |
var trackers = [ | |
'udp://tracker.openbittorrent.com:80', | |
'udp://tracker.ccc.de:80', | |
'udp://tracker.istole.it:80', | |
'udp://tracker.publicbt.com:80' | |
]; | |
// I don't want to worry about destroying the trackers if I | |
// don't keep track if I've already asked about this hash | |
return _.memoize(function(hash) { | |
var scrapes = []; | |
// We'll make a request to each of our favorite trackers, | |
// then bundle them all the resulting deferred objects | |
// using jQuery.when | |
_.each(trackers, function(tracker) { | |
var scrape = new jQuery.Deferred; | |
func({ | |
hash: hash, | |
tracker: tracker, | |
callback: function(data) { | |
scrape.resolve(data); | |
} | |
}); | |
scrapes.push(scrape); | |
}, this); | |
// The best part is that memoize will just return the | |
// pre-resolved deferred object if we've already made | |
// a request for this hash | |
return jQuery.when.apply(this, scrapes); | |
}); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment