forked from ksky521/nodeppt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·326 lines (288 loc) · 10.5 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
var fs = require('fs');
var URL = require('url');
var path = require('path');
var exec = require('child_process').exec;
var mimes = require('./mime.json');
var $ = require('./helper');
var connect = require('connect');
var libDir = __dirname;
var rootDir = path.join(libDir, '../') + path.sep;
var templateDir = path.join(rootDir, 'template') + path.sep;
var md_parser = require('./md_parser');
//session 相关
var cookie = require('cookie');
var parseSignedCookie = connect.utils.parseSignedCookie;
var MemoryStore = connect.middleware.session.MemoryStore;
var Session = connect.middleware.session.Session;
//建立一个memory store的实例
var storeMemory = new MemoryStore({
reapInterval: 60000 * 10
});
module.exports.start = function(port, pptDir, host, argvObj) {
port = parseInt(port, 10) || 8080;
var app = startApp(port, pptDir, host, argvObj);
var io = require('socket.io').listen(app, {
log: false,
origins: '*:*' //解决同源策略
});
//设置session
io.set('authorization', function(handshakeData, accept) {
// 通过客户端的cookie字符串来获取其session数据
var ccc = '';
if(handshakeData.headers && handshakeData.headers.cookie){
ccc = handshakeData.headers.cookie;
}
handshakeData.cookie = cookie.parse(ccc);
var connect_sid = parseSignedCookie(handshakeData.cookie['connect.sid'], 'wyq');
if (connect_sid) {
storeMemory.get(connect_sid, function(error, session) {
if (error) {
// if we cannot grab a session, turn down the connection
accept(error.message, false);
} else {
// save the session data and accept the connection
handshakeData.session = new Session(handshakeData, session);
handshakeData.connect_sid = connect_sid;
accept(null, true);
}
});
} else {
accept('nosession');
}
});
var now = Date.now();
var sockets = {};
var userMap = {};
io.sockets.on('connection', function(socket) {
var session = socket.handshake.session; //session
// var uid = now++;
var uid = session.uid;
socket.uid = uid;
console.log('socket.io:' + uid);
sockets[uid] = socket;
//监听添加map
socket.on('add client', function(data) {
var targetUid = socket.targetUid = data.targetUid;
var otherSocket = sockets[targetUid];
userMap[targetUid] = uid;
userMap[uid] = targetUid;
otherSocket && otherSocket.emit('system', {
action: 'join',
joinUid: uid
});
});
//建立消息中转站
socket.on('repost data', function(data) {
var uid = socket.uid;
var targetUid = userMap[uid];
var otherSocket = sockets[targetUid];
otherSocket && otherSocket.emit('data from another client', data);
});
//将当前分配的uid告知客户端
socket.emit('UUID', uid);
socket.on('disconnect', function() {
var uid = socket.uid;
var targetUid = userMap[uid];
var otherSocket = sockets[targetUid];
otherSocket && otherSocket.emit('system', {
action: 'leave',
leaveUid: uid
});
delete sockets[uid];
});
});
};
function startApp(port, dir, host, argvObj) {
host = host || '0.0.0.0';
var staticDir = path.normalize(path.join(__dirname, '../assets')) + path.sep;
var pptDir = (dir || path.join(__dirname, '../ppts')) + path.sep;
try {
pptDir = fs.realpathSync(pptDir) + path.sep;
} catch (e) {}
var now = Date.now();
var app = connect(
connect.cookieParser(),
connect.session({
secret: 'wyq',
store: storeMemory
}),
function(req, res) {
var url = URL.parse(req.url).pathname;
var dirname = path.dirname(url);
var realPath, ext;
var uid = req.session.uid;
if (!uid) {
uid = now++; //当前连接用户的UID
req.session.uid = uid;
console.log('new user: ' + uid);
} else {
console.log('welcome back ' + uid);
}
if (url === '/') {
pptlist(res, pptDir, argvObj);
return;
} else if (dirname === '/md') {
uid = req.session.uid;
if (!uid) {
uid = now++; //当前连接用户的UID
req.session.uid = uid;
console.log('new user: ' + uid);
} else {
console.log('welcome back ' + uid);
}
url = URL.parse(req.url).pathname;
var basename = path.basename(url);
var queryObj = URL.parse(req.url, true).query;
realPath = pptDir + basename;
console.log('markdown', realPath);
markdown(realPath, basename, res, argvObj, queryObj);
return;
} else {
//优先选择pptDir的静态资源
url = url.indexOf('/') === 0 ? url.substring(1) : url;
realPath = pptDir + url;
if (!fs.existsSync(realPath)) {
realPath = staticDir + url;
}
ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
}
assets(realPath, ext, url, res, argvObj);
}).listen(port, host);
return app.on('listening', function() {
var server = app.address();
var address = server.address === '0.0.0.0' ? '127.0.0.1' : server.address;
var url = ' http://' + address + ':' + server.port
console.log('ppt directory:'.cyan + ' ' + pptDir);
console.log('assets directory:'.cyan + ' '+staticDir);
console.log('nodeppt server started:'.cyan + url.yellow);
if (process.platform === 'win32') {
exec('start' + url);
} else {
exec('open' + url);
}
}).on('error', function(e) {
if (e.code === 'EADDRINUSE' || e.code === 'EACCES') {
console.log('ERROR: '.red + 'port ' + port + ' is in use!');
} else {
console.log('ERROR: '.red + 'server start ' + host + ':' + port + ' info : ' + e.code);
}
});
}
function assets(realPath, ext, url, res, argvObj) {
//静态资源
if (fs.existsSync(realPath)) {
fs.readFile(realPath, 'binary', function(err, file) {
if (err) {
res.writeHead(500, {
'Powered-By': 'nodePPT',
'Content-Type': 'text/plain'
});
res.end(err);
} else {
res.writeHead(200, {
'Powered-By': 'nodePPT',
'Content-Type': mimes[ext]
});
res.write(file, 'binary');
res.end();
}
});
} else {
page404(res, url);
}
}
function page404(res, url) {
res.writeHead(404, {
'Powered-By': 'nodePPT',
'Content-Type': mimes.txt
});
res.write('This request URL ' + url + ' was not found on this server.');
res.end();
}
function markdown(realPath, url, res, argvObj, queryObj) {
if (fs.existsSync(realPath)) {
var content = fs.readFileSync(realPath, 'utf-8').toString();
try {
var html = md_parser(content, function() {}, argvObj, queryObj);
res.writeHead(200, {
'Powered-By': 'nodePPT',
'Content-Type': mimes.html
});
res.write(html);
res.end();
} catch (e) {
res.writeHead(500, {
'Powered-By': 'nodePPT',
'Content-Type': 'text/plain'
});
res.end(e.toString());
}
} else {
page404(res, url);
}
}
/**
* 读取ppt列表
* @param {[type]} res [description]
* @param {[type]} dir [description]
* @return {[type]} [description]
*/
function pptlist(res, dir, argvObj) {
var staticDir = path.join(__dirname, '../assets') + '/';
res.writeHead(200, {
'Powered-By': 'nodePPT',
'Content-Type': mimes.html
});
var curPath = dir;
var count = 0,
list = '';
//遍历html文件
$.recurse(dir, function(abspath, rootdir, subdir, filename) {
count++;
var content = fs.readFileSync(abspath, 'utf-8').toString();
var title = content.match(/<title>(.*?)<\/title>/);
if (title[1]) {
title = title[1];
} else {
title = filename;
}
var url = filename;
list += '<li><a class="star" href="' + url + '" target="_blank">' + title + '</a></li>';
}, '', '', function(filename) {
return /\.htm[l]?/.test(filename);
});
//遍历markdown文件
$.recurse(dir, function(abspath, rootdir, subdir, filename) {
count++;
var content = fs.readFileSync(abspath, 'utf-8').toString();
//第一个是封面
var cover = content.split('[slide]').shift();
var title = md_parser.parseCover(cover).title;
if (!title) {
title = filename;
}
var url = '/md/' + filename;
list += '<li><a class="star" href="' + url + '" target="_blank">' + title + '</a>';
list += (argvObj.controller === 'socket' ? '' : ' [<a href="' + url + '?_multiscreen=1" target="_blank" title="多窗口打开">多窗口</a>] [<a href="' + url + '?controller=socket" target="_blank" title="用socket远程控制">远程控制</a>]') + '</li>';
}, '', '', function(filename) {
return /\.(md|markdown)$/.test(filename);
});
var json = require(path.join(__dirname, '../package.json'));
var data = {
version: json.version,
site: json.site,
date: Date.now(),
list: list,
dir: curPath
};
//渲染模板
var html = $.renderFile(templateDir + 'list.ejs', data);
res.write(html);
if (count == 0) {
//路径不存在ppt
res.write('This directory ' + curPath + ' was not found html on this server.');
console.log(('This directory ' + curPath + ' was not found html on this server.').red);
}
res.end();
}