summaryrefslogtreecommitdiff
path: root/index.php
blob: 464433aac5388b7af51da6143bf01204f2be9bd7 (plain)
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
<?php require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/header.php"; ?>

<div class="container">
    <br><br><br><br>

    <div id="box" style="display: grid;grid-template-columns: 1fr 1fr;grid-gap: 50px;background-image: url('/assets/bg.png');background-position-x: right;background-position-y: bottom;background-size: 60vw;background-repeat: no-repeat;">
        <div id="main">
            <input type="file" id="file" style="display: none;" onchange="processFile();">

            <div style="margin-top: 20px; text-align: center;" id="drop-zone" class="disabled">
                <div>
                    <img src="/assets/icons/add.svg" style="width: 64px; margin-bottom: 10px;"><br>
                    <div style="font-weight: bold; font-size: 1.2em;">Drop and drop a file</div>
                    or click to share up to <?= sizeToString(getLimits()['size']) ?>
                    <div style="margin-top: 20px;">
                        <span class="btn btn-primary">Select a file to share</span><br>
                        <div style="margin-top: 10px;">
                            <?php if (!isLoggedIn()): ?>
                                <a class="small" href="/auth/init/" id="login-cta">Sign in to send up to 100 MiB</a>
                            <?php else: ?>
                                <a class="small" href="/plan/" id="login-cta">Contact us to share larger files</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <script>
                document.getElementById("drop-zone").onclick = (e) => {
                    if (e.target?.id !== "login-cta") document.getElementById('file').click();
                }

                document.getElementById("drop-zone").ondragover = (ev) => {
                    console.log("File(s) in drop zone");
                    ev.preventDefault();
                }

                document.getElementById("drop-zone").ondragenter = document.getElementById("drop-zone").ondragstart = () => {
                    document.getElementById("drop-zone").classList.add("drag");
                }

                document.getElementById("drop-zone").ondragleave = document.getElementById("drop-zone").ondragend = () => {
                    document.getElementById("drop-zone").classList.remove("drag");
                }

                window.onbeforeunload = () => {
                    if (connected && canResume && !forceQuit) {
                        return "";
                    }
                }

                document.getElementById("drop-zone").ondrop = (ev) => {
                    console.log("File(s) dropped");
                    ev.preventDefault();

                    if (ev.dataTransfer.items) {
                        let list = [...ev.dataTransfer.items].filter(item => item.kind === "file");

                        if (list.length > 0) {
                            window.file = list[0].getAsFile();
                        }
                    } else {
                        let list = [...ev.dataTransfer.files];

                        if (list.length > 0) {
                            window.file = list[0];
                        }
                    }

                    if (window.file) openFile();
                }
            </script>
        </div>
        <div id="share" style="display: none;">
            <h1>&nbsp;</h1>

            <div class="card" style="margin-top: 5px; margin-bottom: 1rem;">
                <div class="card-body">
                    <p>
                        <b id="file-name">File name</b> · <span id="file-size">123 kB</span><span id="share-error" style="display: none;"> · (reconnecting...)</span>
                        <a class="close-btn" href="/" style="float: right;">
                            <img alt="Cancel" style="height: 24px; width: 24px;" src="/assets/icons/cancel.svg">
                        </a>
                    </p>

                    <div class="progress" style="margin-bottom: 1rem;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-progress" style="width: 100%;" id="share-progress"></div>
                    </div>

                    <div id="file-status">
                        Waiting for the other user to connect...
                    </div>
                </div>
            </div>
            <hr>
            <div id="share-link">Share the following link with the other user:<br><a id="link" style="word-break: break-all;" href="#">https://bridleshare.equestria.dev/?/{code}</a></div>
            <script>
                document.getElementById("link").onclick = (e) => {
                    e.preventDefault();
                    return false;
                }
            </script>
            <div id="share-disclaimer" style="display: none;">The exchanged data cannot be read by anyone other than you and the other user.</div>
        </div>
        <div id="receive" style="display: none;">
            <h1>&nbsp;</h1>

            <div class="card" style="margin-top: 5px; margin-bottom: 1rem;">
                <div class="card-body">
                    <p id="receive-info" style="display: none;">
                        <b id="rfile-name">File name</b> · <span id="rfile-size">123 kB</span><span id="receive-error" style="display: none;"> · (reconnecting...)</span>
                        <a class="close-btn" href="/" style="float: right;">
                            <img alt="Cancel" style="height: 24px; width: 24px;" src="/assets/icons/cancel.svg">
                        </a>
                    </p>
                    <p id="receive-load">
                        Loading...
                        <a class="close-btn" href="/" style="float: right;">
                            <img alt="Cancel" style="height: 24px; width: 24px;" src="/assets/icons/cancel.svg">
                        </a>
                    </p>

                    <div class="progress" style="margin-bottom: 1rem;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-progress" style="width: 100%;" id="receive-progress"></div>
                    </div>

                    <div id="rfile-status">
                        Waiting for the other user to connect...
                    </div>
                </div>
            </div>
            <hr>
            <div>The exchanged data cannot be read by anyone other than you and the other user.</div>
        </div>
        <div>
            <h1 id="title" style="margin-top: 50px;">Simple, secure file sharing</h1>
            <p style="max-width: 600px; margin-top: 20px;">Bridleshare lets you share files with end-to-end encryption and without storing it on a remote server. That way, no one (not even Equestria.dev) has access to your files, so that your private data stays private.</p>
        </div>
    </div>
