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