Nodejs

a node.js environment for chat

fork
loading
Files
  • index.js
  • public
  • views
  • package.json
  • toDoList.txt
index.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const pug = require('pug');
const isUrl = require('is-url');
const ifIsImage = require('if-is-image');
const rp = require('request-promise');
const isColor = require('is-color')


app.locals.basedir = __dirname+"/views";
app.set('view engine', 'pug');

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/ednd'));
app.use(express.static(__dirname + '/views'));
var chat = io.of('/chat');
var lobby = io.of('/online');

var msgHelp = async function(socket) {
  socket.emit('server message', "--help--");
  socket.emit('server message', "/help -- displays this");
  socket.emit('server message', "/online -- checks who's online");
  socket.emit('server message', "/clear -- clears chat");
  socket.emit('server message', "/name [name] -- changes your name");
  socket.emit('server message', "/color #[hex code] -- changes your color");
};

var online = function(room) {
  var array = [];
  if(users[room] !== undefined) {
    for(var z=0;z<users[room].length;z++) {
      array.push(users[room][z].name);
    }
  }
  return {'str': array.toString(), 'array': array};
};

var users = {};

server.listen(3000, async function(){
  console.log('listening on port 3000');
});

chat.on('connection', async function(socket){
  socket.emit('clear chat');
  socket.emit('get user');
  socket.emit('server message',"use /help to see functions");
  
  socket.on('disconnect', async function(){
    if (socket.room !== undefined) {
      var i = users[socket.room].indexOf(socket.user);
      chat.to(socket.room).emit('server message', users[socket.room][i].name+" left");
      users[socket.room].splice(i, 1);
      lobby.emit('update',getRooms());
    }
  });
  
  socket.on('remove user', async function(){
    if (socket.room !== undefined) {
      chat.to(socket.room).emit('server message', socket.user+" left");
      users[socket.room].splice(users[socket.room].indexOf(socket.user), 1);
      lobby.emit('update',getRooms());
    }
  });
  
  socket.on('chat message', async function(msg){
    lobby.emit('update',getRooms());
    if (socket.room !== undefined) {
      var i = users[socket.room].indexOf(socket.user);
      if(msg.indexOf('/') === 0) {
        msg = msg.slice(1, msg.length);
        if(msg === "online") {
          socket.emit('server message', online(socket.room).str);
        } else if(msg === "help") {
          msgHelp(socket);
        } else if(msg === "clear") {
          socket.emit('clear chat');
        } else if(msg === "lobby") {
          socket.emit('to lobby');
        
        } else if(msg.indexOf('name') === 0) {
          msg = msg.slice('name '.length, msg.length);
          var temp = msg.replace(/ /g,"");
          if (temp == "") {
            socket.emit('server message', 'please enter a name');
          } else if(msg.length <= 50) {
            chat.to(socket.room).emit("server message", socket.user.name+" changed their name to "+msg)
            users[socket.room][i].name = msg;
            socket.user.name = msg;
            socket.emit('set user', msg);
          } else {
            socket.emit('server message', 'that name was too long');
          }
        
        } else if(msg.indexOf('room') === 0) {
          msg = msg.slice('room '.length, msg.length);
          var temp = msg.replace(/ /g,"");
          if (temp == "") {
            socket.emit('server message', 'please enter a room name');
          } else if(msg.length <= 50) {
            socket.emit('redirect', "/room/"+msg);
          } else {
            socket.emit('server message', 'that room name was too long');
          }
        
        } else if(msg.indexOf('color') === 0) {
          msg = msg.slice('color '.length, msg.length);
          var temp = msg.replace(/ /g,"");
          if (!isColor(temp) && temp !== "inherit" && temp !== "transparent") {
            socket.emit('server message', 'please enter a valid color');
          } else {
            socket.emit("server message", "your color is now "+"~~?~<span style='color:"+msg+"'>"+msg+"</font>~~?~")
            users[socket.room][i].color = msg;
            socket.user.color = msg;
            socket.emit('set color', msg);
          }
        } else {
          socket.emit('server message', "that's not recognised as a function");
        }
      } else {
        msg = encodeURI(msg);

        var ary = msg.split("%20");
        for (var z in ary) {
          var item = ary[z];
          if (isUrl(item)) {
            if(ifIsImage(item) || item.indexOf('gstatic.com/images') !== -1) {
              var good = true
              var data = await getImageData(item).catch((err) => good = false)
              if(good) ary[z] = "~~?~<img src='"+data+"'>~~?~"
            } else {
              ary[z] = "~~?~<a href='"+item+"' rel='noopener noreferrer' target='_blank'>"+item+"</a>~~?~"
            }
          }
        }

        msg = ary.join(" ")
        chat.to(socket.room).emit('chatMessage', users[socket.room][i], msg);

      }
    }
  });
  
  socket.on('join', async function(user, room){
    var name = '';
    if (user.name === 'Guest') {
      while(online(room).array.includes(name) || name === '') {
        name = user.name + " " + newID();
      }
      socket.emit("set user", name);
    } else {
      name = user.name;
    }
    user.name = name;
    if(!online(room).array.includes(name)){
      socket.user = user;
      socket.join(room);
      socket.room = room;
      if(users[room] !== undefined) {
        users[room].push(socket.user);
      } else {
        users[room] = [socket.user];
      }
      chat.to(socket.room).emit('server message', name+" has joined");
      lobby.emit('update',getRooms());
    } else {
      socket.emit('new username');
    }
  });
  socket.on('log',function(...info) {
    for (let i=0; i<info.length; i++) console.log(info[i]);
  });

});

lobby.on('connection', async function(socket){
  lobby.emit('update',getRooms());
});

app.get('/', async (req, res) => {
  res.render('home');
});

app.get('/ednd', async (req, res) => {
  res.render('ednd');
});

app.get('/lobby', async (req, res) => {
  res.render('lobby');
});

app.get('/room/:room', async (req, res) => {
  if(req.params.room.length <= 50) {
    res.render('chat', {room: req.params.room});
  } else {
    res.status(404).render('404');
  }
});

function newID() {
  return Math.floor(1000 + Math.random() * 9000);
}
function getRooms() {
  var result = [];
  for (var item in users) {
    if (users.hasOwnProperty(item)) {
      if(users[item].length !== 0) {
        result.push([item,users[item].length]);
      }
    }
  }
  return result;
}
app.use(async function (req, res, next) {
  res.status(404).render('404');
})


async function getImageData(url) {
  var options = {
      method: 'GET',
      uri: url,
      resolveWithFullResponse: true,
      encoding: null
  };
  var res = await rp(options)
  .catch(function (err) {
    throw err;
  })
  data = "data:" + res.headers["content-type"] + ";base64," + res.body.toString('base64');
  return data;
}
node v10.16.0