From f45c79b0d6eba673d537ba86b9cd8797666ad4b7 Mon Sep 17 00:00:00 2001 From: cel Date: Thu, 31 Jan 2019 15:17:28 -1000 Subject: Add drafts feature --- lib/app.js | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) (limited to 'lib/app.js') diff --git a/lib/app.js b/lib/app.js index e7cca83..1ca864e 100644 --- a/lib/app.js +++ b/lib/app.js @@ -22,6 +22,8 @@ var SsbNpmRegistry = require('ssb-npm-registry') var os = require('os') var path = require('path') var fs = require('fs') +var mkdirp = require('mkdirp') +var Base64URL = require('base64-url') var zeros = new Buffer(24); zeros.fill(0) @@ -50,6 +52,7 @@ function App(sbot, config) { this.baseUrl = 'http://' + host1 + ':' + this.port this.dir = path.join(config.path, conf.dir || 'patchfoo') this.scriptDir = path.join(this.dir, conf.scriptDir || 'script') + this.draftsDir = path.join(this.dir, conf.draftsDir || 'drafts') var base = conf.base || '/' this.opts = { @@ -103,6 +106,7 @@ function App(sbot, config) { 'search', 'live', 'compose', + 'drafts', 'emojis', 'self', 'searchbox' @@ -1390,3 +1394,61 @@ App.prototype.getScript = function (filepath, cb) { cb(null, module) }) } + +function writeNewFile(dir, data, tries, cb) { + var id = Base64URL.encode(crypto.randomBytes(8)) + fs.writeFile(path.join(dir, id), data, {flag: 'wx'}, function (err) { + if (err && err.code === 'EEXIST' && tries > 0) return writeNewFile(dir, data, tries-1, cb) + if (err) return cb(err) + cb(null, id) + }) +} + +App.prototype.saveDraft = function (id, url, form, content, cb) { + var self = this + if (!self.madeDraftsDir) { + mkdirp.sync(self.draftsDir) + self.madeDraftsDir = true + } + if (/[\/:\\]/.test(id)) return cb(new Error('draft id cannot contain path seperators')) + var draft = { + url: url, + form: form, + content: content + } + var data = JSON.stringify(draft) + if (id) fs.writeFile(path.join(self.draftsDir, id), data, cb) + else writeNewFile(self.draftsDir, data, 32, cb) +} + +App.prototype.getDraft = function (id, cb) { + var self = this + fs.readFile(path.join(self.draftsDir, id), 'utf8', function (err, data) { + if (err) return cb(err) + var draft + try { draft = JSON.parse(data) } + catch(e) { return cb(e) } + draft.id = id + cb(null, draft) + }) +} + +App.prototype.discardDraft = function (id, cb) { + fs.unlink(path.join(this.draftsDir, id), cb) +} + +App.prototype.listDrafts = function () { + var self = this + return u.readNext(function (cb) { + fs.readdir(self.draftsDir, function (err, files) { + if (err && err.code === 'ENOENT') return cb(null, pull.empty()) + if (err) return cb(err) + cb(null, pull( + pull.values(files), + pull.asyncMap(function (name, cb) { + self.getDraft(name, cb) + }) + )) + }) + }) +} -- cgit v1.2.3