var staticCache = require('koa-static-cache');
var koa = require('../..');
var path = require('path');
var fs = require('fs');
var app = koa();
var port = process.env.PORT || 3000;
app.use(staticCache(path.join(__dirname, 'public')));
app.use(function*() {
this.body = fs.createReadStream(path.join(__dirname, 'public/index.html'));
this.type = 'html';
});
app.listen(port, function () {
console.log('Server listening at port %d', port);
});
var usernames = {};
var numUsers = 0;
app.io.use(function* userLeft(next) {
console.log('somebody connected');
console.log(this.headers)
yield* next;
if (this.addedUser) {
delete usernames[this.username];
--numUsers;
this.broadcast.emit('user left', {
username: this.username,
numUsers: numUsers
});
}
});
app.io.route('add user', function* (next, username) {
this.username = username;
usernames[username] = username;
++numUsers;
this.addedUser = true;
this.emit('login', {
numUsers: numUsers
});
this.broadcast.emit('user joined', {
username: this.username,
numUsers: numUsers
});
});
app.io.route('new message', function* (next, message) {
this.broadcast.emit('new message', {
username: this.username,
message: message
});
});
app.io.route('typing', function* () {
console.log('%s is typing', this.username);
this.broadcast.emit('typing', {
username: this.username
});
});
app.io.route('stop typing', function* () {
console.log('%s is stop typing', this.username);
this.broadcast.emit('stop typing', {
username: this.username
});
});