Skip to content

Commit

Permalink
Watch downloads
Browse files Browse the repository at this point in the history
  • Loading branch information
Frando committed Aug 10, 2020
1 parent 486e10b commit d82b791
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
28 changes: 28 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit d82b791

Please sign in to comment.