-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.ts
412 lines (351 loc) · 10.2 KB
/
main.ts
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
import Bencode from './bencode/index.js';
import { Buffer } from 'buffer';
import ClipboardJS from 'clipboard';
import FileSaver from 'file-saver';
import Key from 'keymaster';
import LZString from 'lz-string';
import Ace from 'ace-builds';
import 'ace-builds/src-min-noconflict/mode-json';
import 'ace-builds/src-min-noconflict/ext-searchbox';
/// helper functions
// https://github.com/microsoft/TypeScript/pull/33050#issuecomment-543365074
interface RecordOf<T>
{
[_: string]: T;
}
function isString(s: any): s is string
{
return (Object.prototype.toString.call(s) === "[object String]");
}
function loadFile(blob: Blob): Promise<ArrayBuffer>
{
return new Promise((resolve, _reject) => {
const reader = new FileReader();
reader.onload = () => { resolve(reader.result as ArrayBuffer); };
reader.readAsArrayBuffer(blob);
});
}
function tryEncodeHexstring(data: ArrayBuffer): string
{
const isValidUtf8String = (str: string): boolean =>
{
const replacementChar = '\uFFFD'; // U+FFFD REPLACEMENT CHARACTER
return (str.indexOf(replacementChar) === -1);
};
const encodeToHexstring = (buf: Buffer): string =>
{
// example: <hex>0A 0B 0C ...</hex>
const hexStr = buf.toString('hex').toUpperCase();
let str = "";
for (let i = 0; i < hexStr.length; i += 2)
str += (hexStr.substr(i, 2) + " ");
str = `<hex>${str.trim()}</hex>`;
return str;
};
const str = data.toString();
return isValidUtf8String(str)
? str
: encodeToHexstring(Buffer.from(data));
}
function tryDecodeHexstring(str: string): Buffer
{
const isHexstring = (str: string): boolean =>
{
const re = /<hex>[0-9a-f ]+<\/hex>/gi;
return re.test(str);
};
const decodeToBuffer = (hex: string): Buffer =>
{
const str = hex.substring(5, (hex.length - 6)).replace(/ /g, "");
return Buffer.from(str, 'hex');
};
return isHexstring(str)
? decodeToBuffer(str)
: Buffer.from(str);
}
type EncodeInTypes = number | Uint8Array | Array<EncodeInTypes> | Map<any, EncodeInTypes>;
type EncodeOutTypes = number | string | Array<EncodeOutTypes> | RecordOf<EncodeOutTypes>;
function encodeToArray(data: Array<EncodeInTypes>): Array<EncodeOutTypes>
{
const ret = [];
for (const val of data)
{
if (typeof val === "number")
{
ret.push(val);
}
else if (val instanceof Uint8Array)
{
ret.push(tryEncodeHexstring(val));
}
else if (val instanceof Array)
{
ret.push(encodeToArray(val));
}
else if (val instanceof Map)
{
ret.push(encodeToObject(val));
}
else
{
//throw new Error("Type unhandled: " + typeof val + "\nValue: " + val);
}
}
return ret;
}
function encodeToObject(data: Map<Buffer, EncodeInTypes>): Record<string, EncodeOutTypes>
{
const ret: ReturnType<typeof encodeToObject> = {};
for (const [key, val] of data)
{
const keyString = tryEncodeHexstring(key);
if (typeof val === "number")
{
ret[keyString] = val;
}
else if (val instanceof Uint8Array)
{
ret[keyString] = tryEncodeHexstring(val);
}
else if (val instanceof Array)
{
ret[keyString] = encodeToArray(val);
}
else if (val instanceof Map)
{
ret[keyString] = encodeToObject(val);
}
else
{
//throw new Error("Type unhandled: " + typeof val + "\nValue: " + val);
}
}
return ret;
}
type DecodeInTypes = number | string | Array<DecodeInTypes> | RecordOf<DecodeInTypes>;
type DecodeOutTypes = Buffer | number | Array<DecodeOutTypes> | Map<any, DecodeOutTypes>;
function decodeToArray(data: Array<DecodeInTypes>): Array<DecodeOutTypes>
{
const ret = [];
for (const val of data)
{
if (typeof val === "number")
{
ret.push(val);
}
else if (isString(val))
{
ret.push(tryDecodeHexstring(val));
}
else if (val instanceof Array)
{
ret.push(decodeToArray(val));
}
else if (val instanceof Object)
{
ret.push(decodeToMap(val));
}
else
{
//throw new Error("Type unhandled: " + typeof val + "\nValue: " + val);
}
}
return ret;
}
function decodeToMap(data: Record<string, DecodeInTypes>): Map<Buffer, DecodeOutTypes>
{
const ret = new Map();
for (const [key, val] of Object.entries(data))
{
const keyString = tryDecodeHexstring(key);
if (typeof val === "number")
{
ret.set(keyString, val);
}
else if (isString(val))
{
ret.set(keyString, tryDecodeHexstring(val));
}
else if (val instanceof Array)
{
ret.set(keyString, decodeToArray(val));
}
else if (val instanceof Object)
{
ret.set(keyString, decodeToMap(val));
}
else
{
//throw new Error("Type unhandled: " + typeof val + "\nValue: " + val);
}
}
return ret;
}
/// End of helper functions
class Session
{
constructor(editorText: string)
{
this.editorText = editorText;
if (this.editorText.length > 0)
this.valid = true;
}
serialize(): string
{
const object = {
"editorText": this.editorText
};
// https://github.com/pieroxy/lz-string/pull/127
const compressed = LZString.compressToEncodedURIComponent(JSON.stringify(object));
return compressed.replace(/\+/g, '_').replace(/\$/g, '.');
}
static deserialize(encoded: string): Session
{
const decoded = encoded.replace(/\./g, '$').replace(/_/g, '+');
const decompressed = LZString.decompressFromEncodedURIComponent(decoded);
if ((decompressed === null) || (decompressed.length <= 0))
return new Session("");
let data;
try {
data = JSON.parse(decompressed);
}
catch (exception: any) {
if (!(exception instanceof SyntaxError))
alert(exception.message);
return new Session("");
}
if (!Object.prototype.hasOwnProperty.call(data, "editorText"))
return new Session("");
return new Session(data.editorText);
}
editorText = "";
valid = false;
}
function main(): void
{
// editor configs
const jsonEditor = document.getElementById('jsonEditor')!;
const editor = Ace.edit(jsonEditor);
editor.getSession().setMode('ace/mode/json');
editor.setShowPrintMargin(false);
editor.setFontSize(14);
// Characters stop showing up after the 10000th charater in a line
// https://github.com/ajaxorg/ace/issues/3983
(editor.renderer as any).$textLayer.MAX_LINE_LENGTH=Infinity;
const setEditorValue = (str: string): void =>
{
editor.setValue(str);
editor.gotoLine(0, 0, undefined!);
editor.scrollToLine(0, undefined!, undefined!, undefined!);
editor.focus();
};
const loadData = (fileName: string, data: Buffer): void =>
{
let decoded;
try
{
decoded = Bencode.decode(data);
}
catch (_exception)
{
editor.setValue(`Error: "${fileName}" is not a valid bencoded file\n`);
return;
}
const result = encodeToObject(decoded);
setEditorValue(JSON.stringify(result, null, 3) + "\n");
};
const handleFilesInput = async (files: FileList): Promise<void> =>
{
editor.setValue("");
// only handle the first file
const fileBlob = files[0];
const buf = Buffer.from(await loadFile(fileBlob));
loadData(fileBlob.name, buf);
};
jsonEditor.addEventListener('dragover', (ev: DragEvent) => { if (ev.preventDefault) ev.preventDefault(); });
jsonEditor.addEventListener('dragenter', (ev: DragEvent) => { if (ev.preventDefault) ev.preventDefault(); });
jsonEditor.addEventListener("drop", async (ev: DragEvent) => {
if (ev.preventDefault)
ev.preventDefault();
await handleFilesInput(ev.dataTransfer!.files);
});
const fileInput = document.getElementById('fileInput')!;
fileInput.addEventListener("change", async function(this: HTMLInputElement) {
await handleFilesInput(this.files!);
});
const onOpenFile = () => {
const fileInput = document.getElementById('fileInput')!;
fileInput.click();
};
const openfileButton = document.getElementById("openfileButton")!;
openfileButton.addEventListener("click", onOpenFile);
const shareButton = document.getElementById('shareButton')!;
const shareButtonText = shareButton.firstChild!.nodeValue;
if (ClipboardJS.isSupported()) {
const clipboard = new ClipboardJS(shareButton, {
text: (_elem) => {
const url = new URL(location.href);
url.hash = (new Session(editor.getValue())).serialize();
history.replaceState(null, "", url.href);
return url.href;
}
});
clipboard.on('success', async (_e) => {
shareButton.firstChild!.nodeValue = "OK!";
const _sleep = await new Promise((resolve, _reject) => { setTimeout(resolve, 1500); });
shareButton.firstChild!.nodeValue = shareButtonText;
});
}
const onSave = () => {
const text = editor.getValue();
if (text.length === 0)
return;
let data: Buffer;
try
{
const obj = JSON.parse(text);
const obj2 = decodeToMap(obj);
data = Bencode.encode(obj2);
}
catch (exception: any)
{
alert("Save error:\n" + exception.message);
return;
}
const blob = new Blob([data], {type: 'application/octet-stream'});
FileSaver.saveAs(blob, "file");
};
const saveBtn = document.getElementById("saveButton")!;
saveBtn.addEventListener("click", onSave);
const loadExampleBtn = document.getElementById("loadExampleButton")!;
loadExampleBtn.addEventListener("click", () => {
const exampleFileName = "bbb_sunflower_1080p_60fps_normal.mp4.torrent";
const xreq = new XMLHttpRequest();
xreq.onreadystatechange = () => {
if ((xreq.readyState !== XMLHttpRequest.DONE) || (xreq.status !== 200))
return;
loadData(exampleFileName, xreq.response);
};
xreq.open("GET", exampleFileName);
xreq.responseType = "arraybuffer";
xreq.send();
});
// keyboard shortcuts
Key.filter = (_event) => { return true; };
Key('ctrl+o, command+o', () => {
onOpenFile();
return false;
});
Key('ctrl+s, command+s', () => {
onSave();
return false;
});
// load data from URI fragment
const compressedHash = document.location.hash.slice(1);
if (compressedHash.length > 0) {
const session = Session.deserialize(compressedHash);
if (session.valid)
setEditorValue(session.editorText);
}
}
main();