-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatify_server.js
94 lines (75 loc) · 2.54 KB
/
chatify_server.js
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
var html = require('fs').readFileSync(__dirname+'/chatify.html');
var url = require('url');
var server = require('http').createServer(function(req, res){
/*if(req.method=='GET') {
var url_parts = url.parse(req.url,true);
//everyone.now.receiveMessage("Server", curDate(), url_parts.query);
console.log(url_parts.query);
}*/
res.end(html);
});
server.listen(80);
var nowjs = require("now");
var everyone = nowjs.initialize(server);
var groups = {1:{names:[], log:[], group: nowjs.getGroup(1+"")}};
//var names = []; //Active users
//var log = []; //Chat history
//Keep 50 lines of chat
everyone.now.distributeMessage = function(message){
var date = curDate();
var data = {"date":date, "name":this.now.name, "message":message, "type":"msg"};
var log = groups[this.now.group].log;
var group = groups[this.now.group].group;
log.push(data); //Add to history
if(log.length > 50) log.splice(0, 1); //Ensure that there are only 50 lines kept in the history
group.now.receiveMessage(this.now.name, date, message);
};
nowjs.on('connect', function(){
//Update user list
var newName = this.now.name;
if(newName=="" || newName==null) {
newName="Guest";
this.now.name="Guest";
}
if(!(this.now.group in groups)) groups[this.now.group] = {names:[], log:[], group: nowjs.getGroup(this.now.group+"")};
var names = groups[this.now.group].names;
var log = groups[this.now.group].log;
var group = groups[this.now.group].group;
var num = 1;
while(names.indexOf(newName)!=-1) {
newName = this.now.name+num;
num++;
}
this.now.name = newName;
this.now.changeName(newName);
var date=curDate();
group.now.announceUser(newName, date);
group.addUser(this.user.clientId);
names.push(newName);
this.now.listAllUsers(names);
//Send user some chat history
this.now.receiveHistory(log);
log.push({"date":date, "name":this.now.name, "message":"", "type":"connect"});
});
nowjs.on('disconnect', function(){
var date=curDate();
var index = groups[this.now.group].names.indexOf(this.now.name);
groups[this.now.group].names.splice(index, 1);
groups[this.now.group].group.now.removeUser(this.now.name, date);
groups[this.now.group].log.push({"date":date, "name":this.now.name, "message":"", "type":"disconnect"});
});
function curDate(){
var d = new Date();
var morn = "AM";
var hours = d.getHours();
if(hours>12) {
morn = "PM";
hours-=12;
}
var mins = ""+d.getMinutes();
if(mins.length==1) mins = "0"+mins;
var secs = ""+d.getSeconds();
if(secs.length==1) secs = "0"+secs;
var dStr = hours + ":" + mins + ":"+ secs + " " + morn;
return dStr;
}