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