var pull = require('pull-stream') var ref = require('ssb-ref') var msum = require('markdown-summary') var sort = require('ssb-sort') var u = require('yap-util') var toUrl = u.toUrl function uniqueRecps (recps) { if(!recps || !recps.length) return recps = recps.map(function (e) { return 'string' === typeof e ? e : e.link }) .filter(Boolean) return recps.filter(function (id, i) { return !~recps.indexOf(id, i+1) }) } function getThread(sbot, id, cb) { pull( sbot.query.read({ //hack so that ssb-query filters on post but uses //indexes for root. query: [{$filter: { value: { content: {root: id} } }},{$filter: { value: { content: {type: 'post'} } }}] }), pull.collect(function (err, ary) { if(err) return cb(err) cb(null, ary) }) ) } function isObject(o) { return o && 'object' === typeof o } var isArray = Array.isArray module.exports = function (sbot) { return function (opts, apply, req) { var context = req.cookies var since = apply.since var tr = require('./translations')(context.lang) return function (cb) { var cacheTime = 0 if(!ref.isMsg(opts.id)) return cb(new Error('expected valid msg id as id')) sbot.get({id:opts.id, private: true}, function (err, msg) { if(err) return cb(err) var data = {key: opts.id, value: msg, timestamp: msg.timestamp || Date.now() } if(data.value.content.root) cb(null, apply('message', data)) //just show one message else if(data.value.content.type != 'post') cb(null, apply('message', data)) //just show one message else getThread(sbot, opts.id, function (err, ary) { var root = opts.id ary = [data].concat(ary || []) var branch = sort.heads(ary) var recps = uniqueRecps(ary[0].value.content.recps) ary.unshift(data) var o = {}, cacheTime ary = ary.filter(function (e) { if(o[e.key]) return false return o[e.key] = true }) sort(ary) var recipients = ' ' if(ary[0].value.content.recps) recipients = ['div.Recipients', tr('ThreadRecipients'), ary[0].value.content.recps.map(function (e) { return apply('avatar', e) })] cb(null, ['div.thread', apply.cacheAttrs(apply.toUrl('patch/thread', opts), data.key, since), ary[0].value.content.text && ['title', msum.title(ary[0].value.content.text)], recipients, ary.map(function (data) { var msg = apply('messageLayout', { id: data.key, author: data.value.author, content: u.markdown(data.value.content), root: root, branch: branch, ts: data.value.timestamp || data.timestamp, meta: [], extra: true }) return msg }), apply('compose', { content: { type: 'post', root: root, recps: recps, branch: branch, channel: ary[0].value.content.channel } }) ] ) }) }) } } }