diff --git a/README.md b/README.md index f948af6..ec31f12 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,14 @@ See the [Hypercore docs](https://github.com/hypercore-protocol/hypercore) for mo Append a block or array of blocks to the hypercore +#### `await feed.watchDownloads()` + +Emit `download` events for all blocks downloaded from now. + +#### `await feed.unwatchDownloads()` + +Stop emitting `download` events. + #### `feed.peers` A list of peers this feed is connected to. @@ -216,6 +224,10 @@ Emitted when a peer is removed. Emitted when the feed is appended to, either locally or remotely. +#### `feed.on('download', seq)` + +Emitted when block is downloaded. Has to be enabled with `watchDownloads()` first. + # License MIT diff --git a/index.js b/index.js index 6fba3a2..5650726 100644 --- a/index.js +++ b/index.js @@ -73,6 +73,11 @@ class RemoteCorestore extends EventEmitter { const remoteCore = this._sessions.get(id) if (!remoteCore) throw new Error('Invalid RemoteHypercore ID.') remoteCore._onwait(onWaitId) + }, + onDownload ({ id, seq }) { + const remoteCore = this._sessions.get(id) + if (!remoteCore) throw new Error('Invalid RemoteHypercore ID.') + remoteCore._ondownload({ seq }) } }) this._client.corestore.onRequest(this, { @@ -446,6 +451,11 @@ class RemoteHypercore extends Nanoresource { ext.onmessage(data, remotePeer) } + _ondownload (rsp) { + // TODO: Add to local bitfield? + this.emit('download', rsp.seq) + } + // Private Methods _indexOfPeer (remotePublicKey) { @@ -568,6 +578,16 @@ class RemoteHypercore extends Nanoresource { return rsp.bytes } + async _watchDownloads () { + if (!this.opened) await this.open() + if (this.closed) throw new Error('Feed is closed') + return this._client.hypercore.watchDownloads({ id: this._id }) + } + + async _unwatchDownloads () { + return this._client.hypercore.unwatchDownloads({ id: this._id }) + } + // Public Methods append (blocks, cb) { @@ -690,6 +710,14 @@ class RemoteHypercore extends Nanoresource { return prom.then(() => () => this._client.hypercore.releaseLockNoReply({ id: this._id })) } + watchDownloads (cb) { + return maybe(cb, this._watchDownloads()) + } + + unwatchDownloads (cb) { + return maybe(cb, this._unwatchDownloads()) + } + // TODO: Unimplemented methods registerExtension (name, opts) {