-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathteletextserver.js
More file actions
1169 lines (966 loc) · 32.1 KB
/
teletextserver.js
File metadata and controls
1169 lines (966 loc) · 32.1 KB
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs')
const readline = require('readline')
const path = require('path')
const { URL } = require('url')
const http = require('http')
const https = require('https')
const parseUrl = require('parseurl')
const express = require('express')
const nunjucks = require('nunjucks')
// socket.io documentation is helpful: https://socket.io/docs/emit-cheatsheet/
//const socket = require('socket.io')
const { Server } = require('socket.io');
// import constants and config for use server-side
const CONST = require('./constants.js')
const CONFIG = require('./config.js')
// import package.json so we can get the current version
const PACKAGE_JSON = require('./package.json')
// import logger
const LOG = require('./log.js')
let subPage = -1 // Used in doLoad to ensure that subpage numbers are logical
function renderLogo (includeEndBlankLine = false) {
// determine logo char array length
const logoCharLength = CONFIG[CONST.CONFIG.CONSOLE_LOGO_CHAR_ARRAY].reduce(
(previousValue, currentValue) => {
return Math.max(
(typeof previousValue === 'string')
? previousValue.length
: previousValue,
currentValue.length
)
}
)
let str = ''
// output logo char array lines
str += ''.padStart(logoCharLength) + '\n'
for (const i in CONFIG[CONST.CONFIG.CONSOLE_LOGO_CHAR_ARRAY]) {
str += CONFIG[CONST.CONFIG.CONSOLE_LOGO_CHAR_ARRAY][i] + '\n'
}
// include current version under the logo
const versionString = 'v' + PACKAGE_JSON.version
str += ''.padStart(logoCharLength - versionString.length) + versionString + '\n'
if (includeEndBlankLine) {
str += ''.padStart(logoCharLength) + '\n'
}
return str
}
// output logo in console?
if (CONFIG[CONST.CONFIG.SHOW_CONSOLE_LOGO] === true) {
// output logo char array lines to console
console.log(
renderLogo(true)
)
}
// output basic server information
LOG.fn(
null,
[
`Server is running on ${process.platform}`,
`Serving service page files from ${CONFIG[CONST.CONFIG.SERVICE_PAGES_SERVE_DIR]}`
],
LOG.LOG_LEVEL_MANDATORY
)
// import modules
require('./weather.js') // Should check if this is obsolete
require('./service.js')
require('./utils.js') // Prestel and other string handling
require('./keystroke.js') // Editing data from clients
// list of services
const services = []
// instantiate Express app
const app = express()
// instantiate Nunjucks templating system
const env = nunjucks.configure(
'html',
{
autoescape: true,
express: app
}
)
app.set('view engine', 'html')
// For Express apps on ports 3000, 3001, 8080
app.set('trust proxy', true);
// This makes req.protocol return 'https' when X-Forwarded-Proto is set
env.addFilter(
'featureEnabled',
function (features, featureName) {
return (features && (features[featureName] === true))
}
)
env.addFilter(
'isArray',
function (obj) {
return Array.isArray(obj)
}
)
// define shared template variables
const templateVars = {
IS_DEV: CONFIG[CONST.CONFIG.IS_DEV],
TITLE: CONFIG[CONST.CONFIG.TITLE]
}
if (CONFIG[CONST.CONFIG.SERVICES_AVAILABLE]) {
templateVars.SERVICES_AVAILABLE = {}
// process non-group services
for (const serviceName in CONFIG[CONST.CONFIG.SERVICES_AVAILABLE]) {
const serviceData = CONFIG[CONST.CONFIG.SERVICES_AVAILABLE][serviceName]
if (!serviceData.group) {
templateVars.SERVICES_AVAILABLE[serviceName] = serviceData
}
}
// process service groups...
const serviceGroups = {}
for (const serviceName in CONFIG[CONST.CONFIG.SERVICES_AVAILABLE]) {
const serviceData = CONFIG[CONST.CONFIG.SERVICES_AVAILABLE][serviceName]
const groupName = serviceData.group
if (groupName) {
if (typeof serviceGroups[groupName] !== 'object') {
serviceGroups[groupName] = []
}
serviceData.id = serviceName
serviceGroups[groupName].push(serviceData)
}
}
// add service groups at end of services list
templateVars.SERVICES_AVAILABLE = {
...templateVars.SERVICES_AVAILABLE,
...serviceGroups
}
}
if (CONFIG[CONST.CONFIG.SHOW_CONSOLE_LOGO] === true) {
templateVars.LOGO_CHARS = renderLogo()
}
// read in logo SVG to pass into the template
try {
templateVars.LOGO_SVG = fs.readFileSync(CONFIG[CONST.CONFIG.LOGO_SVG_PATH])
} catch (e) { }
// define app routes
app.use(
'/constants.js',
function (req, res) {
res.sendFile(
path.join(__dirname, '/constants.js')
)
}
)
app.use(
'/config.js',
function (req, res) {
// only generate line for config keys we have explicitly whitelisted in config.js
const content = {}
for (const key in CONFIG) {
if (CONFIG[CONST.CONFIG.FRONTEND_CONFIG_KEYS].includes(key)) {
const configKeyData = CONFIG[key]
// further modify / filter this config key's data?
if (key === CONST.CONFIG.SERVICES_AVAILABLE) {
for (const i in configKeyData) {
configKeyData[i] = {
name: configKeyData[i].name,
headerTitle: configKeyData[i].headerTitle,
url: configKeyData[i].url,
port: configKeyData[i].port,
secondsSeparator: configKeyData[i].secondsSeparator || false,
forceServiceHeader: configKeyData[i].forceServiceHeader || false,
isEditable: configKeyData[i].isEditable || false,
credit: configKeyData[i].credit
}
}
}
content[key] = configKeyData
}
}
const output = 'const CONFIG = ' + JSON.stringify(content) + ';'
res.send(
output
)
}
)
app.use(
'/manifest.json',
function (req, res) {
let output = {}
try {
const searchParams = new URLSearchParams(parseUrl(req).search)
const service = searchParams.get('service')
// deep clone before modification
output = JSON.parse(
JSON.stringify(
loadServiceManifest(service)
)
)
// only output relevant page object keys...
if (typeof output.pages === 'object') {
const pages = {}
for (const pageNumber in output.pages) {
// skip non-numeric page numbers
if (/[A-F]+/i.test(pageNumber)) {
continue
}
pages[pageNumber] = {
p: output.pages[pageNumber].p
}
if (output.pages[pageNumber].d) {
pages[pageNumber].d = output.pages[pageNumber].d
}
}
output.pages = pages
}
} catch (e) { }
res.setHeader('Content-Type', 'application/json')
res.send(
JSON.stringify(output)
)
}
)
app.use(
'/pages',
function (req, res) {
res.sendFile(
path.join(
CONFIG[CONST.CONFIG.SERVICE_PAGES_SERVE_DIR],
parseUrl(req).path
)
)
}
)
app.use(
express.static(path.join(__dirname, '/public'))
)
app.use(
'*',
function (req, res) {
const customTemplateVars = {
...templateVars
}
// read in zapper SVG's to pass into the template
try {
customTemplateVars.ZAPPER_STANDARD_SVG = fs.readFileSync(CONFIG[CONST.CONFIG.ZAPPER_STANDARD_SVG_PATH])
customTemplateVars.ZAPPER_COMPACT_SVG = fs.readFileSync(CONFIG[CONST.CONFIG.ZAPPER_COMPACT_SVG_PATH])
} catch (e) { }
res.render(
'index.html',
customTemplateVars
)
}
)
// serve over HTTP?
let serverHttp
if (CONFIG.TELETEXT_VIEWER_SERVE_HTTP) {
serverHttp = http.createServer(app).listen(
CONFIG.TELETEXT_VIEWER_SERVE_HTTP_PORT
)
LOG.fn(
null,
`Serving on port ${CONFIG.TELETEXT_VIEWER_SERVE_HTTP_PORT}`,
LOG.LOG_LEVEL_MANDATORY
)
}
// serve over HTTPS?
let serverHttps
if (CONFIG.TELETEXT_VIEWER_SERVE_HTTPS) {
// read in key and cert files
const options = {
key: fs.readFileSync(CONFIG[CONST.CONFIG.TELETEXT_VIEWER_SERVE_HTTPS_KEY_PATH]),
cert: fs.readFileSync(CONFIG[CONST.CONFIG.TELETEXT_VIEWER_SERVE_HTTPS_CERT_PATH])
}
serverHttps = https.createServer(options, app).listen(
CONFIG.TELETEXT_VIEWER_SERVE_HTTPS_PORT
)
LOG.fn(
null,
`Serving on port ${CONFIG.TELETEXT_VIEWER_SERVE_HTTPS_PORT}`,
LOG.LOG_LEVEL_MANDATORY
)
}
LOG.blank()
// instantiate socket.io server
const io = new Server(
(CONFIG.TELETEXT_VIEWER_SERVE_HTTPS)
? serverHttps
: serverHttp,
{
handlePreflightRequest: (req, res) => {
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST',
'Referrer-Policy': 'no-referrer-when-downgrade'
})
res.end()
},
cors: {
origin: "https://www.xenoxxx.com",
credentials: true
}
}
)
io.sockets.on('connection', newConnection)
// instantiate keystroke class
const keystroke = new KeyStroke()
// instantiate Weather module
const weather = new Weather(doLoad)
app.get(
'/weather.tti',
weather.doLoadWeather
)
let initialPage
// Associative array links user id to service: connectionList['/#NODc31jxxFTSm_SaAAAC']=CONST.SERVICE_DIGITISER
const connectionList = {}
let missingPage = 0
const serviceManifests = {}
function autosave () {
if (keystroke.saveEdits()) {
LOG.fn(
['teletextserver', 'autosave'],
'Autosave',
LOG.LOG_LEVEL_VERBOSE
)
}
}
function keyMessage (data) {
// socket.broadcast.emit('keystroke', data) // To all but sender
io.emit('keystroke', data) // To everyone
// Also send this keymessage to our pages
// Or maybe to our services who can then switch the message as needed?
for (let i = 0; i < services.length; i++) {
services[i].keyMessage(data)
}
// Temporary hack. Use ] to trigger the writeback mechanism.
if (data.k === ']') {
keystroke.saveEdits()
} else {
keystroke.addEvent(data)
}
}
function loadServiceManifest (service) {
if (!serviceManifests[service]) {
const serviceManifestFile = path.join(
CONFIG[CONST.CONFIG.SERVICE_PAGES_SERVE_DIR],
service,
'manifest.json'
)
try {
serviceManifests[service] = JSON.parse(
fs.readFileSync(serviceManifestFile)
)
} catch (e) { }
}
return serviceManifests[service]
}
function newConnection (socket) {
// check if request IP address is banned (in config.js)
const clientIp = socket.request.connection.remoteAddress
if (CONFIG.BANNED_IP_ADDRESSES.includes(clientIp)) {
return
}
if ( typeof socket.handshake.headers.referer === 'undefined') {
return
}
// determine parameters from socket URL
console.log("[teletextServer::newConnection] clientIp="+clientIp)
console.log(socket.handshake.headers.referer)
const viewerUrl = new URL(socket.handshake.headers.referer)
const viewerSearchParams = new URLSearchParams(viewerUrl.search)
const socketUrl = new URL(socket.handshake.url, 'http://example.com')
const socketSearchParams = new URLSearchParams(socketUrl.search)
let service = socketSearchParams.get('service')
const page = viewerSearchParams.get('page')
// ensure service name is valid
const servicesData = CONFIG[CONST.CONFIG.SERVICES_AVAILABLE]
if (!service || !servicesData[service]) {
service = CONFIG[CONST.CONFIG.DEFAULT_SERVICE]
}
// register that this user is linked to this service
connectionList[socket.id] = service
LOG.fn(
['teletextserver', 'newConnection'],
`service=${service}, page=${page}, requested service was=${socketSearchParams.get('service')} socket.handshake.url=${socket.handshake.url}`,
LOG.LOG_LEVEL_VERBOSE
)
// set default page number if none supplied
let p
if (page === undefined) {
p = CONST.PAGE_MIN
} else {
p = parseInt(`0x${page}`, 16)
}
// If there is no page=nnn in the URL then default to CONST.PAGE_MIN
if ((p >= CONST.PAGE_MIN) && (p <= CONST.PAGE_MAX)) {
initialPage = p
const data = {
p: initialPage,
S: service
}
io.sockets.emit('setpage', data)
} else {
initialPage = CONST.PAGE_MIN
}
LOG.fn(
['teletextserver', 'newConnection'],
`socket.id=${socket.id}`,
LOG.LOG_LEVEL_INFO
)
// Send the socket id back. If a message comes in with this socket we know where to send the setpage to.
socket.emit('id', socket.id)
// Set up handlers for this socket
socket.on('keystroke', keyMessage)
socket.on('load', doLoad)
socket.on('initialLoad', doInitialLoad)
socket.on('create', doCreate)
socket.on('clearPage', doClearPage)
socket.on('deleteSubpage', doDeleteSubPage)
socket.on('description', doSetDescription)
socket.on('x28f1', doX28f1)
socket.on('fastext', doFastext)
// When this connection closes we remove the connection id
socket.on('disconnect', function () {
delete connectionList[socket.id]
})
// for editable services...
if (service && servicesData[service] && servicesData[service].isEditable) {
LOG.fn(
['teletextserver', 'newConnection'],
`This service is editable, service=${service}`,
LOG.LOG_LEVEL_VERBOSE
)
// ...every minute autosave the edits
setInterval(
autosave,
((CONFIG[CONST.CONFIG.DEFAULT_AUTOSAVE_INTERVAL] || 60) * 1000)
)
}
}
/** Set the description field
*/
function doSetDescription (data) {
LOG.fn(
['teletextserver', 'doSetDescription'],
[
`Setting description = ${data.desc}` ,
` keyMessage S=${data.S}, p=${data.p}, s=${data.s}`
],
LOG.LOG_LEVEL_VERBOSE
)
const txt = {
S: data.S, // service number
p: data.p, // page number
s: 0, // sub page
k: data.desc, // description text
x: CONST.SIGNAL_DESCRIPTION_CHANGE, // flag to set the description
y: 0,
id: data.id
}
keystroke.addEvent(txt)
// Broadcast the changed description to all listeners
// [!] @TODO
}
/** Delete the subpage s
*/
function doDeleteSubPage( data ) {
LOG.fn(
['teletextserver', 'doDeleteSubPage'],
[
`Setting description = ${data.desc}` ,
` keyMessage S=${data.S}, p=${data.p}, s=${data.s}`
],
LOG.LOG_LEVEL_VERBOSE
)
// could check that x === CONST.SIGNAL_DELETE_SUBPAGE
keystroke.addEvent(data)
}
/** Clear the current page to blank
* First write out a blank page, then load it in
*/
function doClearPage (data) {
LOG.fn(
['teletextserver', 'doClearPage'],
[
`Clearing page=${data.p.toString(16)}`,
`keyMessage S=${data.S}, p=${data.p}, s=${data.s}`
],
LOG.LOG_LEVEL_VERBOSE
)
// Write the blank page in the same way as createPage()
createBlankPage(data,
function() {
doLoad(data)
}
)
// @todo Remove clearPage from keystroke
// clearPage is very inefficient and doesn't always work correctly.
// keystroke.clearPage(data) // Clear the page
// This is done by doLoad()
// io.sockets.emit('blank', data) // Clear down old data on the clients
}
/** Create the page and load it
*/
function doCreate (data) {
LOG.fn(
['teletextserver', 'doCreate'],
`Creating page=${data.p.toString(16)}`,
LOG.LOG_LEVEL_VERBOSE
)
// Create a page from template
createPage(
data,
function () {
doLoad(data)
}
)
}
function doInitialLoad (data) {
LOG.fn(
['teletextserver', 'doInitialLoad'],
'',
LOG.LOG_LEVEL_VERBOSE
)
data.p = parseInt(initialPage)
doLoad(data)
}
/** doX28f1 - Update X28 configuration from the client
* Adds this as a keyevent to update the tti file with a new OL,28 packet
* Returns this message to update any clients viewing the same page
* @param data - X28F1 settings wrapped up in a keyevent message
*/
function doX28f1(data) {
// Data returned from X28F1 properties editor
console.log("Message from client:\n" + JSON.stringify(data, null, 4));
// let ol28 = EncodeOL28(data.X28F1)
// @todo Format this into a .tti packet OL,28
// @todo Update the OL,28 in the .tti file
keystroke.addEvent(data) // probably some form of keystroke event
// @todo Send the update to any clients looking at the same page
}
/** doFastext - Update the fastext links for this page
*
*/
function doFastext(data) {
// Add a fastext event
LOG.fn(
['teletextserver', 'doFastext'],
'Got fastext event',
LOG.LOG_LEVEL_VERBOSE
)
// broadcast to clients
io.sockets.emit('fastext', data) // [!] Probably want to do this later but I guess it can't hurt
// And stack it for replay
keystroke.addEvent(data)
}
function processServicePageLine (serviceData, data, line) {
let ix
let row
if (line.indexOf('PN') === 0) {
// [!] @todo The PN page must match the actual page number and not inadvertently get set to page 100
// @todo: Need to implement carousels
data.line = line.substring(6) // [!] @todo Don't know why we set line to the subpage. Should we delete this?
// [!] todo: If not greater than the last subpage, set to one greater than the last subpage
data.s = Number(line.substring(6))
io.sockets.emit('subpage', data)
console.log(data)
} else if (line.indexOf('DE,') === 0) { // Detect a description row
data.desc = line.substring(3)
// if page has page not found signal set, append the failed page number to the page description display
if (data.x === CONST.SIGNAL_PAGE_NOT_FOUND) {
missingPage = data.p.toString(16)
data.desc += ` - page ${missingPage}`
// Save the file not found flag for when we create the fastext links
data.fnf = CONST.SIGNAL_PAGE_NOT_FOUND // enable creating a new page
}
io.sockets.emit('description', data)
LOG.fn(
['teletextserver', 'processServicePageLine'],
`Sending desc=${data.desc}`,
LOG.LOG_LEVEL_VERBOSE
)
} else if (line.indexOf('LK,') === 0) { // Detect a Locked page
LOG.fn(
['teletextserver', 'locked'],
`page is locked`,
LOG.LOG_LEVEL_VERBOSE
)
io.sockets.emit('locked', data)
} else if (line.indexOf('FL,') === 0) { // Detect a Fastext link
let ch
ix = 3
data.fastext = [0x8ff,0x8ff,0x8ff,0x8ff,0x8ff,0x100]
console.log('FL line = "' + line +'"')
for (let link = 0; link < 6; link++) { // Check that we are sending out ALL the links correctly
let flink = ''
for (ch = line.charAt(ix++); ch !== ',' && ch !==' ' && ix < line.length;) {
flink = flink + ch
ch = line.charAt(ix++)
}
console.log(`flink[${link}] = ${flink}`)
data.fastext[link] = flink
}
// if page has page not found signal set...
if (typeof data.fnf != "undefined" && data.fnf === CONST.SIGNAL_PAGE_NOT_FOUND) {
// ...and service is editable, change the yellow fastext link to allow creating of a new page at this page number
if (serviceData && serviceData.isEditable) {
data.fastext[2] = `1${missingPage}`
}
}
io.sockets.emit('fastext', data)
return data
} else if (line.indexOf('CT,') === 0) { // Counter timer
// [!] Hack: Send the time in Fastext[0]
const tokens = line.split(',') // Token[2] is C or T and is not currently used
data.fastext = []
data.fastext[0] = parseInt(tokens[1])
io.sockets.emit('timer', data)
return data
} else if (line.indexOf('OL,') === 0) { // Detect a teletext row
const arr = (new RegExp(/^[0-9]{1,2}/)).exec(line.slice(3, 5))
row = parseInt(arr[0], 10)
ix = (4 + arr[0].length)
} else if (line.indexOf('PS') === 0) { // Page control bits
// @todo Need to get the language bits out of the PS command
// and integrate it with X/28/0 format 1 G0G2 character set options
const tokens = line.split(',')
data.control = parseInt('0x'+tokens[1])
io.sockets.emit('control', data)
return data
} else {
return data // Not a row. Not interested
}
data.y = row
// Here is a line at a time
let result = line.substring(ix) // snip out the row data
// Pad strings shorter than 40 characters
if (result.length < 40) {
result = result.padEnd(CONFIG[CONST.CONFIG.NUM_COLUMNS])
}
// Special hack for 404 page. Replace this field with the missing page number
// @todo Different services need different permissions
if (
(data.S === CONST.SERVICE_WIKI) &&
(data.p === CONST.PAGE_404) &&
(row === 22)
) {
const first = result.substring(0, 32)
const second = result.substr(35)
result = first + missingPage + second
}
data.k = '?' // k and x are ignored
data.x = 0 // (!) Don't use anything in CONST.<state signals>. It can trigger overwriting our page
data.y = row // The row that we are sending out
if ((!serviceData || !serviceData.forceServiceHeader) || (row !== 0)) {
result = DeEscapePrestel(result) // remove Prestel escapes
data.rowText = result
}
//
// Check if it is a special row, X26,X27,X28
if (row === 28) {
data.X28F1 = DecodeOL28(data.rowText)
}
io.sockets.emit('row', data)
return data
}
function doLoad (data) {
if (typeof data.p !== 'number') {
data.p = CONST.PAGE_MIN
}
// @todo: This should emit only to socket.emit, not all units
// clear the existing page
io.sockets.emit('blank', data)
// if client request has data.x==CONST.SIGNAL_INITIAL_LOAD, we load the initial page.
if (data.x === CONST.SIGNAL_INITIAL_LOAD) {
data.p = initialPage
data.x = 0
}
// get service (and set to default service if not found)
let service = connectionList[data.id]
if (!service) {
service = CONFIG[CONST.CONFIG.DEFAULT_SERVICE]
}
// shorthand service data object
const servicesData = CONFIG[CONST.CONFIG.SERVICES_AVAILABLE]
// determine what to serve...
let filename
if (data.x === CONST.SIGNAL_PAGE_NOT_FOUND) {
// determine 404 page file to serve...
filename = CONFIG[CONST.CONFIG.PAGE_404_PATH]
// if service is editable, serve editable 404 page
if (servicesData[service] && servicesData[service].isEditable) {
filename = CONFIG[CONST.CONFIG.PAGE_404_EDITABLE_PATH]
}
// serve custom 404 page, or leave existing blanked page?
if (!fs.existsSync(filename)) {
// custom 404 page does not exist, leave existing blanked page
return false
}
} else {
// attempt serve a standard page...
const serviceManifest = loadServiceManifest(service)
if (serviceManifest && serviceManifest.pages && serviceManifest.pages[data.p.toString(16)] && serviceManifest.pages[data.p.toString(16)].f) {
// ...use page filename as defined in service manifest
filename = path.join(
CONFIG[CONST.CONFIG.SERVICE_PAGES_SERVE_DIR],
service,
serviceManifest.pages[data.p.toString(16)].f
)
} else {
// service manifest does not exist, use standard page-number-based filename format
filename = path.join(
CONFIG[CONST.CONFIG.SERVICE_PAGES_SERVE_DIR],
service,
`p${data.p.toString(16)}.tti`
)
}
}
// check if the page is already in cache
let found = findService(service)
if (found === false) {
LOG.fn(
['teletextserver', 'doLoad'],
`Adding service=${service}, buffered key count=${keystroke.length}`,
LOG.LOG_LEVEL_VERBOSE
)
// create the service
services.push(
new Service(service)
)
// the index of the service we just created
found = services.length - 1
}
// Now we have a service number. Does it contain our page?
const svc = services[found]
const page = svc.findPage(data.p) // @todo: this will always be false, since we're not doing svc.addPage()
// determine if page file exists...
let is404 = false
if (!fs.existsSync(filename)) {
LOG.fn(
['teletextserver', 'doLoad'],
`Error: Page TTI file not found. service=${service}, page=${page}, filename=${filename}, data.x=${data.x}, data.id=${data.id}`,
LOG.LOG_LEVEL_ERROR
)
is404 = true
} else {
LOG.fn(
['teletextserver', 'doLoad'],
`Found service=${service}, page=${page}, filename=${filename}, data.x=${data.x}, data.id=${data.id}`,
LOG.LOG_LEVEL_VERBOSE
)
}
const pageNotFound = function () {
const data2 = {
...data,
...{
p: data.p,
x: CONST.SIGNAL_PAGE_NOT_FOUND, // Signal a 404 error
S: connectionList[data.id] // How do we lose the service type? This hack shouldn't be needed
}
}
io.sockets.emit('setpage', data2)
doLoad(data2)
}
// if page file is not available, immediately serve 404 page
if (is404) {
pageNotFound()
return
}
// attempt to read page file contents...
const instream = fs.createReadStream(
filename,
{
// ascii strips bit 7 without messing up the rest of the text. latin1 does not work :-(
encoding: CONST.ENCODING_ASCII
}
)
instream.on('error', pageNotFound)
subPage = -1 // Make sure that subPage numbers are logical
const rl = readline.createInterface({
input: instream,
terminal: false
})
rl.on('line', function (line) {
data = processServicePageLine(
servicesData[service],
data,
line
)
})
rl.on('close', function () {
LOG.fn(
['teletextserver', 'doLoad'],
'end of file',
LOG.LOG_LEVEL_VERBOSE
)
// When the file has been read, we want to send any keystrokes that might have been added to this page
keystroke.replayEvents(io.sockets)
// How are we going to send this?
}
)
}
/** Finds the service with the required name.
* @return Index of service, or false
*/
function findService (name) {
if (services.length === 0) {
return false // No services
}
for (let i = 0; i < services.length; i++) {
if (services[i].matchName(name)) {
return i
}
}
return false // Not found
}
/** Create a page from template number data.p
*/
function createPage (data, callback) {
const servicesData = CONFIG[CONST.CONFIG.SERVICES_AVAILABLE]
// Don't create page if service is not defined, or is not a known service
if (!data.S || !servicesData[data.S]) {
LOG.fn(
['teletextserver', 'createPage'],
`Error: Could not create page, service=${data.S} unknown`,
LOG.LOG_LEVEL_ERROR