-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhome.js
235 lines (198 loc) · 8.57 KB
/
home.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
// File variable for future use
file = null;
// JavaScript for disabling form submissions if there are invalid fields
/*(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var form = document.getElementById("uploadForm")
// Prevent submission
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
} else{
startUpload();
}
form.classList.add('was-validated')
}, false)
})()*/
// Simple client side validation of file size
function checkFile(videoFile) {
closeFileToBigAlert();
var byteSize = videoFile[0].size;
var mb = ((byteSize / 1024) / 1024).toFixed(4); // Size in MB
if (mb > 500) {
document.getElementById("fileToUpload").value = "";
document.getElementById("fileToBigWarning").style.display = "block";
} else {
//document.getElementById("file-name-info").innerHTML = "Selected: " + videoFile[0].name;
//document.getElementById("file-name-info").style.display = "block";
//document.getElementById("fileToUpload").files = videoFile;
file = videoFile[0];
}
}
// Close the alert message of file to big
function closeFileToBigAlert() {
document.getElementById("fileToBigWarning").style.display = "none";
document.getElementById("fileToUpload").focus();
}
// Drag and Drop on Upload Form
let dropArea = document.getElementById("drop-area");
;["dragenter", "dragover", "dragleave", "drop"].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
})
;["dragenter", "dragover"].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false)
})
;["dragleave", "drop"].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false)
})
dropArea.addEventListener("drop", handleDrop, false);
function handleDrop(e) {
checkFile(e.dataTransfer.files);
document.getElementById("fileToUpload").files = e.dataTransfer.files;
}
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
function highlight(e) {
dropArea.classList.add("highlight");
}
function unhighlight(e) {
dropArea.classList.remove("highlight");
}
// Event listener on the upload form to trigger in a submit event
//async function startUpload() {
document.getElementById("uploadForm").addEventListener("submit", async (event) => {
event.preventDefault();
//if(!valid)
//return
//console.log("Triggered Upload AJAX");
// Disable upload button and file select field
document.getElementById("fileToUpload").setAttribute("disabled", "");
document.getElementById("uploadButton").setAttribute("disabled", "");
document.getElementById("fileSelectButton").setAttribute("disabled", "");
// Show progress bar and status message
document.getElementById("status").style = "display: block;";
document.getElementById("progress-wrapper").style = "display: block;";
// Get the file - redundant since file is now saved in a variable on drop/file select
//var file = document.getElementById("fileToUpload").files[0];
// Create FormData object and append file as "file"
var formData = new FormData();
formData.append("file", file);
// Generate a thumbnail and add to form data
const cover = await getVideoCover(file);
formData.append("thumb", cover);
// Debug: Display the key/value pairs of the formData
/*
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}*/
// Create XMLHttpRequest object
var ajax = new XMLHttpRequest();
// Handle what happens on progress
ajax.upload.onprogress = function (event) {
// Update loaded x of n, round to MB with two decimals TODO: MB calculation is off/to large
//document.getElementById("status").innerHTML = "Uploaded " + Math.round((event.loaded / 1000 / 1000 + Number.EPSILON) * 100) / 100 + " megabytes of " + Math.round((event.total / 1000 / 1000 + Number.EPSILON) * 100) / 100;
document.getElementById("status").innerHTML = "Uploaded " + (((event.loaded - cover.size) / 1024) / 1024).toFixed(2) + " of " + (((event.total - cover.size) / 1024) / 1024).toFixed(2) + "mb";
// Calculate percentage
var percent = (event.loaded / event.total) * 100;
// Insert percentage number into progress bar
var bar = document.getElementById("upload-progress");
bar.setAttribute("aria-valuenow", Math.round(percent));
bar.setAttribute("style", "width: " + Math.round(percent) + "%");
bar.innerHTML = Math.round(percent) + "%";
if(percent == 100) {
document.getElementById("status").innerHTML = "<strong>Please wait for file to be processed! Do not reload/refresh the page, you will be redirected.</strong>";
}
}
// Handle what happens on abort
ajax.onabort = function (e) {
document.getElementById("status").innerHTML = "Upload Aborted";
}
// Handle what happens on error
ajax.onerror = function (e) {
document.getElementById("status").innerHTML = "Upload Failed";
}
// Handle what happens on load
ajax.onload = function (e) {
if (ajax.status >= 200 && ajax.status <= 299) {
console.log(ajax.responseText);
var response = JSON.parse(ajax.responseText);
if (response.error) {
document.getElementById("status").innerHTML = "<b>Server-Side Errors:</b> <br>" + response.error + "<b> Please try to resolve the errors or contact us at info@bruh-clips.com";
} else if (response.location) {
window.location.href = response.location;
}
}
}
// Open upload.php and send POST request
ajax.open("POST", "upload.php");
ajax.send(formData);
});
// Generate a thumbnail for the video file
function getVideoCover(file) {
//console.log("getting video cover for file: ", file);
return new Promise((resolve, reject) => {
// load the file to a video player
const videoPlayer = document.createElement('video');
videoPlayer.setAttribute('src', URL.createObjectURL(file));
videoPlayer.load();
videoPlayer.addEventListener('error', (ex) => {
reject("error when loading video file", ex);
});
// load metadata of the video to get video duration and dimensions
videoPlayer.addEventListener('loadedmetadata', () => {
// delay seeking or else 'seeked' event won't fire on Safari
setTimeout(() => {
videoPlayer.currentTime = videoPlayer.duration * 0.9;
}, 200);
// extract video thumbnail once seeking is complete
videoPlayer.addEventListener('seeked', () => {
//console.log('video is now paused at %ss.', seekTo);
// define a canvas to have the same dimension as the video
const canvas = document.createElement("canvas");
canvas.width = videoPlayer.videoWidth;
canvas.height = videoPlayer.videoHeight;
// draw the video frame to canvas
const ctx = canvas.getContext("2d");
ctx.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);
// return the canvas image as a blob
ctx.canvas.toBlob(
blob => {
resolve(blob);
},
"image/jpeg",
0.75 // quality
);
});
});
});
}
// Helper for fading out elements
function fadeout(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1) {
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 10);
}
// Helper for fading in elements
function fadein(element) {
var op = 0.1; // initial opacity
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1) {
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}