-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
230 lines (196 loc) · 7.12 KB
/
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
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
// imports
const https = require( 'https' );
const socket = require( 'socket.io' )
const Sqlite3 = require("sqlite3");
const expressClass = require( 'express' );
const cors = require( 'cors' );
const Sessions = require( 'express-session' );
const sqliteStoreFactory = require( 'express-session-sqlite' ).default ;
const util = require( "./src/server/util.js" );
const AppSqlite = require( "./src/server/sqlite3.js" );
// Variables
const { hostname , port } = require( './src/hostPort.js' );
const path = require( 'path' );
const fs = require( 'fs' );
const Queue = require("./src/server/queue");
const root = __dirname ;
const SessionsSqliteStore = sqliteStoreFactory( Sessions );
const SessionStore = new SessionsSqliteStore({
// Database library to use. Any library is fine as long as the API is compatible
// with sqlite3, such as sqlite3-offline
driver: Sqlite3.Database,
// for in-memory database
// path: ':memory:'
path: 'sessions.db',
// Session TTL in milliseconds
ttl: 30000000 ,
// (optional) Session id prefix. Default is no prefix.
prefix: 'sess:',
// (optional) Adjusts the cleanup timer in milliseconds for deleting expired session rows.
// Default is 5 minutes.
cleanupInterval: 30000000
});
// Create Express App
const express = expressClass();
// Cross-Origin Handling
express.use( cors() );
// Session Handling ( express-sessions with custom sqlite3 store )
express.use( Sessions({
secret:'Node Socket Server' ,
resave: false,
saveUninitialized: true,
cookie: { maxAge: 600000 } ,
genid : ( req ) => util.generateUID() ,
store : SessionStore
}));
// static files
express.use( "/dist" , expressClass.static( path.join( root , "/dist" ) ) );
// method for initializing user sessions
express.initUser = ( req , res ) => {
let ssn = req.session ;
// Set Id As Cookie
res.cookie( 'sid', ssn.id );
}
// App Routes
express.get('/', (req, res) => {
express.initUser( req , res );
res.sendFile( path.join( root , './dist/index.html' ) );
});
// testing : session id => socket connection id
express.get( '/io', (req, res) => {
express.initUser( req , res );
AppSqlite.getSocket( req.session.id , ( socketRow ) => {
if( !socketRow ){
res.json({
"failed" : "no socket entry found for your session"
});
} else res.json({
"message" : "welcome : " + socketRow.ssid ,
"socket" : socketRow.io
});
});
});
/**
* @Creating-Server
* Camera & Mic permissions only work when we are secure ( HTTPS )
* so we will create "HTTPS" server to meet the security requirements
**/
// more info :
// Certificate & Key created according to this answer on Stackoverflow :
// https://stackoverflow.com/questions/23001643/how-to-use-https-with-node-js
let httpsOptions = {
key : fs.readFileSync( path.join( root , 'http-cert.key') ) ,
cert : fs.readFileSync( path.join( root , 'http-cert.crt') )
};
// Https server ( express as middleware )
const server = https.createServer( httpsOptions , express );
// Socket server with Cross-Origin options
const ioServer = socket( server , {
cors: {
origin: hostname , // Only answer to this origin
methods: ["GET", "POST" ]
}
});
// Socket server magic :)
ioServer.on( "connection" , (mSocket) => {
mSocket.on( "setSessionId" , ({ sid }) => {
// find my session - add/update
AppSqlite.addSocket( sid , mSocket.id , '-' , () => {});
// send back my new socket id
mSocket.emit( "setSocketId" , mSocket.id );
});
mSocket.on( "getContactIO" , ({ contactId }) => {
AppSqlite.getSocketByPartial( contactId , ( raw ) => {
if( raw ){ // Contact is online
mSocket.emit( "foundContactIO" , raw.io );
} else { // No contact found
mSocket.emit( "noContactIO" , contactId );
}
});
});
// p2p call functions
mSocket.on("disconnect", () => {
mSocket.broadcast.emit("callEnded")
});
mSocket.on("callUser", ({ userToCall, signalData, from, name , number }) => {
ioServer.to(userToCall).emit("callReceive", { signal: signalData, from , number , callerName : name });
});
mSocket.on("answerCall", ({ signal , to , name , number , from }) => {
ioServer.to(to).emit("callAccepted", { signal , from , cNumber : number , cName : name });
});
// radio/tv functions
let queue ;
mSocket.on( "host_init" , ( sid ) => {
// create new queue for this user ( host )
// queue = new Queue();
// update( remove / add ) socket user's row
AppSqlite.addSocket( sid , mSocket.id , 'hosting' , () => {});
});
mSocket.on( "listener_join" , ({ sid , channel }) => {
// update( remove / add ) socket user's row
AppSqlite.addSocket( sid , mSocket.id , channel , () => {});
});
mSocket.on("channel_bufferHeader", ({ channel , header }) => {
//queue.bufferHeader = header ;
AppSqlite.getSocketListeners( channel , ( rows ) => {
// send to each listener!
if( rows ) for( let row in rows ) {
//console.log( 'streaming header to : ' + rows[row].io );
mSocket.to(rows[row].io).emit('channel_bufferHeader', { header });
}
});
});
mSocket.on( "channel_stream" , ({ channel , data }) => {
AppSqlite.getSocketListeners( channel , ( rows ) => {
// send to each listener!
if( rows ) for( let row in rows ){
//console.log( 'streaming data to : ' + rows[row].io );
mSocket.to( rows[row].io ).emit( 'channel_stream' , { data });
}
});
});
mSocket.on( 'channel_stream_stop' , ({ channel }) => {
AppSqlite.getSocketListeners( channel , ( rows ) => {
// send to each listener!
if( rows ) for( let row in rows ){
//console.log( 'streaming data to : ' + rows[row].io );
mSocket.to( rows[row].io ).emit( 'channel_stream_stop' );
}
});
});
mSocket.on( 'listener_leave' , ({ sid }) => {
// update( remove / add ) socket user's row
AppSqlite.addSocket( sid , mSocket.id , '-' , () => {});
});
});
// for streaming radio/tv
express.get("/stream/radio/:channel", (req, res) => {
// add new listener
const { id, client } = queue.addClient();
console.log( "stream radio init" )
res.set({
"Content-Type": "audio/mp3" ,
"Transfer-Encoding": "chunked",
}).status(200);
client.pipe( res );
req.on("close", () => {
queue.removeClient(id);
});
});
// for streaming radio/tv
express.get("/stream/tv/:channel", (req, res) => {
// add new listener
const { id, client } = queue.addClient();
console.log( "stream tv init" )
res.set({
"Content-Type": "video/mp4" ,
"Transfer-Encoding": "chunked",
}).status(200);
client.pipe( res );
req.on("close", () => {
queue.removeClient(id);
});
});
server.listen(port, hostname, () => {
console.log(`HTTPS-Server running at https://${hostname}:${port}/`);
});