forked from juanpabloaj/p2p-microblog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (71 loc) · 2.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const choo = require('choo')
const html = require('choo/html')
const dat = require('./lib/dat.js')
const utils = require('./lib/utils.js')
var mainView = require('./templates/main.js')
var app = choo()
app.use(function (state, emitter) {
state.posts = []
state.sources = []
emitter.on('addPost', function (data) {
dat.publishPost(data.content).then(url => {
dat.updatePostsFile(window.location.toString(), url)
emitter.emit('render')
})
})
emitter.on('addSource', function (data) {
state.sources.push(data)
dat.writeJson(
window.location.toString(),
'/sources.json', {sources: state.sources}
)
emitter.emit('render')
})
emitter.on('removeSource', function (i) {
state.sources.splice(i, 1)
dat.writeJson(
window.location.toString(),
'/sources.json', {sources: state.sources}
)
emitter.emit('render')
})
emitter.on('getPostsFromAllSources', function () {
state.sources.forEach(function(source){
emitter.emit('getPostsFromSource', source.url)
})
})
emitter.on('getPostsFromSource', function (url) {
dat.getPosts(url).then(posts => {
posts.forEach(function (post) {
dat.getPostContent(post).then(newPost => {
if (!utils.urlInArray(newPost.url, state.posts)) {
state.posts.unshift(newPost)
emitter.emit('render')
}
})
})
})
})
emitter.on('getSourcesInfo', function () {
var result = state.sources.map(dat.getSourcesInfo)
Promise.all(result).then(updatedSources => {
state.sources = updatedSources
})
})
dat.loadJson(window.location.toString(), '/sources.json').then(json => {
state.sources = json.sources
state.events = state.sources.map(source => {
var archive = new DatArchive(source.url)
var evts = archive.watch('/posts.json')
evts.addEventListener('changed', ({path}) => {
emitter.emit('getPostsFromSource', source.url)
})
return {url: source.url, events: evts}
})
emitter.emit('getPostsFromAllSources')
emitter.emit('getSourcesInfo')
emitter.emit('render')
})
})
app.route('/', mainView)
app.mount('main')