-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.coffee
70 lines (54 loc) · 2.13 KB
/
app.coffee
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
express = require 'express'
handlebars = require 'hbs'
app = require('express')()
server = require('http').createServer(app)
io = require('socket.io').listen(server)
fs = require('fs')
data = []
app.configure ->
app.set 'port', process.env.PORT || '3000'
app.use express.logger("dev")
app.set 'views', "#{__dirname}/views"
app.set 'view engine', 'hbs'
handlebars.registerPartial('videoWorm', fs.readFileSync('views/partials/videoWorm.hbs', 'utf8'));
app.use app.router
app.use express.static("#{__dirname}/public")
app.use express.errorHandler()
app.get '/', (request, response) ->
response.render 'home'
app.get '/news', (request, response) ->
response.render 'news'
app.get '/status', (request, response) ->
response.send data
app.get '/clear', (request, response) ->
data = []
response.send 200
getRandomInt = (min, max) -> Math.floor(Math.random() * (max - min + 1)) + min
generateComment = -> { comment: "lorem-ipsum #{getRandomInt(1, 1000)}", mood: getRandomInt(0, 100) }
app.get '/populate', (request, response) ->
for i in [0..59]
data[i] =
count: getRandomInt(1, 5)
index: i
comments: []
mood: getRandomInt(0, 100)
data[i].comments.push generateComment() if getRandomInt(1, 2) > 1
response.send 200
getDataItemForIndex = (index) ->
data[index] = {count: 0, mood: 0, comments: [], index: index} if not data[index]
data[index]
updateClientsForIndex = (index) -> io.sockets.emit 'update', data[index]
io.sockets.on 'connection', (socket) ->
socket.emit 'init', data
socket.on 'client-mood-update', (updateData) ->
dataItem = getDataItemForIndex(updateData.index)
newCount = dataItem.count + 1
dataItem.mood = ((dataItem.mood * dataItem.count) + updateData.mood) / newCount
dataItem.count = newCount
updateClientsForIndex(updateData.index)
socket.on 'client-comment-update', (updateData) ->
dataItem = getDataItemForIndex(updateData.index)
dataItem.comments.push { comment: updateData.comment, mood: updateData.mood }
updateClientsForIndex(updateData.index)
server.listen app.get('port'), ->
console.log "Express server listening on port #{app.get('port')}"