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