git ssb

16+

Dominic / patchbay



Tree: 508894a815eee17488cd4f6666209a4038721053

Files: 508894a815eee17488cd4f6666209a4038721053 / modules_basic / avatar / image.js

2881 bytesRaw
1'use strict'
2var h = require('hyperscript')
3var visualize = require('visualize-buffer')
4
5var pull = require('pull-stream')
6
7var self_id = require('../../keys').id
8
9exports.needs = {
10 sbot_query: 'first',
11 blob_url: 'first'
12}
13
14exports.gives = {
15 connection_status: true,
16 avatar_image_src: true,
17 avatar_image: true
18}
19
20var ready = false
21var waiting = []
22
23var last = 0
24
25var cache = {}
26
27exports.create = function (api) {
28 var avatars = {}
29
30 //blah blah
31 return {
32 connection_status: function (err) {
33 if (err) return
34 pull(
35 api.sbot_query({
36 query: [{
37 $filter: {
38 timestamp: {$gt: last || 0 },
39 value: { content: {
40 type: "about",
41 about: {$prefix: "@"},
42 image: {link: {$prefix: "&"}}
43 }}
44 }},
45 {
46 $map: {
47 id: ["value", "content", "about"],
48 image: ["value", "content", "image", "link"],
49 by: ["value", "author"],
50 ts: 'timestamp'
51 }}],
52 live: true
53 }),
54 pull.drain(function (a) {
55 if(a.sync) {
56 ready = true
57 while(waiting.length) waiting.shift()()
58 return
59 }
60 last = a.ts
61 //set image for avatar.
62 //overwrite another avatar
63 //you picked.
64 if(
65 //if there is no avatar
66 (!avatars[a.id]) ||
67 //if i chose this avatar
68 (a.by == self_id) ||
69 //they chose their own avatar,
70 //and current avatar was not chosen by me
71 (a.by === a.id && avatars[a.id].by != self_id)
72 )
73 avatars[a.id] = a
74
75 })
76 )
77 },
78
79 avatar_image_src: function (author) {
80 return ready && avatars[author]
81 ? api.blob_url(avatars[author].image)
82 : genSrc(author)
83
84 function genSrc (id) {
85 if(cache[id]) return cache[id]
86 var { src } = visualize(new Buffer(author.substring(1), 'base64'), 256)
87 cache[id] = src
88 return src
89 }
90 },
91
92 avatar_image: function (author, classes) {
93 classes = classes || ''
94 if(classes && 'string' === typeof classes) classes = '.avatar--'+classes
95
96 function gen (id) {
97 if(cache[id]) return h('img', {src: cache[id]})
98 var img = visualize(new Buffer(author.substring(1), 'base64'), 256)
99 cache[id] = img.src
100 return img
101 }
102
103 var img = ready && avatars[author] ? h('img', {src: api.blob_url(avatars[author].image)}) : gen(author)
104
105 ;(classes || '').split('.').filter(Boolean).forEach(function (c) {
106 img.classList.add(c)
107 })
108
109 if(!ready)
110 waiting.push(function () {
111 if(avatars[author]) img.src = api.blob_url(avatars[author].image)
112 })
113
114 return img
115 }
116 }
117}
118

Built with git-ssb-web