aboutsummaryrefslogtreecommitdiff
path: root/server.js
blob: 8f7d1c3245b776ee36569cb35572b0a9eac0ca45 (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
const HTTPPORT = 8089
const WSPORT = 8080
const URL = 'localhost'
const ADVERTISEMENTS = true

var ads = require('./ads')

const fullURL = 'http://' + URL + ':' + HTTPPORT + '/'

if (process.argv[2] === 'verbose') {
  var VERBOSE = true
} else {
  var VERBOSE = false
}

console.log('Verbose output is ' + VERBOSE + ' run with `node server verbose` to see all output')
console.log('Advertisements are ' + ADVERTISEMENTS)

// log messages

function printAsk(req, unboxedreq) {
  if (VERBOSE) {
    console.log(req.requester + ' asked for feed ' + unboxedreq.author + ' after sequence ' + unboxedreq.seq)
  }
}

function printNewFeed (msg, req) {
  if (VERBOSE) 
    console.log('Saved full log of ' + msg.author + ' sent by ' + req.requester)
  else 
    console.log('NEW FEED from ' + msg.author)
}

function printUpdateFeed (msg, req) {
  if (VERBOSE)
    console.log('combined existing feed of ' + msg.author + ' sent from ' + req.requester + ' with diff and saved to server')
  else
    console.log('NEW UPDATE from ' + msg.author)
}

function printNoFeed (msg, req) {
  if (VERBOSE) { 
    console.log('We don\'t have the log on the server, requesting log from ' + req.requester )
  }
}

function printClientLonger (msg, req) {
  if (VERBOSE) {
    console.log(req.requester + '\'s feed of ' + msg.author  + ' is longer, requesting diff from ' + req.requester)
  }
}

function printClientShorter (msg, req, baserange, endrange) {
  if (VERBOSE) {
    console.log(req.requester + ' feed of ' + msg.author + ' is shorter, sending from ' + baserange + ' to ' + endrange + ' to ' + req.requester)
  }
}

function printFeedIdentical (msg, req) {
  if (VERBOSE) { 
    console.log(msg.author + '\'s feed sent from ' + req.requester + ' is identical')
  }
}

function printSendAd (msg, req) {
  if (VERBOSE) {
    console.log('sent ad ' + msg.content + ' to ' + req.requester)  
  }
}

// static server (8089)

var fs = require('fs')
var http = require('http')
var serve = require('ecstatic')
var open = require('open')

http.createServer(
  serve({ root: __dirname})
).listen(HTTPPORT)

open(fullURL)

console.log('Bogbook is running at: ' + fullURL)

// ws server (8080)

var bog = require('./bog')
var WS = require('ws')
var nacl = require('tweetnacl')
    nacl.util = require('tweetnacl-util')

var homedir = require('os').homedir()
var bogdir = homedir + '/.bogbook/bogs/'
var addir = homedir + '/.bogbook/ads/'

if (!fs.existsSync(homedir + '/.bogbook/')) {fs.mkdirSync(homedir + '/.bogbook/')}
if (!fs.existsSync(bogdir)){fs.mkdirSync(bogdir)}

var wserve = new WS.Server({ port: WSPORT })

bog.keys().then(key => {
  wserve.on('connection', function (ws) {
    ws.on('message', function (message) {
      var req = JSON.parse(message)
      if (req.sendpub) {
        ws.send(key.publicKey)
      } else { 
        bog.unbox(req.box, req.requester, key).then(unboxed => {
          var unboxedreq = JSON.parse(nacl.util.encodeUTF8(unboxed))
          if (unboxedreq.type == 'ad') {
            
            var hex = Buffer.from(nacl.hash(nacl.util.decodeUTF8(unboxedreq.signature))).toString('hex')
            
            var obj = {
              hash: hex,
              author: unboxedreq.author,
              signature: unboxedreq.signature,
              views: 0
            }
             
            fs.writeFile(addir + hex, JSON.stringify(obj), 'UTF-8', function () {
              console.log('Saved as ' + hex)
            })
            ws.close()
          }
          if (unboxedreq.seq >= 0) {
            printAsk(req, unboxedreq)
            fs.readFile(bogdir + unboxedreq.author, 'UTF-8', function (err, data) {
              if (data) {
                var feed = JSON.parse(data)
                bog.open(feed[0]).then(msg => {
                  if (unboxedreq.seq === msg.seq) { 
                    printFeedIdentical(msg, req)
                    if (ADVERTISEMENTS) {
                      if (Math.floor(Math.random() * 4) == 2) {
                        fs.readdir(addir, function (err, adfiles) {
                          if (adfiles[0]) {
                            var num = Math.floor(Math.random() * (adfiles.length)) 
                            fs.readFile(addir + adfiles[num], 'UTF-8', function (err, adFile) {
                              var obj = JSON.parse(adFile)
                              var ad = {
                                author: obj.author,
                                name: fullURL,
                                content: obj.signature,
                                timestamp: Date.now(),
                                views: obj.views
                              }
                              if ((obj.views > 100) && (obj.author != '@Q++V5BbvWIg8B+TqtC9ZKFhetruuw+nOgxEqfjlOZI0=')) {
                                fs.unlinkSync(addir + obj.hash)
                                //console.log('REMOVING AD')
                              } else {
                                obj.views++
                                fs.writeFileSync(addir + obj.hash, JSON.stringify(obj), 'UTF-8')
                              }
                              printSendAd(ad, req)
                              //console.log('SENDING AD')
                              bog.box(JSON.stringify(ad), req.requester, key).then(boxed => {
                                sendobj = {
                                  requester: key.publicKey,
                                  box: boxed
                                }
                                ws.send(JSON.stringify(sendobj))    
                                ws.close()
                              })
                            })
                          } else {
                            ads.make('Hello World.')
                          }
                        })
                      }
                    }
                  } 
                  if (unboxedreq.seq > msg.seq) {
                    printClientLonger(msg, req)
                    var reqdiff = JSON.stringify({author: unboxedreq.author, seq: msg.seq})
                    bog.box(reqdiff, req.requester, key).then(boxed => {
                      var obj = {
                        requester: key.publicKey,
                        box: boxed
                      }
                      ws.send(JSON.stringify(obj))
                    })
                  }
                  if (unboxedreq.seq < msg.seq) {
                    var endrange = feed.length - unboxedreq.seq - 25
                    if (endrange < 0) {
                      endrange = feed.length - unboxedreq.seq - 1
                    }
                    var baserange = feed.length - unboxedreq.seq
                    printClientShorter(msg, req, baserange, endrange)
                    var diff = JSON.stringify(
                      feed.slice(
                        endrange, 
                        baserange)
                      )
                    bog.box(diff, req.requester, key).then(boxed => {
                      var obj = {
                        requester: key.publicKey,
                        box: boxed
                      }
                      ws.send(JSON.stringify(obj))
                      ws.close()
                    })
                  }  
                }) 
              } else {
                printNoFeed(unboxedreq, req)
                var reqwhole = JSON.stringify({author: unboxedreq.author, seq: 0})

                bog.box(reqwhole, req.requester, key).then(boxed => {
                  var obj = {
                    requester: key.publicKey,
                    box: boxed  
                  }
                  ws.send(JSON.stringify(obj))
                })
              }
            })
          } else if (Array.isArray(unboxedreq)) {
            bog.open(unboxedreq[0]).then(msg => {
              if (msg.seq === unboxedreq.length) {
                fs.writeFile(bogdir + msg.author, JSON.stringify(unboxedreq), 'UTF-8', function (err, success) {
                  printNewFeed(msg, req)
                })
              } if (msg.seq > unboxedreq.length) {
                fs.readFile(bogdir + msg.author, 'UTF-8', function (err, data) {
                  var feed = JSON.parse(data)
                  bog.open(feed[0]).then(lastmsg => {
                    if (unboxedreq.length + lastmsg.seq === msg.seq) {
                      var newlog = unboxedreq.concat(feed)
                      fs.writeFile(bogdir + msg.author, JSON.stringify(newlog), 'UTF-8', function (err, success) {
                        printUpdateFeed(msg, req)
                      })
                    }
                  })
                })
              } 
            })
          } 
        })
      }
    })
  })
})