forked from angrymouse/elymus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
354 lines (325 loc) · 7.95 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
const {
app,
BrowserWindow,
Menu,
Tray,
ipcMain,
session,
protocol,
} = require("electron");
const pino = require("pino");
const fs = require("fs");
const path = require("path");
protocol.registerSchemesAsPrivileged([
{
scheme: "repens",
privileges: {
bypassCSP: true,
secure: true,
corsEnabled: true,
standard: true,
supportFetchAPI: true,
allowServiceWorkers: true,
},
},
]);
const unhandled = require("electron-unhandled");
unhandled();
const logger = pino(
pino.destination(
path.join(
require("os").homedir(),
"elymus-fastify-log-" + Date.now() + ".txt"
)
)
);
async function startup() {
let IPFS = await import("ipfs");
let mime = require("mime");
let yauzl = require("yauzl");
let fetchMethods = require("./fetchMethods/combine");
if (fs.existsSync(path.join(require("os").homedir(), ".elymus-ipfs"))) {
fs.rmSync(path.join(require("os").homedir(), ".elymus-ipfs"), {
recursive: true,
force: true,
});
}
const { dns } = require("bns");
const resolver = new dns.Resolver({
tcp: true,
inet6: true,
edns: true,
dnssec: true,
});
const util = require("util");
let { request } = require("undici");
const Store = require("electron-store");
let win = null;
let tray = null;
let store = new Store({
watch: true,
defaults: {
userSettings: {
arweaveGateway: "arweave.net",
skynetPortal: "siasky.net",
cacheSize: 20,
handshakeDns: "127.0.0.1:9591",
},
setuped: false,
},
});
store.onDidChange("userSettings.handshakeDns", async (v) => {
resolver.setServers([v]);
});
resolver.setServers([await store.get("userSettings.handshakeDns")]);
const createWindow = () => {
win = new BrowserWindow({
title: "Elymus",
width: 1000,
height: 700,
enableLargerThanScreen: true,
icon: path.join(__dirname, "src", "assets", "logo-01.png"),
webPreferences: {
preload: path.join(__dirname, "preload.js"),
webviewTag: true,
},
});
win.on("close", () => {
win = null;
});
win.loadURL("http://localhost:11984/");
};
app.on("window-all-closed", () => {
win = null;
});
const fastify = require("fastify")({ logger });
// Declare a route
fastify.get("/api/show", async (request, reply) => {
if (!win) {
createWindow();
} else {
await win.show();
await win.setAlwaysOnTop(true);
win.setAlwaysOnTop(false);
}
return { okay: true };
});
fastify.register(require("@fastify/static"), {
root: path.join(__dirname, "ui-static/public"),
prefix: "/", // optional: default '/'
});
// Run the server!
const start = async (app) => {
try {
let { body } = await request("http://localhost:11984/api/show");
if ((await body.json()).okay) {
return app.exit();
}
} catch (e) {
try {
global.ipfs = await IPFS.create({
repoAutoMigrate: true,
repo: path.join(require("os").homedir(), ".elymus-ipfs"),
});
ipcMain.handle("get-store-value", (event, key) => {
return store.get(key);
});
ipcMain.handle("set-store-values", (event, entries) => {
return store.set(entries);
});
ipcMain.handle("stop-app", () => {
app.quit();
});
createWindow();
tray = new Tray(path.join(__dirname, "icon.png"));
const contextMenu = Menu.buildFromTemplate([
{
label: "Stop and close Elymus",
type: "normal",
role: "quit",
},
]);
tray.setToolTip("Elymus Configuration");
tray.setContextMenu(contextMenu);
tray.on("click", () => {
if (!win) {
createWindow();
} else {
win.show();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
await fastify.listen({ port: 11984 });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
}
};
app.whenReady().then(() => {
protocol.registerBufferProtocol("repens", async (request, callback) => {
let url = new URL(request.url);
let domainInfo = await resolver.resolveRaw(url.hostname, "TXT");
if (url.pathname == "/") {
url.pathname = "/index.html";
}
let txtMap = domainInfo.answer
.filter((rec) => {
return (
rec.type == 16 &&
rec.data.txt.length > 0 &&
rec.data.txt[0].split("=").length > 1
);
})
.map((rec) => [
rec.data.txt[0].split("=")[0],
rec.data.txt[0].split("=").slice(1).join(""),
])
.reduce((pv, cv) => {
if (pv[cv[0]]) {
pv[cv[0]] = [...pv[cv[0]], cv[1]];
} else {
pv[cv[0]] = [cv[1]];
}
return pv;
}, {});
// console.log(domainInfo.authority, domainInfo.additional);
// domainInfo.answer.forEach((e) => console.log(e));
if (!txtMap.repensprotocol || txtMap.repensprotocol[0] != "enabled") {
callback({
statusCode: 850,
data: Buffer.from("Repens protocol is not enabled on this domain"),
});
return;
}
if (
!txtMap.data_hash ||
!txtMap.data_hash[0] ||
!Buffer.from(txtMap.data_hash[0], "hex") ||
Buffer.from(txtMap.data_hash[0], "hex").length != 32
) {
callback({
statusCode: 851,
data: Buffer.from("Invalid data hash"),
});
return;
}
let dataHash = txtMap.data_hash[0];
if (!txtMap.data_way) {
callback({
statusCode: 404,
data: Buffer.from("No ways to fetch content provided"),
});
return;
}
for (const way of txtMap.data_way) {
if (way.split(":").length != 2) {
continue;
}
let method = way.split(":")[0];
let path = way.split(":")[1];
if (!fetchMethods[method]) {
continue;
}
let cid = await fetchMethods[method](path, dataHash, store);
if (cid == null) {
continue;
} else {
let rawArchiveChunks = [];
for await (bf of ipfs.cat(cid)) {
rawArchiveChunks.push(bf);
}
yauzl.fromBuffer(
Buffer.concat(rawArchiveChunks),
{},
async (err, zip) => {
if (err) {
callback({
statusCode: 571,
data: Buffer.from("Failed parsing site archive"),
});
return;
}
let resEntry = null;
let notFoundEntry = null;
zip.on("entry", (entry) => {
if (url.pathname.slice(1) == entry.fileName) {
resEntry = entry;
}
if (
["404.html", "404/index.html", "404.txt"].includes(
entry.fileName
)
) {
notFoundEntry = entry;
}
});
zip.once("end", async () => {
if (!resEntry && !notFoundEntry) {
callback({
statusCode: 404,
data: Buffer.from(
"404: File not found in archive of the resource"
),
});
return;
}
if (!resEntry) {
zip.openReadStream(notFoundEntry, {}, (err, stream) => {
if (err) {
callback({
statusCode: 571,
data: Buffer.from("Failed parsing site archive"),
});
return;
}
let bufferChunks = [];
stream.on("data", (fileData) =>
bufferChunks.push(fileData)
);
stream.once("end", async () => {
callback({
statusCode: 404,
data: Buffer.concat(bufferChunks),
mimeType: mime.getType(notFoundEntry.fileName),
});
return;
});
});
return;
} else {
zip.openReadStream(resEntry, {}, (err, stream) => {
if (err) {
callback({
statusCode: 571,
data: Buffer.from("Failed parsing site archive"),
});
return;
}
let bufferChunks = [];
stream.on("data", (fileData) =>
bufferChunks.push(fileData)
);
stream.once("end", async () => {
callback({
statusCode: 200,
data: Buffer.concat(bufferChunks),
mimeType: mime.getType(resEntry.fileName),
});
return;
});
});
return;
}
});
}
);
}
}
});
start(app);
});
}
startup();