Use most popular name/image

This commit is contained in:
cel
2017-05-12 13:29:46 -10:00
parent 4cfbba635d
commit d87029da1c
+36 -13
View File
@@ -1,31 +1,54 @@
var pull = require('pull-stream')
var sort = require('ssb-sort')
function linkDest(val) {
return typeof val === 'string' ? val : val && val.link
function asString(val) {
return typeof val === 'string' && val
}
function reduceAbout(about, msg) {
var c = msg.value.content
if (!c) return about
if (c.name) about.name = c.name.replace(/^@?/, '@')
if (c.image) about.image = linkDest(c.image)
return about
function linkDest(val) {
return val ? asString(val) || asString(val.link) : null
}
module.exports = function (sbot, id, cb) {
var about = {}
var aboutByFeed = {}
pull(
sbot.links({
rel: 'about',
dest: id,
values: true,
}),
pull.collect(function (err, msgs) {
pull.drain(function (msg) {
var author = msg.value.author
var c = msg.value.content
if (!c) return
var feedAbout = aboutByFeed[author] || (aboutByFeed[author] = {})
if (c.name) feedAbout.name = c.name.replace(/^@?/, '@')
if (c.image) feedAbout.image = linkDest(c.image)
}, function (err) {
if (err) return cb(err)
cb(null, sort(msgs).reduce(reduceAbout, {
name: String(id).substr(0, 10) + '…',
}))
// Use whatever properties have the most counts.
// Usually we would want to handle renames for dead feeds and such,
// but for ssb-viewer it is mostly public/archival content anyway,
// so we'll let the popular name stand.
var propValueCounts = {/* prop: {value: count} */}
var topValues = {/* prop: value */}
var topValueCounts = {/* prop: count */}
var about = {}
for (var feed in aboutByFeed) {
var feedAbout = aboutByFeed[feed]
for (var prop in feedAbout) {
var value = feedAbout[prop]
var valueCounts = propValueCounts[prop] || (propValueCounts[prop] = {})
var count = (valueCounts[value] || 0) + 1
valueCounts[value] = count
if (count > (topValueCounts[prop] || 0)) {
topValueCounts[prop] = count
topValues[prop] = value
}
}
}
if (!topValues.name) topValues.name = String(id).substr(0, 10) + '…'
cb(null, topValues)
})
)
}