cobox-group
Version:
a p2p private group for files and application-layer data
85 lines (73 loc) • 2.08 kB
JavaScript
const { KappaDrive } = require('kappa-drive')
const mount = require('kappa-drive-mount')
const assert = require('assert')
const maybe = require('call-me-maybe')
const { keyIds } = require('cobox-constants')
const {
metadata: METADATA_ID,
content: CONTENT_ID
} = keyIds
class DriveHandler extends KappaDrive {
/**
* inherit kappa-drive file system operations
* @constructor
*/
constructor (opts = {}) {
super(opts.storage, opts.address, {
feedIds: [METADATA_ID, CONTENT_ID],
multifeed: opts.feeds,
core: opts.core,
db: opts.db,
logger: opts.logger ? opts.logger('kappa-drive') : null,
keyPair: opts.deriveKeyPair
})
this.location = null
this._unmount = null
}
ready (callback) {
return maybe(callback, new Promise((resolve, reject) => {
super.ready((err) => {
if (err) return reject(err)
return resolve()
})
}))
}
async mount (opts = {}) {
assert(opts.location, 'provide a mount location')
assert(!this._unmount, 'already mounted')
this._unmount = await mount(this, opts.location, opts)
this.location = opts.location
return this.location
}
async unmount () {
assert(this._unmount, 'not mounted')
await this._unmount()
this._unmount = null
var location = this.location
this.location = null
return location
}
async ls (subdir = '/') {
assert(typeof subdir === 'string', 'path must be a string')
const files = await new Promise((resolve, reject) => {
this.readdir(subdir, (err, files) => {
if (err) reject(err)
resolve(files)
})
})
const stats = await Promise.all(files.map((file) => {
return new Promise((resolve, reject) => {
this.lstat(file, (err, statObj) => {
if (err) reject(err)
resolve(statObj)
})
})
}))
return stats.reduce((acc, cur, i) => {
acc[files[i]] = cur
return acc
}, {})
}
}
module.exports = (...args) => new DriveHandler(...args)
module.exports.DriveHandler = DriveHandler