</div>

<script>
    if (location.search.split("/")[1]) {
        window.fileID = location.search.split("/")[1];
        document.getElementById("main").style.display = "none";
    }

    window.currentID = null;
    window.currentSpeed = 0;
    window.maxSpeed = <?= getLimits()['speed'] ?> / 2;
    window.file = null;
    window.keyChain = null;
    window.forceQuit = false;

    function formatSize(size) {
        if (size > 1024) {
            if (size > 1024**2) {
                if (size > 1024**3) {
                    if (size > 1024**4) {
                        return (size / 1024**4).toFixed(1) + " TiB";
                    } else {
                        return (size / 1024**3).toFixed(1) + " GiB";
                    }
                } else {
                    return (size / 1024**2).toFixed(1) + " MiB";
                }
            } else {
                return (size / 1024).toFixed(1) + " KiB";
            }
        } else {
            return size + " B";
        }
    }

    function openFile() {
        console.log(file);

        document.getElementById("file-name").innerText = file.name;
        document.getElementById("file-size").innerText = formatSize(file.size);

        document.getElementById("main").style.display = "none";
        document.getElementById("share").style.display = "";
        canResume = true;
    }

    function processFile() {
        if (document.getElementById("file").files.length > 0) {
            window.file = document.getElementById("file").files[0];
            openFile();
        }
    }

    let connected = false;
    let connecting = false;
    let canResume = false;
    let allowCrash = true;
    let totalReceived = 0;
    let blob = new Blob();

    window.fileSize = 0;
    window.pos = 0;

    setInterval(() => {
        if (connected) {
            ws.send(JSON.stringify({
                type: "keepalive"
            }));
        }
    }, 2000);

    function connect() {
        connecting = true;
        window.ws = new WebSocket("wss://bridleshare.equestria.dev/ws");

        ws.onopen = (event) => {
            console.log(event);
        }

        async function sendEncrypted(message, cb) {
            ws.send(JSON.stringify({
                type: "encrypted",
                message: await BridleshareCrypt.encrypt(JSON.stringify(message), keyChain.chain)
            }), cb ?? function () {});
        }

        function generateStatus(up, done, total) {
            let eta = (1 / currentSpeed) * (total - done);
            let etaString;

            if (isFinite(eta) && !isNaN(eta)) {
                if (eta > 3600) {
                    etaString = Math.round(eta / 3600) + " hour" + (Math.round(eta / 3600) > 1 ? "s" : "");
                } else if (eta > 60) {
                    etaString = Math.round(eta / 60) + " minute" + (Math.round(eta / 60) > 1 ? "s" : "");
                } else {
                    etaString = Math.round(eta) + " second" + (Math.round(eta) > 1 ? "s" : "");
                }
            }

            return (up ? "↑ " : "↓ ") + formatSize(currentSpeed) + "/s · " + formatSize(done) + "/" + formatSize(total) + (etaString ? (" · " + etaString) : "");
        }

        let lastChunk;

        async function nextChunk(pos) {
            let chunkSize = maxSpeed / 2;
            let chunks = Math.ceil(file.size / chunkSize);

            function readArrayBuffer(file, offset, size) {
                return new Promise((res) => {
                    let reader = new FileReader();
                    let blob = file.slice(offset, offset + size);

                    reader.onload = (event) => {
                        res(reader.result);
                    }

                    reader.readAsArrayBuffer(blob);
                });
            }

            let ab = await readArrayBuffer(file, pos * chunkSize, chunkSize);

            if (ab.byteLength > 0) {
                ws.send(JSON.stringify({
                    type: "encryptedData",
                    message: await BridleshareCrypt.encryptBuffer(ab, keyChain.chain)
                }));
            } else {
                sendEncrypted({
                    type: "end"
                });

                document.getElementById("file-status").innerText = document.getElementById("rfile-status").innerText = "Transfer completed successfully";
                document.getElementById("receive-progress").className = document.getElementById("share-progress").className = "progress-bar bg-success";
            }

            let done = pos * chunkSize + chunkSize;
            let total = file.size;
            if (done > total) done = total;
            let percentage = (done / total) * 100;

            if (lastChunk) {
                currentSpeed = ab.byteLength / ((new Date().getTime() / 1000) - lastChunk);
                lastChunk = new Date().getTime() / 1000;
            } else {
                lastChunk = new Date().getTime() / 1000;
            }

            document.getElementById("share-progress").className = "progress-bar bg-primary";
            document.getElementById("receive-error").style.display = document.getElementById("share-error").style.display = "none";
            document.getElementById("share-progress").style.width = percentage + "%";
            document.getElementById("file-status").innerText = generateStatus(true, done, total);
        }

        ws.onmessage = (event) => {
            try {
                let data = JSON.parse(event.data);
                if (data.type !== "encrypted" && data.type !== "encryptedData") console.log(data);

                if (data.type === "encryptedData") {
                    BridleshareCrypt.decryptBuffer(data.message, keyChain.chain).then((ab) => {
                        blob = new Blob([blob, ab], {
                            type: window.fileType
                        });

                        totalReceived = totalReceived + ab.byteLength;
                        let total = window.fileSize;
                        let percentage = (totalReceived / total) * 100;

                        if (lastChunk) {
                            currentSpeed = ab.byteLength / ((new Date().getTime() / 1000) - lastChunk);
                            lastChunk = new Date().getTime() / 1000;
                        } else {
                            lastChunk = new Date().getTime() / 1000;
                        }

                        document.getElementById("receive-progress").className = "progress-bar bg-primary";
                        document.getElementById("receive-error").style.display = document.getElementById("share-error").style.display = "none";
                        document.getElementById("receive-progress").style.width = percentage + "%";
                        document.getElementById("rfile-status").innerText = generateStatus(false, totalReceived, total);

                        if (connected) {
                            pos++;

                            sendEncrypted({
                                type: "next",
                                chunk: pos
                            });
                        }
                    });
                }

                if (data.type === "encrypted") {
                    BridleshareCrypt.decrypt(data.message, keyChain.chain).then((msg) => {
                        let data = JSON.parse(msg);
                        console.log(data);

                        if (data.type === "end") {
                            document.getElementById("file-status").innerText = document.getElementById("rfile-status").innerText = "Transfer completed successfully";
                            document.getElementById("receive-progress").className = document.getElementById("share-progress").className = "progress-bar bg-success";

                            if (window.fileID) {
                                sendEncrypted({
                                    type: "end"
                                });

                                console.log(blob);

                                let dl = document.createElement("a");
                                dl.href = URL.createObjectURL(blob);
                                dl.download = document.getElementById("rfile-name").innerText.trim();
                                dl.click();
                            }
                        }

                        if (data.type === "next") {
                            nextChunk(data.chunk);
                        }

                        if (data.type === "metadata") {
                            document.getElementById("receive-load").style.display = "none";
                            document.getElementById("receive-info").style.display = "";
                            document.getElementById("rfile-name").innerText = data.name;
                            document.getElementById("rfile-size").innerText = formatSize(data.size);

                            window.fileType = data.mime;
                            window.fileSize = data.size;

                            document.getElementById("file-status").innerText = document.getElementById("rfile-status").innerText = "Waiting for transfer to start...";

                            sendEncrypted({
                                type: "next",
                                chunk: pos
                            });
                        }
                    });
                }

                if (data.type === "key") {
                    document.getElementById("file-status").innerText = document.getElementById("rfile-status").innerText = "Importing keys...";

                    BridleshareCrypt.importKey(data.key).then((ks) => {
                        window.keyChain = ks;

                        document.getElementById("share-link").style.display = "none";
                        document.getElementById("share-disclaimer").style.display = "";

                        allowCrash = false;

                        if (window.file) {
                            document.getElementById("file-status").innerText = document.getElementById("rfile-status").innerText = "Sending metadata...";

                            sendEncrypted({
                                type: "metadata",
                                name: window.file.name,
                                size: window.file.size,
                                mime: window.file.type
                            });

                            document.getElementById("file-status").innerText = document.getElementById("rfile-status").innerText = "Waiting for receiver to be ready...";
                        } else {
                            document.getElementById("file-status").innerText = document.getElementById("rfile-status").innerText = "Waiting for metadata...";
                        }
                    });
                }

                if ((data.type === "error" && allowCrash) || data.type === "left") {
                    window.forceQuit = true;
                    location.href = "/";
                    return;
                }

                if (data.type === "init") {
                    document.getElementById("link").innerText = document.getElementById("link").href = document.getElementById("link").innerText.replace("{code}", data.code);
                    if (!window.currentID) window.currentID = data.code;

                    BridleshareCrypt.generateKey().then((key) => {
                        ws.send(JSON.stringify({
                            type: "keys",
                            key: key.exported,
                            peer: window.fileID ?? null,
                            me: window.currentID ?? null
                        }));

                        connected = true;

                        if (window.fileID) {
                            document.getElementById("file-status").innerText = document.getElementById("rfile-status").innerText = "Connecting to sender...";
                            canResume = true;
                            document.getElementById("receive").style.display = "";
                        } else {
                            document.getElementById("drop-zone").classList.remove("disabled");
                        }
                    })
                }
            } catch (e) {
                console.error(e);
                console.log(event);
            }
        }

        ws.onclose = (event) => {
            console.log(event);
            connected = false;
            connecting = false;

            if (canResume) {
                document.getElementById("receive-progress").className = document.getElementById("share-progress").className = "progress-bar bg-danger";
                document.getElementById("receive-error").style.display = document.getElementById("share-error").style.display = "";

                setTimeout(() => {
                    connect();
                }, 1000);
            }
        }

        ws.onerror = (event) => {
            console.log(event);
        }
    }

    connect();
</script>

<?php require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/footer.php"; ?>