summaryrefslogtreecommitdiff
path: root/public/static/scripts/upload.js
blob: f180d9a5a77271032390fc926f327aec7b6efbff (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
function createUploadedFileItem(data) {
    const base = document.createElement("div");
    base.classList.add("box", "item", "column", "gap-4", "pad-4");

    const previewContainer = document.createElement("div");
    previewContainer.classList.add("column", "align-center", "justify-center", "grow");
    base.appendChild(previewContainer);

    const preview = document.createElement("img");
    preview.alt = "No thumbnail.";
    previewContainer.appendChild(preview);

    const header = document.createElement("h2");
    base.appendChild(header);

    const description = document.createElement("div");
    base.appendChild(description);

    const buttons = document.createElement("div");
    buttons.classList.add("row", "gap-8");
    base.appendChild(buttons);

    if (data) {
        if (data.mime.startsWith("audio/")) {
            preview.src = "/static/img/icons/file_audio.png";
        } else if (data.mime.startsWith("text/")) {
            preview.src = "/static/img/icons/file_text.png";
        } else if (data.mime == "application/x-shockwave-flash") {
            preview.src = "/static/img/icons/file_flash.png";
        } else if (!data.mime.startsWith("image/") && !data.mime.startsWith("video/")) {
            preview.src = "/static/img/icons/file.png";
        } else {
            preview.src = `${thumbnailPathPrefix}/${data.id}.webp`;
        }

        header.textContent = `${data.id}.${data.extension}`;

        const mime = document.createElement("p");
        description.appendChild(mime);
        mime.textContent = data.mime;

        const size = document.createElement("p");
        description.appendChild(size);
        size.textContent = (data.size / 1024 / 1024).toFixed(2) + " MB";

        if (data.id && data.extension) {
            const url = `${window.location.href}${data.id}.${data.extension}`;
            const link = document.createElement("a");
            link.href = url;
            const btn = document.createElement("button");
            btn.textContent = "Open";
            link.appendChild(btn);
            buttons.appendChild(link);

            const copyBtn = document.createElement("button");
            copyBtn.addEventListener("click", () => {
                navigator.clipboard.writeText(url);
            });
            const copyImg = document.createElement("img");
            copyImg.src = "/static/img/icons/paste_plain.png";
            copyBtn.appendChild(copyImg);
            buttons.appendChild(copyBtn);
        }

        if (data.urls && data.urls.deletion_url) {
            const btn = document.createElement("button");
            btn.addEventListener("click", () => {
                deleteUploadedFile(data.urls.deletion_url, data.id);
            });

            const img = document.createElement("img");
            img.src = "/static/img/icons/cross.png";
            btn.appendChild(img);

            buttons.appendChild(btn);
        }
    }

    return {
        "base": base,
        "preview": preview,
        "header": header,
        "description": description,
        "buttons": buttons
    };
}

function getUploadedFiles() {
    const files = JSON.parse(localStorage.getItem("uploaded_files") ?? "[]");
    return files;
}

function saveUploadedFile(data) {
    const files = getUploadedFiles();
    files.unshift(data);
    localStorage.setItem("uploaded_files", JSON.stringify(files));
}

function displayUploadedFile(data) {
    const items = document.getElementById("uploaded-files");
    if (items) {
        items.prepend(createUploadedFileItem(data).base);
    }
}

function displayUploadedFiles() {
    const files = getUploadedFiles();
    for (const file of files) {
        displayUploadedFile(file);
    }
}

function deleteUploadedFile(url, id) {
    if (confirm("Do you want to delete file locally?")) {
        let files = getUploadedFiles();
        files = files.filter((x) => x.id !== id);
        localStorage.setItem("uploaded_files", JSON.stringify(files));
    }

    if (url && confirm(`Are you sure you want to delete file ID ${id} from the servers?`)) {
        fetch(url, {
            'headers': {
                'Accept': 'application/json'
            },
            'method': 'DELETE'
        }).then((r) => r.json())
            .then((json) => {
                if (json.status_code != 200) {
                    alert(`${json.message} (${json.status_code})`);
                }
            })
            .catch((err) => {
                alert('Failed to delete the file. Look into the console!');
                console.error(err);
            });
    }
}

function uploadData(data) {
    const status = document.createElement("p");

    const bar = document.createElement("progress");
    bar.max = 100;

    const item = createUploadedFileItem(null);
    item.description.appendChild(bar);
    item.description.appendChild(status);

    // setting item name
    if (data.get("file") != null) {
        let name = data.get("file").name;
        if (name.length > 10) {
            name = name.substring(0, 7) + '...';
        }
        item.header.textContent = name;
        item.header.style.fontStyle = "italic";
    }

    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload.php');
    xhr.setRequestHeader("Accept", "application/json");

    xhr.upload.onprogress = (e) => {
        if (e.lengthComputable) {
            const percent = Math.round((e.loaded / e.total) * 100);
            bar.value = percent;
            status.textContent = `Uploading file: ${percent}%`;
        } else {
            status.textContent = "Uploading...";
        }
    };

    xhr.onload = () => {
        const j = JSON.parse(xhr.responseText);

        if (xhr.status == 201) {
            status.textContent = "Uploaded!";
            bar.value = 100;

            const d = j.data;
            item.base.remove();
            saveUploadedFile(d);
            displayUploadedFile(d);
        } else {
            status.textContent = `Upload failed: ${j.message} (${xhr.status})`;
            item.buttons.remove();
        }
    };

    xhr.onerror = () => {
        status.textContent = "Upload error";
        item.buttons.remove();
    };

    xhr.send(data);

    const abortButton = document.createElement("button");
    abortButton.addEventListener("click", () => {
        xhr.abort();
        item.base.remove();
        alert("File upload has been aborted.");
    });
    item.buttons.appendChild(abortButton);
    const abortButtonImg = document.createElement("img");
    abortButtonImg.alt = "Abort";
    abortButtonImg.src = "/static/img/icons/cross.png";
    abortButton.appendChild(abortButtonImg);

    const items = document.getElementById("uploaded-files");
    if (items) {
        items.prepend(item.base);
    }
}

window.addEventListener("load", () => {
    const itemsElement = document.getElementById("uploaded-files");
    if (!itemsElement) return;

    const files = getUploadedFiles();
    files.forEach((x) => {
        const item = createUploadedFileItem(x);
        itemsElement.appendChild(item.base);
    });
});