diff options
Diffstat (limited to 'lib/util.js')
-rw-r--r-- | lib/util.js | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/lib/util.js b/lib/util.js index fe5b4f3..d25ecaf 100644 --- a/lib/util.js +++ b/lib/util.js @@ -4,6 +4,7 @@ var h = require('hyperscript') var u = exports u.ssbRefRegex = /((?:@|%|&|ssb:\/\/%)[A-Za-z0-9\/+]{43}=\.[\w\d]+)/g +u.ssbRefEncRegex = /((?:ssb:\/\/)?(?:[@%&]|%26|%40|%25)(?:[A-Za-z0-9\/+]|%2[fF]|%2[bB]){43}(?:=|%3[dD])\.[\w\d]+)/g u.isRef = function (str) { if (!str) return false @@ -62,6 +63,10 @@ u.hyperwrap = function (fn) { } } +u.toLink = function (link) { + return typeof link === 'string' ? {link: link} : link +} + u.linkDest = function (link) { return typeof link === 'string' ? link : link && link.link || link } @@ -104,3 +109,63 @@ u.extractFeedIds = function (str) { }) return ids } + +u.isMsgReadable = function (msg) { + var c = msg && msg.value && msg.value.content + return typeof c === 'object' && c !== null +} + +u.isMsgEncrypted = function (msg) { + var c = msg && msg.value.content + return typeof c === 'string' +} + +u.pullConcat = function (cb) { + return pull.collect(function (err, bufs) { + if (err) return cb(err) + cb(null, Buffer.concat(bufs)) + }) +} + +u.customError = function (name) { + return function (message) { + var error = new Error(message) + error.name = name + error.stack = error.stack.replace(/^ at .*\n/m, '') + return error + } +} + +u.escapeHTML = function (html) { + return html.toString('utf8') + .replace(/</g, '<') + .replace(/>/g, '>') +} + +u.pullSlice = function (start, end) { + if (end == null) end = Infinity + var offset = 0 + return function (read) { + return function (abort, cb) { + if (abort) read(abort, cb) + else if (offset >= end) read(true, function (err) { + cb(err || true) + }) + else if (offset < start) read(null, function next(err, data) { + if (err) return cb(err) + offset += data.length + if (offset <= start) read(null, next) + else if (offset < end) cb(null, + data.slice(data.length - (offset - start))) + else cb(null, data.slice(data.length - (offset - start), + data.length - (offset - end))) + }) + else read(null, function (err, data) { + if (err) return cb(err) + offset += data.length + if (offset <= end) cb(null, data) + else cb(null, data.slice(0, data.length - (offset - end))) + }) + } + } +} |