-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.coffee
103 lines (78 loc) · 2.4 KB
/
server.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
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
require('nko')('WP4Tfg3Wdz0fNnzA')
fs = require 'fs'
PeerServer = require('peer').PeerServer
peerServer = new PeerServer({ port: 8001 })
express = require 'express'
app = express()
process.chdir __dirname
app.configure ->
app.set 'port', if app.get('env') is 'production' then 80 else 8000
app.set 'views', __dirname + '/views'
app.set 'view engine', 'jade'
app.use express.logger('dev')
app.use express.compress()
app.use require('connect-assets')
helperContext: app.locals
minifyBuilds: no # minification freaks out angular
app.locals.js.root = 'javascripts'
app.locals.css.root = 'stylesheets'
app.use express.static __dirname + '/public'
app.use (req, res, next) -> res.locals.req = req; next()
app.use app.router
# Configuration (development)
# ---------------------------
app.configure 'development', ->
app.use express.errorHandler()
# State
# -----
games = {}
waiting = {}
words = ['yay']
fs.readFile '/usr/share/dict/words', (err, data) ->
return console.log(err) if err
words = data.toString().split("\n")
# Routes
# ------
app.get '/', (req, res) ->
if app.get('env') is 'production' and req.host.toLowerCase() isnt 'sweetn.es'
res.redirect 'http://sweetn.es'
else
res.render 'index'
app.get '/play/:room', (req, res) ->
res.render 'index'
app.get '/word', (req, res) ->
word = words[Math.floor(Math.random() * words.length)].toLowerCase()
res.send word
app.get '/pair/:room/:id', (req, res) ->
id = req.param('id')
room = req.param('room')
console.log "#{room}: checking"
if waiting[room]
console.log "#{room}: pairing"
partner = waiting[room]
res.json id: partner.id, master: false
partner.res.json id: id, master: true
delete waiting[room]
else
console.log "#{room}: waiting"
waiting[room] = { id: id, res: res }
res.on 'close', ->
delete waiting[room]
console.log "#{room}: leaving"
app.get '/test', (req, res) ->
res.render 'test'
# View Helpers
# ------------
app.locals._ = require 'underscore'
# Listen
http = require 'http'
http.createServer(app).listen app.get('port'), (err) ->
if err
console.error(err)
process.exit(-1)
require('util').log "Listening on http://0.0.0.0:#{app.get('port')}/"
# if run as root, downgrade to the owner of this file
if process.getuid() == 0
fs.stat __filename, (err, stats) ->
return console.error(err) if err
process.setuid stats.uid