-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
109 lines (96 loc) · 2.46 KB
/
app.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
var express = require('express');
var http = require('http');
var fs = require('fs');
var app = exports.app = express();
app.use(express.favicon(__dirname + '/static/favicon.ico'));
app.get('/:height?', function(req, res) {
console.log(new Date().toUTCString() + ': request: /' + (req.params.height ? req.params.height : ''));
var page;
var info = {};
fs.readFile(__dirname + '/static/index.html', 'utf8', function (error, data) {
if (error) {
res.send("Error");
return;
}
page = data;
// just in case fs is slower than http for some reason
buildPage(res, info, page);
});
// handle height parameter
if (req.params.height) {
info.height = parseInt(req.params.height);
if (!isNaN(info.height)) {
blocksAtHeight(info.height, function(count) {
info.count = count;
buildPage(res, info, page);
});
return;
}
}
latestHeight(function(height) {
info.height = height;
blocksAtHeight(height, function(count) {
info.count = count;
buildPage(res, info, page);
});
});
});
function buildPage(res, info, page) {
if (!info.count || !page) {
return;
}
if (info.count > 0) {
page = page.replace(/\{YESNO\}/g, info.count > 1 ? '<h1 class="yes">YES</h1>' : '<h1 class="no">NO</h1>');
page = page.replace(/\{BLOCK_DESC\}/g, info.count != 1 ? info.count + " blocks" : "Only one block");
page = page.replace(/\{HEIGHT\}/g, info.height);
res.send(page);
}
else {
page = page.replace(/\{YESNO\}/g, '<h1>WAT</h1>');
page = page.replace(/\{BLOCK_DESC\}/g, 'Error: Zero blocks');
page = page.replace(/\{HEIGHT\}/g, info.height);
res.send(page);
}
}
function latestHeight(callback) {
var url = 'http://blockchain.info/latestblock';
http.get(url, function(res) {
accumulate(res, function(body) {
var height;
try {
height = JSON.parse(body).height;
}
catch(ex) {
height = -1;
}
callback(height);
});
});
}
function blocksAtHeight(height, callback) {
var url = 'http://blockchain.info/block-height/' + height + '?format=json';
http.get(url, function(res) {
accumulate(res, function(body) {
var count;
try {
count = JSON.parse(body).blocks.length;
}
catch(ex) {
count = -1;
}
callback(count);
});
});
}
function accumulate(response, callback) {
var body = '';
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
callback(body);
});
}
app.use(express.static(__dirname + '/static'));
//app.listen(80);
console.log('listening on port 80');