-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
152 lines (120 loc) · 4.24 KB
/
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
'use strict';
var socketIO = require('socket.io');
const fetch = require('node-fetch');
const jwt_decode = require('jwt-decode');
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./db/chatrooms.db');
db.run(`DROP TABLE IF EXISTS "chatrooms"`);
db.run(`CREATE TABLE IF NOT EXISTS "chatrooms" ("name" TEXT UNIQUE, "clients" INTEGER DEFAULT 0, "roomStarted" INTEGER, PRIMARY KEY("name"));`)
console.log('creating and clearing db');
var os = require('os');
var nodeStatic = require('node-static');
var http = require('http');
var PORT = process.env.PORT || 8080;
var fileServer = new(nodeStatic.Server)();
var app = http.createServer(function(req, res) {
fileServer.serve(req, res);
// console.log(req.headers)
}).listen(PORT);
var io = socketIO.listen(app);
io.sockets.on('connection', function(socket) {
socket.on('authenticate', async function(auth) {
const authData = {
username: 'USER',
password: 'PW',
};
const parsedRes = await (login(authData)).then(res => res.json());
if (!parsedRes.access) {
socket.emit('authenticate', false)
} else {
// await storeAuthToken(parsedRes);
socket.emit('authenticate', parsedRes)
}
});
function login(authData) {
const url = 'https://www.sefaria.org/api/login/';
return fetch(url, {
method: "POST",
body: JSON.stringify(authData),
headers: {
"Content-Type": "application/json;charset=UTF-8"
}
})
}
// convenience function to log server messages on the client
function log() {
var array = ['Message from server:'];
array.push.apply(array, arguments);
socket.emit('log', array);
}
socket.on('message', function(message) {
log('Client said: ', message);
var roomId = (Object.keys(socket.rooms).filter(item => item!=socket.id))[0]
socket.to(roomId).emit('message', message);
});
function createNewRoom() {
var room = Math.random().toString(36).substring(7);
socket.join(room);
console.log(`${socket.id} created room ${room}`)
log('Client ID ' + socket.id + ' created room ' + room);
socket.emit('created', room, socket.id);
db.run(`INSERT INTO chatrooms(name, clients, roomStarted) VALUES(?, ?, ?)`, [room, 1, +new Date], function(err) {
if (err) {
log(err.message);
}
});
}
socket.on('how many rooms', function() {
db.get(`SELECT COUNT(*) FROM chatrooms`, (err, rows) => {
if (err) {
return console.error(err.message);
}
const numRows = rows["COUNT(*)"]
socket.broadcast.emit('return rooms', numRows);
socket.emit('route new user', numRows);
});
});
socket.on('new room', function() {
console.log(`${socket.id} searching for a room`)
createNewRoom();
});
socket.on('create or join', function(joinOverride=false) {
console.log(`${socket.id} searching for a room`)
// log('Received request to create or join room ' + room);
db.all(`SELECT name name, clients, clients from chatrooms WHERE clients = ? ORDER BY roomStarted`, [1], (err, rows) => {
if (err) {
return console.error(err.message);
}
if (rows.length >= 2 || (joinOverride == true && rows.length > 0)) {
var row = rows[0];
var room = row.name;
log('Client ID ' + socket.id + ' joined room ' + room);
console.log('Client ID ' + socket.id + ' joined room ' + room);
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room, socket.id);
io.sockets.in(room).emit('ready');
db.run(`UPDATE chatrooms SET clients=? WHERE name=?`, [row.clients+1, room])
}
else {
createNewRoom();
}
});
});
socket.on('ipaddr', function() {
var ifaces = os.networkInterfaces();
for (var dev in ifaces) {
ifaces[dev].forEach(function(details) {
if (details.family === 'IPv4' && details.address !== '127.0.0.1') {
socket.emit('ipaddr', details.address);
}
});
}
});
socket.on('bye', function(room){
console.log(`bye received from ${socket.id} for room ${room}`)
db.run(`DELETE FROM chatrooms WHERE name=?`, room);
socket.leave(room);
socket.to(room).emit('message', 'bye');
})
});