-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSSE-server.js
367 lines (322 loc) · 10.5 KB
/
SSE-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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// New server for Conkey, in Node.js
// TO-DO:
// * alert when new girls arrive
// * ./loadDatabase/:name, Read the latest database_default.##.txt
// * ./saveDatabase/:name
// FIXED:
// * ./speakMandarin/, extra "text=" at beginning of data (fixed in contentscript2, ajax POST)
// * log data is not decoded, with extra "data=" (fixed in contentscript2, ajax POST)
// * log file name = "quick" if name is in Chinese; (added decodeURIComponent)
// * ./saveChatLog/
// * contentscript2 doesn't seem to load for 寻梦园 (add-on is temporary)
// * ./fireFox "data" has '+' instead of spaces (fixed)
// * to be able to output to 寻梦园 at least
// * Strange, double sending /fireFox, why? And it's always twice...!?
// (is it because the login page triggered another copy of contentscript.js?)
// (maybe because console.log($.ajax POST...)?)
// (problem seems disappeared now but I forgot why)
// * how to decide if both Chrome and Firefox have chat windows?
// (use only Firefox from now...)
/* **** This code works, but is not needed now
* **** I prefer to use Python to access Neo4j locally.
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost', neo4j.auth.basic('neo4j', 'l0wsecurity'));
const session = driver.session();
const personName = 'Alice';
async function startNeo4j() {
try {
const result = await session.run(
'CREATE (a:Person {name: $name}) RETURN a',
{ name: personName }
)
const singleRecord = result.records[0]
const node = singleRecord.get(0)
console.log(node.properties.name)
} finally {
await session.close()
// on application exit:
driver.close();
}
}
startNeo4j();
*/
var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var sse_res = null; // for SSE = Server-Side Events
var sse_res2 = null;
function reqHandler(req, res) {
// SSE handler: this allows server to *respond* to events, as opposed to
// a plain server which can only be read from / written to.
if (req.headers.accept && req.headers.accept == 'text/event-stream') {
if (req.url == '/stream') {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write("retry: 10000\n");
res.write("event: connecttime\n");
// res.write("data: " + (new Date()) + "\n\n");
// res.write("data: " + (new Date()) + "\n\n");
res.write(": \n\n");
res.write(": \n\n");
// res.end(); // this causes "write after end" error
sse_res = res;
console.log("Connected event stream");
} else if (req.url == '/dreamstream') {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write("retry: 10000\n");
res.write("event: connecttime\n");
// res.write("data: " + (new Date()) + "\n\n");
// res.write("data: " + (new Date()) + "\n\n");
res.write(": \n\n");
res.write(": \n\n");
// res.end(); // this causes "write after end" error
sse_res2 = res;
console.log("Connected event stream 2");
} else {
res.writeHead(404);
res.end();
}
return;
}
var interval;
var fileName = req.url;
if (fileName === "/")
fileName = "/index.html";
// **** This is the route to send to firefox content script
if (fileName === "/fireFox") {
const buffer1 = [];
req.on('data', chunk => buffer1.push(chunk));
req.on('end', () => {
const data1 = Buffer.concat(buffer1);
if (sse_res != null)
sse_res.write("data: " + data1 + '\n\n');
console.log("data: " + data1);
// console.log(unescape(encodeURIComponent(data)));
});
res.end();
return; }
if (fileName === "/dreamland") {
const buffer1 = [];
req.on('data', chunk => buffer1.push(chunk));
req.on('end', () => {
const data1 = Buffer.concat(buffer1);
if (sse_res2 != null)
sse_res2.write("data: " + data1 + '\n\n');
console.log("dream: " + data1);
// console.log(unescape(encodeURIComponent(data)));
});
res.end();
return; }
if (fileName.startsWith("/saveChatLog/")) {
var logname = decodeURIComponent(path.basename(req.url));
res.writeHead(200, {
'Content-Type': 'text/event-stream',
});
const buffer2 = [];
req.on('data', chunk => buffer2.push(chunk));
req.on('end', () => {
// const data2 = unescape(Buffer.concat(buffer2));
const data2 = decodeURIComponent(Buffer.concat(buffer2));
// Save to file
var fs = require('fs');
var stream = fs.createWriteStream("./logs/" + logname);
stream.once('open', function(fd) {
stream.write(data2);
stream.end();
});
console.log(logname + " saved!");
// console.log("log data: " + data);
// console.log(unescape(encodeURIComponent(data)));
});
res.end();
return; }
// * from Javascript I get the pinyin sequence
// * do a shell escape to key in the sequence
// * return control to Javascript (which then extracts the HTML element from the Google input box)
if (fileName.startsWith("/keystrokes")) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
});
// req.setEncoding("utf8"); // This causes an error, seems chunk cannot be string
const buffer4 = [];
req.on('data', chunk => buffer4.push(chunk));
req.on('end', () => {
const data4 = Buffer.concat(buffer4);
const data4b = decodeURIComponent(data4).toString('utf8');
var exec = require('child_process').exec;
exec("./keystrokes-into-box.sh " + data4b,
function (error, stdout, stderr)
{ console.log(stdout); });
console.log("sent keystrokes: " + data4b);
// console.log("scraping data: " + data3b);
// console.log(unescape(encodeURIComponent(data3b)));
});
res.end();
return; }
if (fileName.startsWith("/speakMandarin")) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
});
// req.setEncoding("utf8"); // This causes an error, seems chunk cannot be string
const buffer3 = [];
req.on('data', chunk => buffer3.push(chunk));
req.on('end', () => {
const data3 = Buffer.concat(buffer3);
const data3b = decodeURIComponent(data3).toString('utf8');
var exec = require('child_process').exec;
exec("ekho " + data3b,
function (error, stdout, stderr)
{ console.log(stdout); });
console.log("Speak: " + data3b);
// console.log("log data: " + data3b);
// console.log(unescape(encodeURIComponent(data3b)));
});
res.end();
return; }
if (fileName.startsWith("/shellCommand")) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
});
const buffer4 = [];
req.on('data', chunk => buffer4.push(chunk));
req.on('end', () => {
const data4 = Buffer.concat(buffer4);
const data4b = decodeURIComponent(data4).toString('utf8');
var exec = require('child_process').exec;
exec(data4b,
function (error, stdout, stderr)
{ console.log(stdout); });
console.log("Shell command: " + data4b);
});
res.end();
return; }
if (fileName.startsWith("/speakCantonese")) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
});
// req.setEncoding("utf8"); // This causes an error, seems chunk cannot be string
const buffer5 = [];
req.on('data', chunk => buffer5.push(chunk));
req.on('end', () => {
const data5 = Buffer.concat(buffer5);
const data5b = decodeURIComponent(data5).toString('utf8');
var exec = require('child_process').exec;
exec("ekho -v Cantonese " + data5b,
function (error, stdout, stderr)
{ console.log(stdout); });
console.log("Speak: " + data5b);
// console.log("log data: " + data5b);
// console.log(unescape(encodeURIComponent(data5b)));
});
res.end();
return; }
if (fileName.startsWith("/saveDatabase/")) {
var filename = path.basename(url.parse(req.url).pathname);
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
});
const buffer4 = [];
req.on('data', chunk => buffer4.push(chunk));
req.on('end', () => {
const data4 = Buffer.concat(buffer4);
// Save to file
var fs = require('fs');
var stream = fs.createWriteStream("./web/" + filename, {encoding: 'utf8'});
stream.once('open', function(fd) {
stream.write(data4);
stream.end();
});
console.log(filename + " saved!");
// console.log("log data: " + data4);
// console.log(unescape(encodeURIComponent(data4)));
});
res.end();
return; }
if (fileName.startsWith("/loadDatabase/")) {
var dbName = path.basename(url.parse(req.url).pathname);
console.log("DB name = " + dbName);
res.writeHead(200, {
"Content-Type":"text/html",
"Cache-Control":"no-cache",
"Connection":"keep-alive"
});
fs = require('fs');
fs.readFile("./web/" + dbName, "utf-8", function (err, data) {
if (err) {
console.log(err)
res.writeHead(404);
res.end();
return;
}
res.writeHead(200, {"Content-Type": "text/html"});
res.end(data, "utf-8");
});
return; }
if (fileName.startsWith("/appendFile/")) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
});
const buffer5 = [];
req.on('data', chunk => buffer5.push(chunk));
req.on('end', () => {
const data5 = Buffer.concat(buffer5);
// Save to file
var fs = require('fs');
var stream = fs.appendFile("./web/scraped-Google.txt", data5, function (err) {
if (err)
throw err;
console.log("File appended!");
});
});
res.end();
return; }
fileName = "./web" + fileName;
fileTypes = {
".html" : ["text/html" , "utf-8"],
".js" : ["application/javascript" , "utf-8"],
".ogg" : ["audio/ogg" , "base64"],
".ico" : ["image/x-icon" , "base64"],
".jpg" : ["image/jpg" , "base64"],
".png" : ["image/png" , "base64"],
".gif" : ["image/gif" , "base64"],
};
for (var ext in fileTypes) {
if (fileName.endsWith(ext)) {
fs.exists(fileName, function(exists) {
if (exists) {
fs.readFile(fileName, fileTypes[ext][1], function(error, content) {
if (error) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, {"Content-Type": fileTypes[ext][0]});
res.end(content, fileTypes[ext][1]);
}
});
} else {
res.writeHead(404);
res.end();
}
});
return; }
}
// All failed:
res.writeHead(404);
res.end();
}
var s = http.createServer(reqHandler);
s.listen(8484, "127.0.0.1");
var s2 = http.createServer(reqHandler); // Seems redundant??
s2.listen(8585, "127.0.0.1");
// Beep sound to signify server is being started
var shell = require('child_process').exec;
shell("beep", function(err, stdout, stderr) {});
console.log("Servers running at http://127.0.0.1:8484/ and :8585/");