]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blob - frontend/js/app.js
Add upload progress to ui
[perso/Immae/Projets/Nodejs/Surfer.git] / frontend / js / app.js
1 (function () {
2 'use strict';
3
4 // poor man's async
5 function asyncForEach(items, handler, callback) {
6 var cur = 0;
7
8 if (items.length === 0) return callback();
9
10 (function iterator() {
11 handler(items[cur], function (error) {
12 if (error) return callback(error);
13 if (cur >= items.length-1) return callback();
14 ++cur;
15
16 iterator();
17 });
18 })();
19 }
20
21 function getProfile(accessToken, callback) {
22 superagent.get('/api/profile').query({ access_token: accessToken }).end(function (error, result) {
23 app.ready = true;
24
25 if (error && !error.response) return callback(error);
26 if (result.statusCode !== 200) {
27 delete localStorage.accessToken;
28 return callback('Invalid access token');
29 }
30
31 localStorage.accessToken = accessToken;
32 app.session.username = result.body.username;
33 app.session.valid = true;
34
35 superagent.get('/api/settings').query({ access_token: localStorage.accessToken }).end(function (error, result) {
36 if (error) console.error(error);
37
38 app.folderListingEnabled = !!result.body.folderListingEnabled;
39
40 callback();
41 });
42 });
43 }
44
45 function sanitize(filePath) {
46 filePath = '/' + filePath;
47 return filePath.replace(/\/+/g, '/');
48 }
49
50 function encode(filePath) {
51 return filePath.split('/').map(encodeURIComponent).join('/');
52 }
53
54 function decode(filePath) {
55 return filePath.split('/').map(decodeURIComponent).join('/');
56 }
57
58 var mimeTypes = {
59 images: [ '.png', '.jpg', '.jpeg', '.tiff', '.gif' ],
60 text: [ '.txt', '.md' ],
61 pdf: [ '.pdf' ],
62 html: [ '.html', '.htm', '.php' ],
63 video: [ '.mp4', '.mpg', '.mpeg', '.ogg', '.mkv' ]
64 };
65
66 function getPreviewUrl(entry, basePath) {
67 var path = '/_admin/img/';
68
69 if (entry.isDirectory) return path + 'directory.png';
70 if (mimeTypes.images.some(function (e) { return entry.filePath.endsWith(e); })) return sanitize(basePath + '/' + entry.filePath);
71 if (mimeTypes.text.some(function (e) { return entry.filePath.endsWith(e); })) return path +'text.png';
72 if (mimeTypes.pdf.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'pdf.png';
73 if (mimeTypes.html.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'html.png';
74 if (mimeTypes.video.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'video.png';
75
76 return path + 'unknown.png';
77 }
78
79 // simple extension detection, does not work with double extension like .tar.gz
80 function getExtension(entry) {
81 if (entry.isFile) return entry.filePath.slice(entry.filePath.lastIndexOf('.') + 1);
82 return '';
83 }
84
85 function refresh() {
86 loadDirectory(app.path);
87 }
88
89 function loadDirectory(filePath) {
90 app.busy = true;
91
92 filePath = filePath ? sanitize(filePath) : '/';
93
94 superagent.get('/api/files/' + encode(filePath)).query({ access_token: localStorage.accessToken }).end(function (error, result) {
95 app.busy = false;
96
97 if (result && result.statusCode === 401) return logout();
98 if (error) return console.error(error);
99
100 result.body.entries.sort(function (a, b) { return a.isDirectory && b.isFile ? -1 : 1; });
101 app.entries = result.body.entries.map(function (entry) {
102 entry.previewUrl = getPreviewUrl(entry, filePath);
103 entry.extension = getExtension(entry);
104 return entry;
105 });
106 app.path = filePath;
107 app.pathParts = decode(filePath).split('/').filter(function (e) { return !!e; }).map(function (e, i, a) {
108 return {
109 name: e,
110 link: '#' + sanitize('/' + a.slice(0, i).join('/') + '/' + e)
111 };
112 });
113
114 // update in case this was triggered from code
115 window.location.hash = app.path;
116 });
117 }
118
119 function open(row, event, column) {
120 var path = sanitize(app.path + '/' + row.filePath);
121
122 if (row.isDirectory) {
123 window.location.hash = path;
124 return;
125 }
126
127 window.open(encode(path));
128 }
129
130 function uploadFiles(files) {
131 if (!files || !files.length) return;
132
133 app.uploadStatus.busy = true;
134 app.uploadStatus.count = files.length;
135 app.uploadStatus.size = 0;
136 app.uploadStatus.done = 0;
137 app.uploadStatus.percentDone = 0;
138
139 for (var i = 0; i < files.length; ++i) {
140 app.uploadStatus.size += files[i].size;
141 }
142
143 asyncForEach(files, function (file, callback) {
144 var path = encode(sanitize(app.path + '/' + (file.webkitRelativePath || file.name)));
145
146 var formData = new FormData();
147 formData.append('file', file);
148
149 superagent.post('/api/files' + path)
150 .query({ access_token: localStorage.accessToken })
151 .send(formData)
152 .on('progress', function (event) {
153 app.uploadStatus.done += event.loaded;
154 app.uploadStatus.percentDone = Math.round(app.uploadStatus.done / app.uploadStatus.size * 100);
155 }).end(function (error, result) {
156 if (result && result.statusCode === 401) return logout();
157 if (result && result.statusCode !== 201) return callback('Error uploading file: ', result.statusCode);
158 if (error) return callback(error);
159
160 callback();
161 });
162 }, function (error) {
163 if (error) console.error(error);
164
165 app.uploadStatus.busy = false;
166 app.uploadStatus.count = 0;
167 app.uploadStatus.size = 0;
168 app.uploadStatus.done = 0;
169 app.uploadStatus.percentDone = 100;
170
171 refresh();
172 });
173 }
174
175 function dragOver(event) {
176 event.stopPropagation();
177 event.preventDefault();
178 event.dataTransfer.dropEffect = 'copy';
179 }
180
181 function drop(event) {
182 event.stopPropagation();
183 event.preventDefault();
184
185 if (!event.dataTransfer.items[0]) return;
186
187 // figure if a folder was dropped on a modern browser, in this case the first would have to be a directory
188 var folderItem;
189 try {
190 folderItem = event.dataTransfer.items[0].webkitGetAsEntry();
191 if (folderItem.isFile) return uploadFiles(event.dataTransfer.files);
192 } catch (e) {
193 return uploadFiles(event.dataTransfer.files);
194 }
195
196 // if we got here we have a folder drop and a modern browser
197 // now traverse the folder tree and create a file list
198 app.uploadStatus.busy = true;
199 app.uploadStatus.uploadListCount = 0;
200
201 var fileList = [];
202 function traverseFileTree(item, path, callback) {
203 if (item.isFile) {
204 // Get file
205 item.file(function (file) {
206 fileList.push(file);
207 ++app.uploadStatus.uploadListCount;
208 callback();
209 });
210 } else if (item.isDirectory) {
211 // Get folder contents
212 var dirReader = item.createReader();
213 dirReader.readEntries(function (entries) {
214 asyncForEach(entries, function (entry, callback) {
215 traverseFileTree(entry, path + item.name + '/', callback);
216 }, callback);
217 });
218 }
219 }
220
221 traverseFileTree(folderItem, '', function (error) {
222 app.uploadStatus.busy = false;
223 app.uploadStatus.uploadListCount = 0;
224
225 if (error) return console.error(error);
226
227 uploadFiles(fileList);
228 });
229 }
230
231 var app = new Vue({
232 el: '#app',
233 data: {
234 ready: false,
235 busy: false,
236 uploadStatus: {
237 busy: false,
238 count: 0,
239 done: 0,
240 percentDone: 50,
241 uploadListCount: 0
242 },
243 path: '/',
244 pathParts: [],
245 session: {
246 valid: false
247 },
248 folderListingEnabled: false,
249 loginData: {
250 username: '',
251 password: '',
252 busy: false
253 },
254 entries: []
255 },
256 methods: {
257 onLogin: function () {
258 var that = this;
259
260 that.loginData.busy = true;
261
262 superagent.post('/api/login').send({ username: that.loginData.username, password: that.loginData.password }).end(function (error, result) {
263 that.loginData.busy = false;
264
265 if (error && !result) return that.$message.error(error.message);
266 if (result.statusCode === 401) return that.$message.error('Wrong username or password');
267
268 getProfile(result.body.accessToken, function (error) {
269 if (error) return console.error(error);
270
271 loadDirectory(window.location.hash.slice(1));
272 });
273 });
274 },
275 onOptionsMenu: function (command) {
276 var that = this;
277
278 if (command === 'folderListing') {
279 superagent.put('/api/settings').send({ folderListingEnabled: this.folderListingEnabled }).query({ access_token: localStorage.accessToken }).end(function (error) {
280 if (error) console.error(error);
281 });
282 } else if (command === 'about') {
283 this.$msgbox({
284 title: 'About Surfer',
285 message: 'Surfer is a static file server written by <a href="https://cloudron.io" target="_blank">Cloudron</a>.<br/><br/>The source code is licensed under MIT and available <a href="https://git.cloudron.io/cloudron/surfer" target="_blank">here</a>.',
286 dangerouslyUseHTMLString: true,
287 confirmButtonText: 'OK',
288 showCancelButton: false,
289 type: 'info',
290 center: true
291 }).then(function () {}).catch(function () {});
292 } else if (command === 'logout') {
293 superagent.post('/api/logout').query({ access_token: localStorage.accessToken }).end(function (error) {
294 if (error) console.error(error);
295
296 that.session.valid = false;
297
298 delete localStorage.accessToken;
299 });
300 }
301 },
302 onDownload: function (entry) {
303 if (entry.isDirectory) return;
304 window.location.href = encode('/api/files/' + sanitize(this.path + '/' + entry.filePath)) + '?access_token=' + localStorage.accessToken;
305 },
306 onUpload: function () {
307 var that = this;
308
309 $(this.$refs.upload).on('change', function () {
310 // detach event handler
311 $(that.$refs.upload).off('change');
312 uploadFiles(that.$refs.upload.files || []);
313 });
314
315 // reset the form first to make the change handler retrigger even on the same file selected
316 this.$refs.upload.value = '';
317 this.$refs.upload.click();
318 },
319 onUploadFolder: function () {
320 var that = this;
321
322 $(this.$refs.uploadFolder).on('change', function () {
323 // detach event handler
324 $(that.$refs.uploadFolder).off('change');
325 uploadFiles(that.$refs.uploadFolder.files || []);
326 });
327
328 // reset the form first to make the change handler retrigger even on the same file selected
329 this.$refs.uploadFolder.value = '';
330 this.$refs.uploadFolder.click();
331 },
332 onDelete: function (entry) {
333 var that = this;
334
335 var title = 'Really delete ' + (entry.isDirectory ? 'folder ' : '') + entry.filePath;
336 this.$confirm('', title, { confirmButtonText: 'Yes', cancelButtonText: 'No' }).then(function () {
337 var path = encode(sanitize(that.path + '/' + entry.filePath));
338
339 superagent.del('/api/files' + path).query({ access_token: localStorage.accessToken, recursive: true }).end(function (error, result) {
340 if (result && result.statusCode === 401) return logout();
341 if (result && result.statusCode !== 200) return that.$message.error('Error deleting file: ' + result.statusCode);
342 if (error) return that.$message.error(error.message);
343
344 refresh();
345 });
346 }).catch(function () {});
347 },
348 onRename: function (entry) {
349 var that = this;
350
351 var title = 'Rename ' + entry.filePath;
352 this.$prompt('', title, { confirmButtonText: 'Yes', cancelButtonText: 'No', inputPlaceholder: 'new filename', inputValue: entry.filePath }).then(function (data) {
353 var path = encode(sanitize(that.path + '/' + entry.filePath));
354 var newFilePath = sanitize(that.path + '/' + data.value);
355
356 superagent.put('/api/files' + path).query({ access_token: localStorage.accessToken }).send({ newFilePath: newFilePath }).end(function (error, result) {
357 if (result && result.statusCode === 401) return logout();
358 if (result && result.statusCode !== 200) return that.$message.error('Error renaming file: ' + result.statusCode);
359 if (error) return that.$message.error(error.message);
360
361 refresh();
362 });
363 }).catch(function () {});
364 },
365 onNewFolder: function () {
366 var that = this;
367
368 var title = 'Create New Folder';
369 this.$prompt('', title, { confirmButtonText: 'Yes', cancelButtonText: 'No', inputPlaceholder: 'new foldername' }).then(function (data) {
370 var path = encode(sanitize(that.path + '/' + data.value));
371
372 superagent.post('/api/files' + path).query({ access_token: localStorage.accessToken, directory: true }).end(function (error, result) {
373 if (result && result.statusCode === 401) return logout();
374 if (result && result.statusCode === 403) return that.$message.error('Folder name not allowed');
375 if (result && result.statusCode === 409) return that.$message.error('Folder already exists');
376 if (result && result.statusCode !== 201) return that.$message.error('Error creating folder: ' + result.statusCode);
377 if (error) return that.$message.error(error.message);
378
379 refresh();
380 });
381 }).catch(function () {});
382 },
383 prettyDate: function (row, column, cellValue, index) {
384 var date = new Date(cellValue),
385 diff = (((new Date()).getTime() - date.getTime()) / 1000),
386 day_diff = Math.floor(diff / 86400);
387
388 if (isNaN(day_diff) || day_diff < 0)
389 return;
390
391 return day_diff === 0 && (
392 diff < 60 && 'just now' ||
393 diff < 120 && '1 minute ago' ||
394 diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago' ||
395 diff < 7200 && '1 hour ago' ||
396 diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago') ||
397 day_diff === 1 && 'Yesterday' ||
398 day_diff < 7 && day_diff + ' days ago' ||
399 day_diff < 31 && Math.ceil( day_diff / 7 ) + ' weeks ago' ||
400 day_diff < 365 && Math.round( day_diff / 30 ) + ' months ago' ||
401 Math.round( day_diff / 365 ) + ' years ago';
402 },
403 prettyFileSize: function (row, column, cellValue, index) {
404 return filesize(cellValue);
405 },
406 loadDirectory: loadDirectory,
407 onUp: function () {
408 window.location.hash = sanitize(this.path.split('/').slice(0, -1).filter(function (p) { return !!p; }).join('/'));
409 },
410 open: open,
411 drop: drop,
412 dragOver: dragOver
413 }
414 });
415
416 getProfile(localStorage.accessToken, function (error) {
417 if (error) return console.error(error);
418
419 loadDirectory(window.location.hash.slice(1));
420 });
421
422 $(window).on('hashchange', function () {
423 loadDirectory(window.location.hash.slice(1));
424 });
425
426 })();