forked from einarwh/hyperwizard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1906 lines (1594 loc) · 49.2 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
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
var express = require('express');
var app = express();
//var fs = require('fs');
var fs = require('fs-extra')
var lepath = require('path');
app.use('/elmer', express.static(__dirname + '/elmer'));
app.use('/images', express.static(__dirname + '/images'));
app.use(express.urlencoded());
app.use(express.json());
if (typeof String.prototype.reverse !== 'function') {
String.prototype.reverse = function () {
return this.split("").reverse().join("");
};
}
if (typeof String.prototype.startsWith !== 'function') {
String.prototype.startsWith = function (str) {
return this.lastIndexOf(str, 0) === 0
};
}
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
var adventures = {};
var masterWizardName = "Edsger";
function book_name(index) {
if (index === 1) {
return "Plain JSON REST APIs for fun and profit";
}
if (index === 2) {
return "Level 2 REST FTW";
}
if (index === 3) {
return "No REST till Hypermedia!";
}
}
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
function get_reps() {
var files = fs.readdirSync("reps");
var reps = [];
for (var i = 0; i < files.length; i++) {
var f = files[i];
var suffixIndex = f.indexOf(".json");
if (f.endsWith(".json")) {
var resource = f.substring(0, f.length - ".json".length);
reps.push(resource);
}
}
return reps;
}
function has_rep(rep) {
var reps = get_reps();
for (var i = 0; i < reps.length; i++) {
if (reps[i] === rep) {
return true;
}
}
return false;
}
function init_state(adv_id, old_state) {
var bridge = false;
var skeleton = false;
if (old_state) {
bridge = old_state.bridge;
skeleton = old_state.skeleton;
}
var mirrors = [1, 2, 3, 4, 5, 6, 7];
var unbreakable = Math.floor((Math.random()*mirrors.length)+1);
var state = {
"id": adv_id,
"timestamp": new Date().getTime(),
"mirrors": mirrors,
"broken_mirrors": [],
"unbreakable": unbreakable,
"room": false,
"closed": true,
"bridge": bridge,
"skeleton": skeleton,
"old_state": old_state
};
return state;
}
var permanent_aid = 1337;
adventures[permanent_aid] = init_state(permanent_aid);
var local_port = 1337;
var base_url = 'http://localhost:' + local_port;
var port = process.env.PORT || local_port;
if (process.env.PORT) {
base_url = 'http://hyperwizard.azurewebsites.net';
}
var game_url = base_url + '/hywit/';
function hylink(relative) {
return game_url + relative;
}
function advlink(adv_id, relative) {
return hylink(adv_id + '/' + relative);
}
function imglink(imgfile) {
return base_url + '/images/' + imgfile;
}
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
function setFsmImage(dir, imageName) {
//console.log('Set FSM image ' + imageName);
var pngFile = imageName + ".png";
var basePath = lepath.join(__dirname, '../fsmwatcher');
var srcPath = lepath.join(basePath, 'graphs', dir, pngFile);
var dstPath = lepath.join(basePath, 'fsmimages', pngFile);
fs.stat(srcPath, function (err, stat) {
if (err == null) {
fs.copySync(srcPath, dstPath);
} else if(err.code == 'ENOENT') {
console.log("FSM image doesn't exist. " + srcPath);
} else {
console.log('Some other error: ', err.code);
}
});
}
function acceptsHtml(req) {
return req.headers.accept.indexOf("text/html") >= 0;
}
function acceptsJson(req) {
return req.headers.accept.indexOf("application/json") >= 0;
}
function acceptsSiren(req) {
return req.headers.accept.indexOf("application/vnd.siren+json") >= 0;
}
function toActionForm(act) {
var s = "";
var field;
var httpMethod = "POST";
if (act.method === "GET") {
httpMethod = "GET";
}
s += "<p>" + act.title + '</p>';
s += '<form action="' + act.href + '" method="' + httpMethod + '">';
if ('undefined' === typeof act.method) {
s += '<select name="httpmethod">';
s += '<option value="GET">GET</option>';
s += '<option value="POST">POST</option>';
s += '<option value="PUT">PUT</option>';
s += '<option value="DELETE">DELETE</option>';
s += '<option value="PATCH">PATCH</option>';
s += '</select>';
}
if ('undefined' !== typeof act.fields) {
for (var i = 0, len = act.fields.length; i < len; i++) {
field = act.fields[i];
s += field.name + '<br />';
s += '<input type="' + field.type + '" name="' + field.name + '" />';
s += '<br />';
}
}
s += '<br />';
s += '<input type="submit" value="Submit" />';
s += '</form>';
return s;
}
function toHtml(srn) {
var s = "";
var props = srn.properties;
var links = srn.links;
var alink;
var actions = srn.actions;
var act;
var title = "Hypermedia in the Wizard's Tower";
if ('undefined' !== typeof srn.title) {
title += ": " + srn.title;
}
s += "<!DOCTYPE html>";
s += "<html>";
s += "<head>";
s += "<title>" + title + "</title>";
s += '<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">';
s += "</head>";
s += "<body>";
var imageLinks = [];
if ('undefined' !== typeof links) {
for (var i = 0, len = links.length; i < len; i++) {
alink = links[i];
if ('undefined' !== typeof alink.type) {
if (alink.rel.indexOf("view") >= 0) {
imageLinks.push(alink);
}
}
}
}
var imgCount = imageLinks.length;
if (imgCount > 0) {
s += '<div class="images">';
for (var imgIndex = 0; imgIndex < imgCount; imgIndex++) {
var animage = imageLinks[imgIndex];
s += '<img src="' + animage.href + '" />';
}
s += '</div>';
}
if ('undefined' !== typeof props) {
s += "<div>";
s += '<p class="name">' + props.name + '</p>';
s += '<p class="description">' + props.description + '</p>';
var keys = Object.keys(props);
for (var k = 0; k < keys.length; k++) {
var propname = keys[k];
if (propname !== 'name' && propname !== 'description') {
s += '<p class="' + propname + '">' + propname + ": " + props[propname] + '</p>';
}
}
s += "</div>";
}
else {
s += "<div>";
var keys = Object.keys(srn);
for (var k = 0; k < keys.length; k++) {
var propname = keys[k];
s += '<p class="' + propname + '">' + srn[propname] + '</p>';
}
s += "</div>";
}
if ('undefined' !== typeof links) {
s += '<div class="links">';
s += '<p>Places to go:</p>'
s += '<ul>';
for (var i = 0, len = links.length; i < len; i++) {
alink = links[i];
var linkText = alink.title || alink.rel;
s += '<li>' + '<a href="' + alink.href + '">' + linkText + '</a>' + '</li>';
}
s += '</ul>';
s += '</div>';
}
if ('undefined' !== typeof actions) {
s += '<div class="actions">';
s += '<p>Things to do:</p>'
s += '<ul>';
for (var i = 0, len = actions.length; i < len; i++) {
act = actions[i];
s += '<li>' + toActionForm(act) + '</li>';
}
s += '</ul>';
s += '</div>';
}
s += "</body>";
s += "</html>";
return s;
}
function toResponse(req, res, siren, statusCode) {
var sc = statusCode || 200;
var ct = "application/vnd.siren+json";
var transform = JSON.stringify;
if (acceptsHtml(req)) {
ct = "text/html";
transform = toHtml;
}
if (statusCode === 401) {
res.set('WWW-Authenticate', 'Basic realm="tower"');
}
if (acceptsSiren(req) || acceptsJson(req)) {
res.contentType(ct);
res.status(sc).send(transform(siren));
return;
}
res.contentType("text/plain");
res.status(406).send("application/vnd.siren+json\napplication/json\ntext/html");
}
function toJsonResponse(req, res, siren, statusCode) {
var sc = statusCode || 200;
var ct = "application/json";
var transform = JSON.stringify;
if (acceptsHtml(req)) {
ct = "text/html";
transform = toHtml;
}
res.contentType(ct);
res.status(sc).send(transform(siren));
}
app.get('/', function(req, res) {
res.contentType("text/plain");
res.send("Visit http://github.com/einarwh/hyperwizard");
});
app.get('/hywit/void', function(req, res) {
var voidUrl = hylink('void');
if (req.headers.accept === "text/plain") {
var text = "The Magical Void\n\nYou're in The Magical Void, a place beyond space and time. This is where adventures begin.\n\nTo start a new adventure, post name, class and race to " + voidUrl;
res.contentType(req.headers.accept);
res.send(text);
return;
}
else if (req.headers.accept === "application/json") {
var plainJson = {
"title": "The Magical Void",
"description": "You're in The Magical Void, a place beyond space and time. This is where adventures begin.",
"link":
{
"title": "Start a new adventure",
"url": voidUrl
}
};
res.contentType(req.headers.accept);
res.send(JSON.stringify(plainJson));
return;
}
var siren = {
"title": "The Magical Void",
"class": [ "location" ],
"properties": {
"name": "The Magical Void",
"description": "You\'re in The Magical Void, a place beyond space and time. This is where adventures begin.",
},
"actions": [
{
"name": "start-adventure",
"method": "POST",
"title": "Start adventure",
"href": hylink('void'),
"fields": [
{ "name": "name", "type": "text" },
{ "name": "class", "type": "text" },
{ "name": "race", "type": "text" }
]
}
],
"links": [
{ "rel": [ "self" ], "href": hylink('void') },
{ "rel": [ "view" ], "href": imglink('magical-void.png'), "type": "image/png" }
]
};
toResponse(req, res, siren);
});
app.get('/hywit/:adv_id/hall/teapot', function(req, res) {
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
if (adv_state.closed) {
res.status(302).location(alink('hill')).send();
return;
}
res.status(418).location(alink('hall')).send();
});
app.get('/hywit/:adv_id/divide', function(req, res) {
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
var self_link = alink('divide');
var act = {
"name": "pull-lever",
"method": "POST",
"title": "Pull the lever.",
"href": self_link
}
var siren = {
"title": "The Great Divide",
"class": [ "location" ],
"properties": {
"name": "The Great Divide",
"description": "You're standing on the edge of a great divide. You can see a rusty lever."
},
"actions": [ act ],
"links": [
{ "rel": [ "self" ], "href": self_link },
{ "rel": [ "move", "south" ], "title": "Go south to the hill.", "href": alink("hill") }
]
};
if (adv_state.bridge) {
siren.properties.description = siren.properties.description + " There is a bridge crossing the divide.";
if (adv_state.skeleton) {
siren.properties.description = siren.properties.description + " You see a skeleton on the bridge.";
} else {
siren.links.push({ "rel": [ "move" ], "title": "Cross the bridge.", "href": alink('bridge') });
}
setFsmImage('divide', 'divide-1-crossable');
}
else {
siren.properties.description = siren.properties.description + " There seems to be a strange bridge hovering in the air, parallel to the divide.";
if (adv_state.skeleton) {
siren.properties.description = siren.properties.description + " You see a skeleton on the bridge.";
}
}
if (adv_state.old_state) {
siren.links.push({ "rel": [ "look" ], "title": "A bag of popcorn?", "href": alink('skcans') });
}
toResponse(req, res, siren);
});
app.post('/hywit/:adv_id/divide', function(req, res) {
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
adv_state.bridge = !adv_state.bridge;
if (adv_state.old_state) {
adv_state.old_state.bridge = !adv_state.old_state.bridge;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
var self_link = alink('divide');
var act = {
"name": "pull-lever",
"method": "POST",
"title": "Pull the lever.",
"href": self_link
}
var siren = {
"title": "The Great Divide",
"class": [ "location" ],
"properties": {
"name": "The Great Divide",
"description": "You're standing on the edge of a great divide. You can see a rusty lever."
},
"actions": [ act ],
"links": [
{ "rel": [ "self" ], "href": self_link },
{ "rel": [ "move", "south" ], "title": "Go south to the hill.", "href": alink("hill") }
]
};
if (adv_state.bridge) {
siren.properties.description = siren.properties.description + " There is a bridge crossing the divide.";
if (adv_state.skeleton) {
siren.properties.description = siren.properties.description + " You see a skeleton on the bridge.";
} else {
siren.links.push({ "rel": [ "move" ], "title": "Cross the bridge.", "href": alink('bridge') });
}
}
else {
siren.properties.description = siren.properties.description + " There seems to be a strange bridge hovering in the air, parallel to the divide.";
if (adv_state.skeleton) {
siren.properties.description = siren.properties.description + " You see a skeleton on the bridge.";
}
}
if (adv_state.old_state) {
siren.links.push({ "rel": [ "look" ], "title": "A bag of popcorn?", "href": alink('skcans') });
}
var fsmImageName = "divide-0-inaccessible";
if (adv_state.bridge) {
fsmImageName = "divide-1-crossable";
}
setFsmImage('divide', fsmImageName);
toResponse(req, res, siren);
});
app.get('/hywit/:adv_id/lake', function(req, res){
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
var self_link = alink('lake');
var siren = {
"title": "The Lake",
"class": [ "location" ],
"properties": {
"name": "The Lake",
"description": ""
},
"links": [
{ "rel": [ "self" ], "href": self_link },
{ "rel": [ "move", "north" ], "title": "Follow the brook north.", "href": alink("brook") }
]
};
if (undefined === adv_state.boat) {
siren.properties.description = "You're standing on the shore of a lake. There's small island in the middle, where you can see a rowing boat tied to a pole. Unfortunately, the current is too strong for you to venture swimming over. Every now and then, the head of an otter emerges from the water.";
if (undefined === adv_state.otter) {
var otter = {
name: "send-otter",
title: "Send the otter to fetch the boat.",
method: "POST",
href: self_link
}
siren.actions = [ otter ];
}
else {
siren.links.push({
"rel": [ "look" ],
"title": "Look at the otter.",
"href": alink('otter')
});
setFsmImage('lake', 'lake-1-waiting');
}
}
else {
siren.properties.description = "You're standing on the shore of a lake. There's small island in the middle. There is a boat here. Every now and then, the head of an otter emerges from the water.";
var row = {
"rel": [ "move" ],
"title": "Row to the island.",
"href": alink('island')
};
siren.links.push(row);
setFsmImage('lake', 'lake-2-boat');
}
if (adv_state.old_state) {
siren.links.push({ "rel": [ "look" ], "title": "A bag of popcorn?", "href": alink('skcans') });
}
toResponse(req, res, siren);
});
app.post('/hywit/:adv_id/lake', function(req, res) {
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
adv_state.otter = Date.now() / 1000;
res.status(202).location(alink('otter')).send();
});
app.get('/hywit/:adv_id/otter', function(req, res){
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
if ('undefined' === typeof adv_state.otter) {
res.status(403).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
var current = Date.now() / 1000;
var elapsed = current - adv_state.otter;
var totalTime = 120;
var halfTime = 60;
var otterReturned = elapsed > totalTime;
if (otterReturned) {
adv_state.boat = current;
res.status(303).location(alink('lake')).send();
setFsmImage('otter', 'otter-3-back');
return;
}
var otterReturning = elapsed > halfTime;
var self_link = alink('otter');
var siren = {
"title": "The Swimming Otter",
"class": [ "entity" ],
"properties": {
"name": "The Swimming Otter",
"description": "The otter is on its way to fetch the rowing boat. It has spent " + Math.floor(elapsed) + " seconds so far."
},
"links": [
{ "rel": [ "self" ], "href": self_link },
{ "rel": [ "previous" ], "href": alink('lake') },
{ "rel": [ "view" ], "href": imglink("otter.png"), type: "image/png" }
]
};
if (otterReturning) {
siren.properties.description += " Currently, it is on the way back, towing the boat.";
setFsmImage('otter', 'otter-2-returning');
}
else {
siren.properties.description += " Currently, it is swimming towards the island.";
setFsmImage('otter', 'otter-1-fetching');
}
if (adv_state.old_state) {
siren.links.push({ "rel": [ "look" ], "title": "A bag of popcorn?", "href": alink('skcans') });
}
toResponse(req, res, siren);
});
app.get('/hywit/:adv_id/hall', function(req, res){
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
if (adv_state.closed) {
res.status(302).location(alink('hill')).send();
return;
}
var self_link = alink('hall');
var siren = {
"title": "The Great Hall",
"class": [ "location" ],
"properties": {
"name": "The Great Hall",
"description": "You find yourself in a great hall. There's a table here. You see some cutlery of no interest to you, as well as a beautiful silver tea pot. Could it be magical? A door leads to the east from here."
},
"links": [
{ "rel": [ "self" ], "href": self_link },
{ "rel": [ "move", "east" ], "href": alink("mirrors"), "title": "Go through the door to the east." },
{ "rel": [ "move", "exit" ], "href": alink("entrance"), "title": "Exit the tower." },
{ "rel": [ "take" ], "href": alink("hall/teapot"), "title": "Take the teapot." }
]
};
if (adv_state.old_state) {
siren.links.push({ "rel": [ "look" ], "title": "A bag of popcorn?", "href": alink('skcans') });
}
toResponse(req, res, siren);
});
app.get('/hywit/:adv_id/grue', function(req, res) {
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
if (undefined === adv_state.grue) {
var act = {
"name": "kill-grue",
"title": "Light a handy torch lying nearby.",
"href": alink('gruesome')
}
var siren = {
"title": "A terrifying grue.",
"class": [ "location" ],
"properties": {
"name": "A terrifying grue.",
"description": "Uh-oh. A terrifying grue has appeared in front of you. This could be fatal, unless you know your HTTP methods."
},
"actions": [ act ],
"links": [
{ "rel": [ "view" ], "href": imglink("grue.png"), type: "image/png" }
]
};
if (adv_state.old_state) {
siren.links.push({ "rel": [ "look" ], "title": "A bag of popcorn?", "href": alink('skcans') });
}
toResponse(req, res, siren);
} else {
setFsmImage('grue', 'grue-2-gone');
res.status(410).send("The grue has vanished permanently.");
}
});
function killGrue(req, res) {
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
setFsmImage('grue', 'grue-2-gone');
adv_state.grue = "dead";
res.status(204).location(alink('brook')).send();
}
function eatenByGrue(res) {
setFsmImage('grue', 'grue-1-deadly');
res.status(405).send("You've been eaten by a grue.");
}
app.post('/hywit/:adv_id/gruesome', function(req, res) {
var verb = req.body.httpmethod;
if (verb === 'DELETE') {
killGrue(req, res);
return;
}
eatenByGrue(res);
});
app.get('/hywit/:adv_id/gruesome', function(req, res) {
eatenByGrue(res);
});
app.patch('/hywit/:adv_id/gruesome', function(req, res) {
eatenByGrue(res);
});
app.put('/hywit/:adv_id/gruesome', function(req, res) {
eatenByGrue(res);
});
app.delete('/hywit/:adv_id/gruesome', function(req, res) {
killGrue(req, res);
});
app.get('/hywit/:adv_id/study', function(req, res) {
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
if (adv_state.closed) {
res.status(302).location(alink('hill')).send();
return;
}
var self_link = alink('study');
var book_action = function(book_number) {
return {
"name": "take-book-" + book_number,
"title": "Take '" + book_name(book_number) + "'",
"method": "POST",
"href": alink("study/books/" + book_number)
};
};
var siren = { "class": [ "location" ],
"title": "The Wizard's Study",
"properties": {
"name": "The Wizard's Study",
"description": "You have entered the Wizard's Study. Luckily, the Wizard is not in, or he would surely have deleted you. This means that you have conquered the Wizard's Tower. Congratulations! You may pick a prize, by choosing a book from the Wizard's shelf. Choose wisely."
},
"actions": [
book_action(1),
book_action(2),
book_action(3)
],
"links": [
{ "rel": [ "self" ], "href": self_link }
]
};
if (adv_state.old_state) {
siren.links.push({ "rel": [ "look" ], "title": "A bag of popcorn?", "href": alink('skcans') });
}
if (adv_state.book_id !== undefined) {
setFsmImage('book', 'book-0-choice');
}
toResponse(req, res, siren);
});
app.post('/hywit/:adv_id/study/books/:book_id', function(req, res) {
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
if (adv_state.closed) {
res.status(302).location(alink('hill')).send();
return;
}
var book_id = parseInt(req.params.book_id, 10);
adv_state.book_id = book_id;
var siren;
if (book_id === 3) {
siren = {
"class": [ "location" ],
"title": book_name(book_id),
"properties": {
"name": book_name(book_id),
"description": "Well done. You may return to The Magical Void with your prize."
},
"links": [
{ "rel": [ "return" ], "href": hylink('void'), "title": "Return to the void." }
]
};
if (adv_state.old_state) {
siren.links.push({ "rel": [ "look" ], "title": "A bag of popcorn?", "href": alink('skcans') });
}
setFsmImage('book', 'book-2-free');
toResponse(req, res, siren);
}
else if (book_id === 1 || book_id === 2) {
var plainJson = {
"book": book_name(book_id),
"text": "Well, that's unfortunate. You see, without hyperlinks, you're just stuck here forever."
};
setFsmImage('book', 'book-1-stuck');
toJsonResponse(req, res, plainJson);
}
else {
res.status(400).send();
return;
}
});
app.get('/hywit/:adv_id/mirrors/:mirror', function(req, res){
var adv_id = req.params.adv_id;
var adv_state = adventures[adv_id];
var mirror = parseInt(req.params.mirror, 10);
if ('undefined' === typeof adv_state) {
res.status(404).send();
return;
}
var alink = function (relative) {
return advlink(adv_id, relative);
};
if (adv_state.closed) {
res.status(302).location(alink('hill')).send();
return;
}
if (adv_state.mirrors.indexOf(mirror) < 0) {
if (adv_state.broken_mirrors.indexOf(mirror) < 0) {
res.status(404).send();
}
else {
res.status(410).send();
}
return;
}
var self_link = alink('mirrors/' + mirror);
var siren = { "class": [ "location" ],
"title": "Mirror #" + mirror,
"properties": {
"name": "Mirror #" + mirror,
"description": "You see a reflection of yourself."
},
"links": [
{ "rel": [ "self" ], "href": self_link },
{ "rel": [ "previous" ], "href": alink('mirrors') },
{ "rel": [ "view" ], "href": imglink('mirror.png'), "type": "image/png" }
]
};
if (mirror === adv_state.unbreakable) {
siren.properties.description = "You see a reflection of yourself, upside-down.";
if (adv_state.mirrors.length === 1) {
var enter_action = {
"name": "enter-mirror",
"title": "Enter the mirror!",
"method": "POST",
"href": alink("mirrors/" + adv_state.unbreakable)
};
siren.actions = [ enter_action ];
}
}
if (adv_state.old_state) {