forked from interplanaria/bottle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
388 lines (381 loc) · 10.6 KB
/
index.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
let win;
const { ipcMain, app, session, protocol, BrowserWindow } = require('electron');
const dirname = app.getAppPath();
const userPath = app.getPath("userData");
const {PassThrough} = require('stream');
const path = require('path');
const fs = require('fs');
const URL = require('url');
const request = require('request');
const mime = require('mime-types');
const Route = require('route-parser');
const Handlebars = require('handlebars');
const CONSTANTS = require('./constants');
const DEFAULTS = require('./defaults.json');
const router_path = path.join(userPath, '.', 'router.json');
var res_headers;
var routes = {};
var routeMap = {};
var routeState = {};
var routeMem = {};
global.headers = function() {
return res_headers;
}
global.router = {
get: function(address) {
return routeState[address];
},
add: function(r, redirect) {
// if existing route, remove
// if non existing route, add.
routes = {};
/**
*
* [1] From the following object:
*
* r := {
* "19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut": {
* "/:tx": {
* "1KBZ3jGAzqRH2VjVkjrgBxjrpiQCQXFzwP": "https://data.bitdb.network/1KuUr2pSJDao97XM8Jsq8zwLS6W1WtFfLg/b/{{tx}}"
* }
* },
* "19iG3WTYSsbyos3uJ733yK4zEioi1FesNU": {
* "/:owner/:key": {}
* },
* "1KCm9cgDdT7r88WRQmm6gynFNmTrskdygn": {
* "/:hash": {
* "1KBZ3jGAzqRH2VjVkjrgBxjrpiQCQXFzwP": "https://data.bitdb.network/1KuUr2pSJDao97XM8Jsq8zwLS6W1WtFfLg/c/{{hash}}"
* }
* },
* "1BurpBxnLyL87Q8XwU9X6J1wCd3VUa7rMU": {
* "/LBM/:page": {
* "1HU76g9nAH8ndvYHi3jw1ZW5saxRxym22e": "https://londonbitcoinmeetup.com/"
* }
* }
* }
*/
Object.keys(r).forEach(function(k) {
/**
*
* [2] Update routeMap
*
* assign r into routeMap
*
*/
let app = r[k];
/**
*
* app := {
* "/:tx": {
* "1KBZ3jGAzqRH2VjVkjrgBxjrpiQCQXFzwP": "https://data.bitdb.network/1KuUr2pSJDao97XM8Jsq8zwLS6W1WtFfLg/b/{{tx}}"
* }
* }
*
*/
Object.keys(app).forEach(function(path) {
let service = app[path];
for(let service_address in service) {
let o = service[service_address];
if (!routeState[k]) {
routeState[k] = {};
}
if (routeState[k][path] && routeState[k][path][service_address]) {
delete routeState[k][path][service_address];
delete routeMap[k][service_address];
} else {
routeState[k][path] = {}
routeState[k][path][service_address] = o;
let matcher = {
i: new Route(k + path),
o: Handlebars.compile(o)
}
routeMap[k] = {}
routeMap[k][service_address] = matcher;
}
}
})
})
/*
*
* [3] Generate routes from routeMap
*
* routes := {
* "19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut": [
* { i: new Route("19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut/:tx"), o: Handlebars.compile("https://data.bitdb.network/1KuUr2pSJDao97XM8Jsq8zwLS6W1WtFfLg/b/{{tx}}") },
* { i: new Route("19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut/:tx"), o: Handlebars.compile("https://bitpaste.app/{{tx}}") },
* ],
* "1KCm9cgDdT7r88WRQmm6gynFNmTrskdygn": [
* { i: new Route("1KCm9cgDdT7r88WRQmm6gynFNmTrskdygn/:hash"), o: Handlebars.compile("https://data.bitdb.network/1KuUr2pSJDao97XM8Jsq8zwLS6W1WtFfLg/c/{{hash}}") },
* ..
* { i: new Route("1BurpBxnLyL87Q8XwU9X6J1wCd3VUa7rMU/LBM/:page"), o: Handlebars.compile("https://londonbitcoinmeetup.com/") },
* ...
* ]
*
*/
for(let key in routeMap) {
if (!routes[key]) {
routes[key] = [];
}
let endpoints = routeMap[key];
for(let j in endpoints) {
routes[key].push({
endpoint: j,
matcher: endpoints[j]
})
}
}
/*
* [4] Later it can be matched sequentially
*
* let resolved;
* for(let i=0; i<routes.length; i++) {
* let match = routes[i].i.match(uri)
* if (match) {
* // parse with handlebars
* resolved = routes[i].o(match)
* break;
* }
* })
*
*/
fs.writeFile(router_path, JSON.stringify(routeState, null, 2), function(err, data) {
if (redirect) {
win.webContents.send("route-updated", redirect);
}
});
}
}
var extract = function(uri) {
let m = /^(b|c|bottle):\/\/([^?#]+)/i.exec(uri)
if (m && m.length === 3) {
let matched = m[2];
if (matched[matched.length-1] === '/') {
return matched.slice(0, -1);
} else {
return matched;
}
} else {
return null;
}
}
var extractBit = function(uri) {
let m = /^bit:[\/]+([^\/]+)\/([^?#]+)/i.exec(uri)
if (m && m.length >= 3) {
let a = m[1];
let p = m[2];
if (p[p.length-1] === '/') {
p = p.slice(0, -1);
}
return {
address: a,
path: p
}
} else {
return null;
}
}
const resolver = function(extracted, callback, raw) {
let addr = extracted.address;
let u = addr + "/" + extracted.path;
// Resolve URI
let resolved;
if (routes[addr]) {
let e = routes[addr]
for(let i=0; i<e.length; i++) {
let match = e[i].matcher.i.match(u)
if (match) {
// parse with handlebars
resolved = e[i].matcher.o(match)
break;
}
}
console.log("Incoming = ", u)
console.log("resolved = ", resolved);
if (resolved) {
let st = request(resolved);
st.on('response', function(response) {
if (raw) {
response.headers["Content-Type"] = "text/plain"
}
res_headers = response.headers;
const pass = new PassThrough();
st.pipe(pass);
callback({
data: pass,
statusCode: response.statusCode,
headers: response.headers
});
})
} else {
console.log("Not resolved")
win.webContents.send("resolve-error", addr);
callback({ statusCode: 404 })
}
} else {
console.log("Not resolved")
win.webContents.send("resolve-error", addr);
callback({ statusCode: 404 })
}
}
var createWindow = function () {
win = new BrowserWindow({
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
plugins: true,
webSecurity: false
}
});
win.maximize();
win.loadURL(`file:///${dirname}/index.html`);
fs.readFile(router_path, function(err, data) {
if (data) {
try {
routeState = JSON.parse(data);
} catch (e) {
console.log("error = ", e);
}
}
if (!routeState || !routeState[CONSTANTS.B]) {
routeState[CONSTANTS.B] = DEFAULTS[CONSTANTS.B];
}
if (!routeState || !routeState[CONSTANTS.C]) {
routeState[CONSTANTS.C] = DEFAULTS[CONSTANTS.C];
}
for(let k in routeState) {
for (let path in routeState[k]) {
let service = routeState[k][path];
for (let service_address in service) {
let o = service[service_address];
let matcher = {
i: new Route(k + path),
o: Handlebars.compile(o)
}
routeMap[k] = {}
routeMap[k][service_address] = matcher;
}
}
}
for(let key in routeMap) {
if (!routes[key]) {
routes[key] = [];
}
let endpoints = routeMap[key];
for(let j in endpoints) {
routes[key].push({
endpoint: j,
matcher: endpoints[j]
})
}
}
});
protocol.registerStreamProtocol('bit', function(req, callback) {
let extracted = extractBit(req.url)
if (extracted) {
resolver(extracted, callback);
} else {
callback({ statusCode: 404 })
}
}, function (error) {
if (error) {
console.error('Failed to register protocol');
}
})
protocol.registerStreamProtocol('b', function(req, callback) {
let path = extract(req.url)
resolver({ address: CONSTANTS.B, path: path }, callback)
}, function (error) {
if (error) {
console.error('Failed to register protocol');
}
})
protocol.registerStreamProtocol('c', function(req, callback) {
let path = extract(req.url)
resolver({ address: CONSTANTS.C, path: path }, callback)
}, function (error) {
if (error) {
console.error('Failed to register protocol');
}
})
protocol.registerStreamProtocol('bottle', function(req, callback) {
let url = extract(req.url);
// file extension doesn't exist
if (!/\.[A-Za-z0-9]+$/i.test(url)) {
url = url + ".html";
}
if (url) {
let stubPath = path.join(dirname, '.', url);
let exists = fs.existsSync(stubPath);
if (exists) {
let result = { data: fs.createReadStream(stubPath) }
let type = mime.lookup(url);
if (type) {
result.headers = { "Content-type": type };
}
callback(result);
return;
}
}
callback({ statusCode: 404 })
})
protocol.interceptStreamProtocol('file', function(req, callback) {
const url = req.url.trim().substr(8);
if (/^b:\/\//i.test(url)) {
let path = extract(url)
if (path) {
resolver({ address: CONSTANTS.B, path: path }, callback)
} else {
callback({ statusCode: 404 })
}
} else if (/^c:\/\//i.test(url)) {
let path = extract(url)
if (path) {
resolver({ address: CONSTANTS.C, path: path }, callback)
} else {
callback({ statusCode: 404 })
}
} else {
// regular file
let parsed;
if (process.platform === 'win32') {
parsed = URL.parse(url);
} else {
parsed = URL.parse(req.url);
}
let decoded = decodeURI(parsed.pathname);
let exists = fs.existsSync(decoded);
let result = { data: fs.createReadStream(decoded) }
let type = mime.lookup(decoded);
if (type) {
result.headers = { "Content-type": type };
}
callback(result);
}
}, function(error) {
if (error) console.error('Failed to register protocol');
});
win.maximize();
win.on('closed', function() {
win = null;
});
}
app.commandLine.appendSwitch('ignore-certificate-errors', 'true');
app.setAsDefaultProtocolClient("bottle");
app.setAsDefaultProtocolClient("bit");
app.setAsDefaultProtocolClient("b");
app.setAsDefaultProtocolClient("c");
app.on('open-url', function (event, data) {
console.log("#### open-url =", data, event);
event.preventDefault();
win.webContents.send("open-tab", data);
});
app.on('ready', function() {
if (!win) {
createWindow();
}
});
app.on('window-all-closed', function() {
if (process.platform !== 'darwin') {
app.quit();
}
});