Permalink
Browse files

Rewrite and push

  • Loading branch information...
1 parent 456aad5 commit 36228a7f0016b4213b30d70478ec482fc5b896b4 flybyme committed Nov 5, 2012
Showing with 173 additions and 117 deletions.
  1. +119 −65 lib/transmission.js
  2. +11 −27 lib/utils.js
  3. +10 −14 package.json
  4. +33 −11 test/testquery.js
View
184 lib/transmission.js
@@ -6,109 +6,162 @@ var fs = require('fs');
var url = require('url');
var events = require('events');
-var keyGen = require('./utils').keyGen;
+var uuid = require('./utils').uuid;
-var Transmission = module.exports = function(port, host) {
+var Transmission = module.exports = function(options) {
events.EventEmitter.call(this);
this.url = '/transmission/rpc';
- this.host = host;
- this.port = port;
+ this.host = options.host || 'localhost';
+ this.port = options.port || 9091;
this.key = '';
- this.isPolling = false;
- this.conActive = false;
- this.timer;
- this.username = '';
- this.password = '';
+
+ if (options.username) {
+ this.authHeader = 'Basic ' + new Buffer(options.username + (options.password ? ':' + options.password : '')).toString('base64');
+ }
};
// So will act like an event emitter
util.inherits(Transmission, events.EventEmitter);
-Transmission.prototype.start = function() {
- if(!this.poll) {
- this.poll = true;
- this.update()
- }
-};
-Transmission.prototype.stop = function() {
- if(this.poll) {
- this.poll = false;
+function onResult(callback) {
+
+ return function(result) {
+ if (result.result === 'success') {
+ callback(null, result.arguments)
+ } else {
+ callback(new Error(result.result))
+ }
}
-};
-Transmission.prototype.addTorrent = function(path) {
+}
+
+Transmission.prototype.add = function(path, callback) {
this.callServer({
arguments : {
filename : path
},
method : this.methods.torrents.add,
- tag : keyGen()
- }, function(result) {
+ tag : uuid()
+ }, onResult(callback))
+}
+Transmission.prototype.remove = function(ids, del, callback) {
+ this.callServer({
+ arguments : {
+ ids : ids,
+ "delete-local-data" : !!del
+ },
+ method : this.methods.torrents.remove,
+ tag : uuid()
+ }, onResult(callback))
+}
+Transmission.prototype.get = function(ids, callback) {
+ var options = {
+ arguments : {
+ fields : this.methods.torrents.feilds,
+ ids : ids
+ },
+ ids : '',
+ method : 'torrent-get',
+ tag : uuid()
+ }
- })
+ if ( typeof ids == 'function') {
+ callback = ids
+ options.arguments.ids = ''
+ }
+
+ var self = this;
+ self.callServer(options, onResult(callback))
+}
+Transmission.prototype.stop = function(ids, callback) {
+ var self = this;
+ self.callServer({
+ arguments : {
+ ids : Array.isArray(ids) ? ids : [ids]
+ },
+ ids : '',
+ method : 'torrent-stop',
+ tag : uuid()
+ }, onResult(callback))
+}
+Transmission.prototype.start = function(ids, callback) {
+ var self = this;
+ self.callServer({
+ arguments : {
+ ids : ids
+ },
+ ids : '',
+ method : 'torrent-start',
+ tag : uuid()
+ }, onResult(callback))
+}
+Transmission.prototype.startNow = function(ids, callback) {
+ var self = this;
+ self.callServer({
+ arguments : {
+ ids : ids
+ },
+ ids : '',
+ method : 'torrent-start-now',
+ tag : uuid()
+ }, onResult(callback))
+}
+Transmission.prototype.update = function(callback) {
+ var self = this;
+ self.callServer({
+ arguments : {
+ fields : this.methods.torrents.feilds
+ },
+ ids : '',
+ method : 'torrent-get',
+ tag : uuid()
+ }, onResult(callback))
}
Transmission.prototype.callServer = function(query, callBack) {
var self = this;
- var authToken;
+
var options = {
- host: this.host,
- path: this.url,
- port: this.port,
- method: 'POST',
- headers: {
+ host : this.host,
+ path : this.url,
+ port : this.port,
+ method : 'POST',
+ headers : {
'Time' : new Date(),
'Host' : this.host + ':' + this.port,
'X-Requested-With' : 'Node',
'X-Transmission-Session-Id' : this.key
}
};
- if (this.username) {
- authToken = this.username + (this.password ? ':'+ this.password : '');
- options.headers['Authorization'] = 'Basic '+ new Buffer(authToken).toString('base64');
+ if (this.authHeader) {
+ options.headers['Authorization'] = this.authHeader;
}
- this.conActive = true;
-
- http.request(options, function(response) {
+ function onResponse(response) {
var page = [];
- response.setEncoding('utf8');
-
- response.on('data', function(chunk) {
+ function onData(chunk) {
page.push(chunk);
- });
+ }
- response.on('end', function() {
- if(response.statusCode == 409) {
+ function onEnd() {
+ if (response.statusCode == 409) {
self.key = response.headers['x-transmission-session-id'];
return self.callServer(query, callBack);
- }
- else if(response.statusCode == 200) {
+ } else if (response.statusCode == 200) {
callBack(JSON.parse(unescape(page.join(''))));
}
- if(self.poll) {
- setTimeout(function() {
- self.update()
- }, 35000)
- }
- });
- }).end(JSON.stringify(query), 'utf8');
+ }
+
+
+ response.setEncoding('utf8');
+ response.on('data', onData);
+ response.on('end', onEnd);
+ }
+
+
+ http.request(options, onResponse).end(JSON.stringify(query), 'utf8');
};
-Transmission.prototype.update = function() {
- var self = this;
- self.callServer({
- arguments : {
- fields : ['activityDate', 'addedDate', 'bandwidthPriority', 'comment', 'corruptEver', 'creator', 'dateCreated', 'desiredAvailable', 'doneDate', 'downloadDir', 'downloadedEver', 'downloadLimit', 'downloadLimited', 'error', 'errorString', 'eta', 'files', 'fileStats', 'hashString', 'haveUnchecked', 'haveValid', 'honorsSessionLimits', 'id', 'isFinished', 'isPrivate', 'leftUntilDone', 'magnetLink', 'manualAnnounceTime', 'maxConnectedPeers', 'metadataPercentComplete', 'name', 'peer-limit', 'peers', 'peersConnected', 'peersFrom', 'peersGettingFromUs', 'peersKnown', 'peersSendingToUs', 'percentDone', 'pieces', 'pieceCount', 'pieceSize', 'priorities', 'rateDownload', 'rateUpload', 'recheckProgress', 'seedIdleLimit', 'seedIdleMode', 'seedRatioLimit', 'seedRatioMode', 'sizeWhenDone', 'startDate', 'status', 'trackers', 'trackerStats ', 'totalSize', 'torrentFile', 'uploadedEver', 'uploadLimit', 'uploadLimited', 'uploadRatio', 'wanted', 'webseeds', 'webseedsSendingToUs']
- },
- ids : '',
- method : 'torrent-get',
- tag : keyGen()
- }, function(result) {
- self.torrents = result.arguments.torrents;
- self.emit('update', self.torrents)
- })
-}
Transmission.prototype.methods = {
torrents : {
stop : 'torrent-stop',
@@ -159,7 +212,8 @@ Transmission.prototype.methods = {
'ids' : true,
'move' : true
},
- get : 'torrent-get'
+ get : 'torrent-get',
+ feilds : ['activityDate', 'addedDate', 'bandwidthPriority', 'comment', 'corruptEver', 'creator', 'dateCreated', 'desiredAvailable', 'doneDate', 'downloadDir', 'downloadedEver', 'downloadLimit', 'downloadLimited', 'error', 'errorString', 'eta', 'files', 'fileStats', 'hashString', 'haveUnchecked', 'haveValid', 'honorsSessionLimits', 'id', 'isFinished', 'isPrivate', 'leftUntilDone', 'magnetLink', 'manualAnnounceTime', 'maxConnectedPeers', 'metadataPercentComplete', 'name', 'peer-limit', 'peers', 'peersConnected', 'peersFrom', 'peersGettingFromUs', 'peersKnown', 'peersSendingToUs', 'percentDone', 'pieces', 'pieceCount', 'pieceSize', 'priorities', 'rateDownload', 'rateUpload', 'recheckProgress', 'seedIdleLimit', 'seedIdleMode', 'seedRatioLimit', 'seedRatioMode', 'sizeWhenDone', 'startDate', 'status', 'trackers', 'trackerStats ', 'totalSize', 'torrentFile', 'uploadedEver', 'uploadLimit', 'uploadLimited', 'uploadRatio', 'wanted', 'webseeds', 'webseedsSendingToUs']
},
session : {
stats : 'session-stats',
View
38 lib/utils.js
@@ -1,28 +1,12 @@
-
-var ranKey = [];
-var genKey = function() {
- for(var l = (100 - ranKey.length); l >= 0; l--) {
- var chars = "0123456789abcdefghijklmnopqrstuvwxyz";
- var len = chars.length
- var key = [];
- key.push('a')
- for(var i = 9; i >= 0; i--) {
- var rnum = Math.floor(Math.random() * len);
- key.push(chars.substring(rnum, rnum + 1));
- }
- key = key.join('');
- if(ranKey.indexOf(key) != -0) {
- ranKey.push(key)
- }
-
- }
+/***
+ *
+ *
+ */
+var exports = module.exports = {};
+//
+var S4 = function() {
+ return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
-genKey()
-
-var keyGen = exports.keyGen = function() {
- if(ranKey.length <= 100) {
- genKey()
- }
- console.log(ranKey.length)
- return ranKey.shift()
-};
+var uuid = module.exports.uuid = function() {
+ return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
+}
View
24 package.json
@@ -1,16 +1,12 @@
{
- "author": "Tim <flybyme@wiyc.info>",
- "name": "transmission",
- "description": "API client for transmissionbt",
- "version": "0.0.1a",
- "repository": {
- "type": "git",
- "url": "git://github.com/FLYBYME/node-transmission.git"
- },
- "main": "lib/transmission",
- "engines": {
-
- },
- "dependencies": {},
- "devDependencies": {}
+ "author": "Tim <timprice@mangoraft.com>",
+ "name": "transmission",
+ "description": "API client for transmissionbt",
+ "version": "0.1.0",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/FLYBYME/node-transmission.git"
+ },
+ "main": "lib/transmission",
+ "engines": {}
}
View
44 test/testquery.js
@@ -1,14 +1,36 @@
-var bt = new (require('../lib/transmission.js'))(9091, 'localhost')
-console.log(bt)
+var bt = new (require('../lib/transmission.js'))({
+ //port : 9091,
+ //host : 'localhost',
+ //username : 'admin',
+ //password : 'password1'
+})
-// optional authorization options
-// bt.username = 'admin';
-// bt.password = 'password1';
+bt.add('http://cdimage.debian.org/debian-cd/6.0.6/i386/bt-cd/debian-6.0.6-i386-netinst.iso.torrent', function(err, result) {
+ if (err) {
+ throw err
+ }
+ console.log(result)
+ bt.stop('5db3a7a15a1391795a74b48c74df5d515a12c6f7', function(err) {
+ if (err) {
+ throw err
+ }
+ bt.start('5db3a7a15a1391795a74b48c74df5d515a12c6f7', function(err) {
+ if (err) {
+ throw err
+ }
+ bt.get('5db3a7a15a1391795a74b48c74df5d515a12c6f7', function(err, result) {
+ if (err) {
+ throw err
+ }
+ console.log(result)
-bt.on('update', function(torrents) {
- console.log(torrents.length)
- console.log(bt)
-})
-bt.start()
+ bt.remove('5db3a7a15a1391795a74b48c74df5d515a12c6f7', true, function(err) {
+ if (err) {
+ throw err
+ }
-bt.addTorrent('path.to.torrent')
+ })
+ })
+ })
+ })
+})

0 comments on commit 36228a7

Please sign in to comment.