-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.js
884 lines (808 loc) · 27.6 KB
/
main.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
const oxoKeyPairs = require("oxo-keypairs")
//config
//const SelfURL = "ws://127.0.0.1:3000"
//standalone server
//const Seed = oxoKeyPairs.generateSeed("obeTvR9XDbUwquA6JPQhmbgaCCaiFa2rvf", 'secp256k1')
const SelfURL = "wss://ru.oxo-chat-server.com"
const Seed = "xxJTfMGZPavnqHhcEcHw5ToPCHftw"
const OtherServer = []
//interconnect servers
//const Seed = "xp1jB6s7H1WjXrpUSUHb3fv12Fdge"
//const OtherServer = [{ "URL": "ws://127.0.0.1:3333", "Address": "o5gVGxqPFCvzTAQ5BpMnwtS8xYvnXQDJoU" }]
//keep alive
process.on('uncaughtException', function (err) {
//打印出错误
console.log(err)
//打印出错误的调用栈方便调试
console.log(err.stack)
})
//json
const Schema = require('./schema.js')
function cloneJson(json) {
return JSON.parse(JSON.stringify(json))
}
function toSetUniq(arr) {
return Array.from(new Set(arr))
}
//ws
const WebSocket = require('ws')
//crypto
const Crypto = require('crypto')
function hasherSHA512(str) {
let sha512 = Crypto.createHash("sha512")
sha512.update(str)
return sha512.digest('hex')
}
function halfSHA512(str) {
return hasherSHA512(str).toUpperCase().substr(0, 64)
}
function quarterSHA512(str) {
return hasherSHA512(str).toUpperCase().substr(0, 32);
}
//oxo
function strToHex(str) {
let arr = []
let length = str.length
for (let i = 0; i < length; i++) {
arr[i] = (str.charCodeAt(i).toString(16))
}
return arr.join('').toUpperCase()
}
function sign(msg, sk) {
let msgHexStr = strToHex(msg)
let sig = oxoKeyPairs.sign(msgHexStr, sk)
return sig
}
function verifySignature(msg, sig, pk) {
let hexStrMsg = strToHex(msg)
try {
return oxoKeyPairs.verify(hexStrMsg, sig, pk)
} catch (e) {
return false
}
}
function VerifyJsonSignature(json) {
let sig = json["Signature"]
delete json["Signature"]
let tmpMsg = JSON.stringify(json)
if (verifySignature(tmpMsg, sig, json.PublicKey)) {
json["Signature"] = sig
return true
} else {
console.log('signature invalid...')
return false
}
}
let ActionCode = {
"Declare": 100,
"ObjectResponse": 101,
"BulletinRandom": 200,
"BulletinRequest": 201,
"BulletinFileRequest": 202,
"ChatDH": 301,
"ChatMessage": 302,
"ChatSync": 303,
"PrivateFileRequest": 304,
"GroupRequest": 401,
"GroupManageSync": 402,
"GroupDH": 403,
"GroupMessageSync": 404,
"GroupFileRequest": 405
}
//message
const MessageCode = {
"JsonSchemaInvalid": 0, //json schema invalid...
"SignatureInvalid": 1, //signature invalid...
"TimestampInvalid": 2, //timestamp invalid...
"BalanceInsufficient": 3, //balance insufficient...
"NewConnectionOpening": 4, //address changed...
"AddressChanged": 5, //new connection with same address is opening...
"ToSelfIsForbidden": 6, //To self is forbidden...
"ToNotExist": 7, //To not exist...
"GatewayDeclareSuccess": 1000 //gateway declare success...
}
const ObjectType = {
"Bulletin": 101,
"BulletinFile": 102,
"PrivateFile": 201,
"GroupManage": 301,
"GroupMessage": 302,
"GroupFile": 303
}
function strServerMessage(msgCode) {
msgJson = { "Action": ActionCode["ServerMessage"], "Code": msgCode }
return JSON.stringify(msgJson)
}
function sendServerMessage(ws, msgCode) {
ws.send(strServerMessage(msgCode))
}
//client connection
let ClientConns = {}
function fetchClientConnAddress(ws) {
for (let address in ClientConns) {
if (ClientConns[address] == ws) {
return address
}
}
return null
}
let ClientServer = null
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//client listener
function teminateClientConn(ws) {
ws.close()
let connAddress = fetchClientConnAddress(ws)
if (connAddress != null) {
console.log(`###################LOG################### client disconnect... <${connAddress}>`)
delete ClientConns[connAddress]
}
}
const sqlite3 = require('sqlite3')
let DB = null
let BulletinCount = 0
let PageSize = 10
let PageCount = BulletinCount / PageSize
let PageLinks = ''
let BulletinAccounts = []
function initDB() {
//建库:数据库名为账号地址
DB = new sqlite3.Database(`./cache.db`)
//建表
DB.serialize(() => {
//为账号地址起名
DB.run(`CREATE TABLE IF NOT EXISTS BULLETINS(
hash VARCHAR(32) PRIMARY KEY,
pre_hash VARCHAR(32),
next_hash VARCHAR(32),
address VARCHAR(35) NOT NULL,
sequence INTEGER NOT NULL,
content TEXT NOT NULL,
quote TEXT NOT NULL,
json TEXT NOT NULL,
signed_at INTEGER NOT NULL,
created_at INTEGER NOT NULL)`, err => {
if (err) {
console.log(err)
}
})
DB.run(`CREATE TABLE IF NOT EXISTS QUOTES(
main_hash VARCHAR(32) NOT NULL,
quote_hash VARCHAR(32) NOT NULL,
address VARCHAR(35) NOT NULL,
sequence INTEGER NOT NULL,
content TEXT NOT NULL,
signed_at INTEGER NOT NULL,
PRIMARY KEY ( main_hash, quote_hash ) )`, err => {
if (err) {
console.log(err)
}
})
})
let SQL = `SELECT * FROM BULLETINS ORDER BY created_at DESC`
DB.all(SQL, (err, items) => {
if (err) {
console.log(err)
} else {
BulletinCount = items.length
PageCount = BulletinCount / PageSize + 1
PageLinks = ''
let PageLinkArray = []
if (PageCount > 1) {
for (let i = 1; i <= PageCount; i++) {
PageLinkArray.push(`<a href="/bulletins?page=${i}">${i}</a>`)
}
PageLinks = PageLinkArray.join(' ')
}
}
})
SQL = `SELECT * FROM BULLETINS GROUP BY address`
DB.all(SQL, (err, items) => {
if (err) {
console.log(err)
} else {
for (let i = 0; i < items.length; i++) {
BulletinAccounts.push({ 'address': items[i].address, 'sequence': 0 })
}
}
})
}
initDB()
////////hard copy from client<<<<<<<<
const crypto = require("crypto")
const keypair = oxoKeyPairs.deriveKeypair(Seed)
const Address = oxoKeyPairs.deriveAddress(keypair.publicKey)
const PublicKey = keypair.publicKey
const PrivateKey = keypair.privateKey
function sign(msg, sk) {
let msgHexStr = strToHex(msg);
let sig = oxoKeyPairs.sign(msgHexStr, sk);
return sig;
}
function GenBulletinRequest(address, sequence, to) {
let json = {
"Action": ActionCode["BulletinRequest"],
"Address": address,
"Sequence": sequence,
"To": to,
"Timestamp": Date.now(),
"PublicKey": PublicKey
}
let sig = sign(JSON.stringify(json), PrivateKey)
json.Signature = sig
let strJson = JSON.stringify(json)
return strJson
}
function GenObjectResponse(object, to) {
let json = {
"Action": ActionCode.ObjectResponse,
"Object": object,
"To": to,
"Timestamp": Date.now(),
"PublicKey": PublicKey,
}
let sig = sign(JSON.stringify(json), PrivateKey)
json.Signature = sig
let strJson = JSON.stringify(json)
return strJson
}
function GenDeclare() {
//send declare to server
let json = {
"Action": ActionCode["Declare"],
"Timestamp": new Date().getTime(),
"PublicKey": PublicKey
}
let sig = sign(JSON.stringify(json), PrivateKey)
json.Signature = sig
let strJson = JSON.stringify(json)
return strJson
}
////////hard copy from client>>>>>>>>
function CacheBulletin(bulletin) {
let timestamp = Date.now()
let hash = quarterSHA512(JSON.stringify(bulletin))
let address = oxoKeyPairs.deriveAddress(bulletin.PublicKey)
let SQL = `INSERT INTO BULLETINS (hash, pre_hash, address, sequence, content, quote, json, signed_at, created_at)
VALUES ('${hash}', '${bulletin.PreHash}', '${address}', '${bulletin.Sequence}', '${bulletin.Content}', '${JSON.stringify(bulletin.Quote)}', '${JSON.stringify(bulletin)}', ${bulletin.Timestamp}, ${timestamp})`
DB.run(SQL, err => {
if (err) {
console.log(err)
} else {
BulletinCount = BulletinCount + 1
PageCount = BulletinCount / PageSize + 1
PageLinks = ''
let PageLinkArray = []
if (PageCount > 1) {
for (let i = 1; i <= PageCount; i++) {
PageLinkArray.push(`<a href="/bulletins?page=${i}">${i}</a>`)
}
PageLinks = PageLinkArray.join(' ')
}
//update account sequence
for (let i = 0; i < BulletinAccounts.length; i++) {
if (BulletinAccounts[i].address == address && BulletinAccounts[i].sequence < bulletin.sequence) {
BulletinAccounts[i].sequence = bulletin.sequence
}
}
//update pre_bulletin's next_hash
SQL = `UPDATE BULLETINS SET next_hash = '${hash}' WHERE hash = "${bulletin.PreHash}"`
DB.run(SQL, (err) => {
if (err) {
console.log(err)
}
})
//update quote
bulletin.Quote.forEach(quote => {
SQL = `INSERT INTO QUOTES (main_hash, quote_hash, address, sequence, content, signed_at)
VALUES ('${quote.Hash}', '${hash}', '${address}', '${bulletin.Sequence}', '${bulletin.Content}', ${bulletin.Timestamp})`
DB.run(SQL, (err) => {
if (err) {
console.log(err)
}
})
});
//Brocdcast to OtherServer
for (let i in OtherServer) {
let ws = ClientConns[OtherServer[i]["Address"]]
if (ws != undefined && ws.readyState == WebSocket.OPEN) {
ws.send(GenObjectResponse(bulletin, OtherServer[i]["Address"]))
}
}
}
})
}
function handleClientMessage(message, json) {
if (json["To"] != null && ClientConns[json["To"]] != null && ClientConns[json["To"]].readyState == WebSocket.OPEN) {
//forward message
ClientConns[json["To"]].send(message)
//cache bulletin
if (json["Action"] == ActionCode["ObjectResponse"] && json["Object"]["ObjectType"] == ObjectType["Bulletin"]) {
//console.log(`###################LOG################### Client Message:`)
//console.log(message)
CacheBulletin(json["Object"])
}
}
if (json["Action"] == ActionCode["BulletinRequest"]) {
//send cache bulletin
let SQL = `SELECT * FROM BULLETINS WHERE address = "${json["Address"]}" AND sequence = "${json["Sequence"]}"`
DB.get(SQL, (err, item) => {
if (err) {
console.log(err)
} else {
if (item != null) {
let address = oxoKeyPairs.deriveAddress(json["PublicKey"])
ClientConns[address].send(item.json)
}
}
})
} else if (json["Action"] == ActionCode["BulletinRandom"]) {
console.log("=====================random")
//send random bulletin
let SQL = `SELECT * FROM BULLETINS ORDER BY RANDOM() LIMIT 1`
DB.get(SQL, (err, item) => {
if (err) {
console.log(err)
} else {
if (item != null) {
let address = oxoKeyPairs.deriveAddress(json["PublicKey"])
ClientConns[address].send(item.json)
}
}
})
} else if (json["To"] == Address && json["Action"] == ActionCode["ObjectResponse"] && json["Object"]["ObjectType"] == ObjectType["Bulletin"]) {
CacheBulletin(json["Object"])
//fetch more bulletin
let address = oxoKeyPairs.deriveAddress(json["Object"].PublicKey)
if (ClientConns[address] != null && ClientConns[address].readyState == WebSocket.OPEN) {
let msg = GenBulletinRequest(address, json["Object"].Sequence + 1, address)
ClientConns[address].send(msg)
}
}
}
function checkClientMessage(ws, message) {
console.log(`###################LOG################### Client Message:`)
console.log(`${message}`)
let json = Schema.checkClientSchema(message)
if (json == false) {
//json格式不合法
sendServerMessage(ws, MessageCode["JsonSchemaInvalid"])
// console.log(`json格式不合法`)
teminateClientConn(ws)
} else {
let address = oxoKeyPairs.deriveAddress(json["PublicKey"])
if (ClientConns[address] == ws) {
//连接已经通过"声明消息"校验过签名
handleClientMessage(message, json)
} else {
let connAddress = fetchClientConnAddress(ws)
if (connAddress != null && connAddress != address) {
//using different address in same connection
sendServerMessage(ws, MessageCode["AddressChanged"])
teminateClientConn(ws)
} else {
if (!VerifyJsonSignature(json)) {
//"声明消息"签名不合法
sendServerMessage(ws, MessageCode["SignatureInvalid"])
teminateClientConn(ws)
return
}
if (json.Timestamp + 60000 < Date.now()) {
//"声明消息"生成时间过早
sendServerMessage(ws, MessageCode["TimestampInvalid"])
teminateClientConn(ws)
return
}
if (connAddress == null && ClientConns[address] == null) {
//new connection and new address
//当前连接无对应地址,当前地址无对应连接,全新连接
console.log(`connection established from client <${address}>`)
ClientConns[address] = ws
//handleClientMessage(message, json)
let SQL = `SELECT * FROM BULLETINS WHERE address = "${address}" ORDER BY sequence DESC`
DB.get(SQL, (err, item) => {
if (err) {
console.log(err)
} else {
let sequence = 1
if (item != null) {
sequence = item.sequence + 1
}
let msg = GenBulletinRequest(address, sequence, address)
ClientConns[address].send(msg)
}
})
} else if (ClientConns[address] != ws && ClientConns[address].readyState == WebSocket.OPEN) {
//new connection kick old conection with same address
//当前地址有对应连接,断开旧连接,当前地址对应到当前连接
sendServerMessage(ClientConns[address], MessageCode["NewConnectionOpening"])
ClientConns[address].close()
ClientConns[address] = ws
//handleClientMessage(message, json)
} else {
ws.send("WTF...")
teminateClientConn(ws)
}
}
}
}
}
function startClientServer() {
if (ClientServer == null) {
ClientServer = new WebSocket.Server({
port: 3000, //to bind on 80, must use 'sudo node main.js'
clientTracking: true,
maxPayload: 512 * 1024
})
ClientServer.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
checkClientMessage(ws, message)
})
ws.on('close', function close() {
let connAddress = fetchClientConnAddress(ws)
if (connAddress != null) {
console.log(`client <${connAddress}> disconnect...`)
delete ClientConns[connAddress]
}
})
})
}
}
startClientServer()
function keepOtherServerConn() {
let notConnected = []
for (let i in OtherServer) {
if (ClientConns[OtherServer[i]["Address"]] == undefined) {
notConnected.push(OtherServer[i])
}
}
if (notConnected.length == 0) {
return
}
let random = Math.floor(Math.random() * (notConnected.length))
let randomServerUrl = notConnected[random]["URL"]
if (randomServerUrl != null) {
console.log(`keepOtherServerConn connecting to StaticCounter ${randomServerUrl}`)
try {
var ws = new WebSocket(randomServerUrl)
ws.on('open', function open() {
ws.send(GenDeclare())
ClientConns[notConnected[random]["Address"]] = ws
})
ws.on('message', function incoming(message) {
checkClientMessage(ws, message)
})
ws.on('close', function close() {
let connAddress = fetchClientConnAddress(ws)
if (connAddress != null) {
console.log(`client <${connAddress}> disconnect...`)
delete ClientConns[connAddress]
}
})
} catch (e) {
console.log('keepOtherServerConn error...')
}
}
}
let OtherServerConnJob = null
if (OtherServerConnJob == null) {
OtherServerConnJob = setInterval(keepOtherServerConn, 5000);
}
//start web server
const http = require('http')
const url = require("url")
const bulletins_reg = /^\/bulletins\?page=\d+/
const bulletin_reg = /^\/bulletin\/[0123456789ABCDEF]{32}$/
const bulletin_json_reg = /^\/bulletin\/[0123456789ABCDEF]{32}\/json$/
const account_bulletins_reg = /^\/account\/o[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{32,33}\/bulletins/
const account = /^o[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{32,33}\//
function add0(m) { return m < 10 ? '0' + m : m }
function timestamp_format(timestamp) {
var time = new Date(timestamp);
var y = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}
http.createServer(function (request, response) {
let path = url.parse(request.url).path;
if (path == "/") {
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(`
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>oxo-chat-server</title>
</head>
<body bgcolor="#8FBC8F">
<h1><a href="/bulletins">公告列表</a></h1>
<h1><a href="/accounts">作者列表</a></h1>
<h2><a href="https://github.com/oxogenesis/oxo-chat-server#deploy-with-ssl-nginx-pm2">自建/搭建本站教程</a></h2>
<h2><a href="https://github.com/oxogenesis/oxo-chat-app/releases">App下载(on android推荐)</a></h2>
<h2><a href="https://github.com/oxogenesis/oxo-chat-client/releases">Client下载(electron on windows不推荐)</a></h2>
<h2>本站服务地址:${SelfURL}</h2>
<h2>本站服务账号:${Address}</h2>
<h3>{"URL": "${SelfURL}", "Address": "${Address}"}</h3>
</body>
</html>
`);
response.end();
} else if (path == "/bulletins" || bulletins_reg.test(path)) {
let page = 1
if (path != "/bulletins") {
page = ~~path.replace(/^\/bulletins\?page=/, '')
}
let SQL = `SELECT * FROM BULLETINS ORDER BY created_at DESC LIMIT ${PageSize} OFFSET ${(page - 1) * PageSize}`
DB.all(SQL, (err, bulletins) => {
if (err) {
console.log(err)
} else {
let trs = ''
bulletins.forEach(bulletin => {
let title = bulletin.content.slice(0, 32).trim()
trs = trs +
`<tr>
<td><a href="/account/${bulletin.address}/bulletins">${bulletin.address}</a></td>
<td>${bulletin.sequence}</td>
<td><a href="/bulletin/${bulletin.hash}">${title}</a></td>
<td>${timestamp_format(bulletin.created_at)}</td>
</tr>`
})
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(`
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>oxo-chat-server</title>
</head>
<body bgcolor="#8FBC8F">
<h1><a href="/">首页</a></h1>
<h1><a href="/bulletins">公告列表</a></h1>
<table border="1">
<tr>
<th>作者</th>
<th>序号</th>
<th>标题</th>
<th>时间</th>
</tr>
${trs}
</table>
${PageLinks}
</body>
</html>
`);
response.end();
}
})
} else if (bulletin_reg.test(path)) {
let hash = path.replace(/^\/bulletin\//, '')
let SQL = `SELECT * FROM BULLETINS WHERE hash = "${hash}"`
DB.get(SQL, (err, item) => {
if (err) {
console.log(err)
} else {
if (item == null) {
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(`
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>oxo-chat-server</title>
</head>
<body bgcolor="#8FBC8F">
<h1><a href="/">首页</a></h1>
<h1><a href="/bulletins">公告列表</a></h1>
<h1>Bulletin#${hash}</h1>
<h1>未被缓存...</h1>
</body>
</html>
`)
response.end();
} else {
let content = item.content.replace(/\n/g, '<br>')
let quote = ''
let quotes = JSON.parse(item.quote)
if (quotes.length != '') {
quote = '<h3>引用</h3><ul>'
for (let i = quotes.length - 1; i >= 0; i--) {
quote = quote + `<li><a href="/bulletin/${quotes[i].Hash}">${quotes[i].Address}#${quotes[i].Sequence}</a></li>`
}
quote = quote + '</ul><hr>'
}
let pre_bulletin = ''
if (item.pre_hash != 'F4C2EB8A3EBFC7B6D81676D79F928D0E') {
pre_bulletin = `<h3><a href="/bulletin/${item.pre_hash}">上一篇</a></h3>`
}
let next_bulletin = ""
if (item.next_hash != null) {
next_bulletin = `<h3><a href="/bulletin/${item.next_hash}">下一篇</a></h3>`
}
SQL = `SELECT * FROM QUOTES WHERE main_hash = "${hash}" ORDER BY signed_at ASC`
DB.all(SQL, (err, is) => {
if (err) {
console.log(err)
} else {
let replys = ''
let floor = 1
is.forEach(i => {
replys = replys + `<hr>
<h4>#${floor} 发布@${timestamp_format(i.signed_at)}</h4>
<h4><a href="/bulletin/${i.quote_hash}">${i.address}#${i.sequence}</a></h4>
<h4>${i.content}</h4>`
floor = floor + 1
});
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(`
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>oxo-chat-server</title>
</head>
<body bgcolor="#8FBC8F">
<h1><a href="/">首页</a></h1>
<h1><a href="/bulletins">公告列表</a></h1>
<h1>Bulletin#${hash}</h1>
${quote}
<h3><a href="/account/${item.address}/bulletins">${item.address}</a>
<a href="/bulletin/${hash}/json">#${item.sequence}</a></h3>
<h3> 发布@${timestamp_format(item.signed_at)}</h3>
${pre_bulletin}${next_bulletin}
<h3>${content}</h3>
${replys}
</body>
</html>
`);
response.end();
}
})
}
}
})
} else if (path == "/accounts") {
let trs = ''
for (let i = 0; i < BulletinAccounts.length; i++) {
trs = trs +
`<tr>
<td><a href="/account/${BulletinAccounts[i].address}/bulletins">${BulletinAccounts[i].address}</a></td>
<td>${BulletinAccounts[i].sequence}</td>
</tr>`
}
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(`
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>oxo-chat-server</title>
</head>
<body bgcolor="#8FBC8F">
<h1><a href="/">首页</a></h1>
<h1><a href="/accounts">作者列表</a></h1>
<table border="1">
<tr>
<th>作者</th>
<th>公告数量</th>
</tr>
${trs}
</table>
</body>
</html>
`);
response.end();
} else if (account_bulletins_reg.test(path)) {
let address = path.replace('/account/', '')
address = address.replace('/bulletins', '')
let SQL = `SELECT * FROM BULLETINS WHERE address = '${address}' ORDER BY sequence DESC`
DB.all(SQL, (err, bulletins) => {
if (err) {
console.log(err)
} else {
//update account sequence
let sequence = 0
if (bulletins.length > 0) {
sequence = bulletins[0].sequence
}
for (let i = 0; i < BulletinAccounts.length; i++) {
if (BulletinAccounts[i].address == address && BulletinAccounts[i].sequence < sequence) {
BulletinAccounts[i].sequence = sequence
}
}
let trs = ''
bulletins.forEach(bulletin => {
let title = bulletin.content.slice(0, 32).trim()
trs = trs +
`<tr>
<td>${bulletin.address}</td>
<td>${bulletin.sequence}</td>
<td><a href="/bulletin/${bulletin.hash}">${title}</a></td>
<td>${timestamp_format(bulletin.created_at)}</td>
</tr>`
})
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(`
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>oxo-chat-server</title>
</head>
<body bgcolor="#8FBC8F">
<h1><a href="/">首页</a></h1>
<h1><a href="/accounts">作者列表</a></h1>
<table border="1">
<tr>
<th>作者</th>
<th>序号</th>
<th>标题</th>
<th>时间</th>
</tr>
${trs}
</table>
</body>
</html>
`);
response.end();
}
})
} else if (bulletin_json_reg.test(path)) {
let hash = path.replace(/^\/bulletin\//, '')
hash = hash.replace(/\/json/, '')
let SQL = `SELECT * FROM BULLETINS WHERE hash = "${hash}"`
DB.get(SQL, (err, item) => {
if (err) {
console.log(err)
} else {
if (item == null) {
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(`
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>oxo-chat-server</title>
</head>
<body bgcolor="#8FBC8F">
<h1><a href="/bulletins">公告列表</a></h1>
<h1>Bulletin#${hash}</h1>
<h1>未被缓存...</h1>
</body>
</html>
`)
response.end();
} else {
response.writeHeader(200, {
"Content-Type": "application/json; charset=utf-8"
});
response.write(`${item.json}`);
response.end();
}
}
})
} else {
response.writeHeader(404, {
"Content-Type": "text/html"
});
response.end();
}
})
.listen(8000);