expose `setMetadata` method

This commit is contained in:
Feross Aboukhadijeh 2014-06-03 21:17:25 -07:00
parent 9562a84c5a
commit 47237ba54a
1 changed files with 20 additions and 12 deletions

View File

@ -40,7 +40,7 @@ module.exports = function (metadata) {
} }
if (info) if (info)
this._gotMetadata(info) this.setMetadata(info)
} }
} }
@ -96,7 +96,10 @@ module.exports = function (metadata) {
} }
} }
// Expose high-level, friendly API (fetch/cancel) /**
* Ask the peer to send metadata.
* @public
*/
ut_metadata.prototype.fetch = function () { ut_metadata.prototype.fetch = function () {
if (this._metadataComplete) { if (this._metadataComplete) {
return return
@ -107,10 +110,24 @@ module.exports = function (metadata) {
} }
} }
/**
* Stop asking the peer to send metadata.
* @public
*/
ut_metadata.prototype.cancel = function () { ut_metadata.prototype.cancel = function () {
this._fetching = false this._fetching = false
} }
ut_metadata.prototype.setMetadata = function (_metadata) {
if (this._metadataComplete) return
this._metadataComplete = true
this.metadata = _metadata
this._metadataSize = this.metadata.length
this.cancel()
this._wire.extendedHandshake.metadata_size = this._metadataSize
this.emit('metadata', bncode.encode({ info: bncode.decode(this.metadata) }))
}
ut_metadata.prototype._send = function (dict, trailer) { ut_metadata.prototype._send = function (dict, trailer) {
var buf = bncode.encode(dict) var buf = bncode.encode(dict)
if (Buffer.isBuffer(trailer)) { if (Buffer.isBuffer(trailer)) {
@ -195,21 +212,12 @@ module.exports = function (metadata) {
// check hash // check hash
if (sha1(this.metadata) === this._infoHash.toString('hex')) { if (sha1(this.metadata) === this._infoHash.toString('hex')) {
this._gotMetadata(this.metadata) this.setMetadata(this.metadata)
} else { } else {
this._failedMetadata() this._failedMetadata()
} }
} }
ut_metadata.prototype._gotMetadata = function (_metadata) {
this.cancel()
this.metadata = _metadata
this._metadataComplete = true
this._metadataSize = this.metadata.length
this._wire.extendedHandshake.metadata_size = this._metadataSize
this.emit('metadata', bncode.encode({ info: bncode.decode(this.metadata) }))
}
ut_metadata.prototype._failedMetadata = function () { ut_metadata.prototype._failedMetadata = function () {
// reset bitfield & try again // reset bitfield & try again
this._bitfield = new BitField(0, { grow: BITFIELD_GROW }) this._bitfield = new BitField(0, { grow: BITFIELD_GROW })