aboutsummaryrefslogtreecommitdiff
path: root/server.js
blob: 30b13bc2e26d761a92210869cbfc62a28f572e89 (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
// static server (8089)

var http = require('http')
var serve = require('ecstatic')
var opn = require('opn')

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


opn('http://localhost:8089')

// websocket server (8080)


var WebSocket = require('ws')
var fs = require('fs')

var wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', function (ws) {
  ws.on('message', function (message) {
    var receivedLog = JSON.parse(message)
    if (receivedLog.publicKey) {
      var publicKey = receivedLog.publicKey

      var clientLog = receivedLog.log
      // check to see if log is on server
      if (fs.existsSync(__dirname + '/bogs/' + publicKey)) {
        var serverLog = JSON.parse(fs.readFileSync(__dirname + '/bogs/' + receivedLog.publicKey))
        // if the server log has more entries than the log in the client, send the server log to the client
        if (serverLog.length > clientLog.length) {
          sendingLog = {
            publicKey: publicKey,
            log: serverLog
          }
          ws.send(JSON.stringify(sendingLog))
          console.log('SENT ' + publicKey + ' TO CLIENT')
        }
        // if server log has less entries than the log sent by the client, write it to the server
        if (serverLog.length < clientLog.length) {
          fs.writeFile(__dirname + '/bogs/' + publicKey, JSON.stringify(clientLog), function (err) {
            if (err) throw err
            console.log('SAVED ' + publicKey + ' TO SERVER')
          })
        }
        // if logs are identical, do nothing
        if (serverLog.length == clientLog.length) {
          console.log(publicKey + ': LOGS ARE THE SAME')
        }
      // if log doesn't already exist, write it
      } else {
        fs.writeFile(__dirname + '/bogs/' + publicKey, JSON.stringify(clientLog), function (err) {
          if (err) throw err
          console.log('SAVED ' + publicKey + ' TO SERVER')
        })
      }
    }
  })
})