]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blob - frontend/js/app.js
1500457e0a3993c402a18860ac47a7ce2d69acbc
[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 callback = callback || function (error) { if (error) console.error(error); };
23
24 superagent.get('/api/profile').query({ access_token: accessToken }).end(function (error, result) {
25 app.busy = false;
26 app.ready = true;
27
28 if (error && !error.response) return callback(error);
29 if (result.statusCode !== 200) {
30 delete localStorage.accessToken;
31 return callback('Invalid access token');
32 }
33
34 localStorage.accessToken = accessToken;
35 app.session.username = result.body.username;
36 app.session.valid = true;
37
38 callback();
39 });
40 }
41
42 function sanitize(filePath) {
43 filePath = '/' + filePath;
44 return filePath.replace(/\/+/g, '/');
45 }
46
47 function encode(filePath) {
48 return filePath.split('/').map(encodeURIComponent).join('/');
49 }
50
51 function decode(filePath) {
52 return filePath.split('/').map(decodeURIComponent).join('/');
53 }
54
55 var mimeTypes = {
56 images: [ '.png', '.jpg', '.jpeg', '.tiff', '.gif' ],
57 text: [ '.txt', '.md' ],
58 pdf: [ '.pdf' ],
59 html: [ '.html', '.htm', '.php' ],
60 video: [ '.mp4', '.mpg', '.mpeg', '.ogg', '.mkv' ]
61 };
62
63 function getPreviewUrl(entry, basePath) {
64 var path = '/_admin/img/';
65
66 if (entry.isDirectory) return path + 'directory.png';
67 if (mimeTypes.images.some(function (e) { return entry.filePath.endsWith(e); })) return sanitize(basePath + '/' + entry.filePath);
68 if (mimeTypes.text.some(function (e) { return entry.filePath.endsWith(e); })) return path +'text.png';
69 if (mimeTypes.pdf.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'pdf.png';
70 if (mimeTypes.html.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'html.png';
71 if (mimeTypes.video.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'video.png';
72
73 return path + 'unknown.png';
74 }
75
76 // simple extension detection, does not work with double extension like .tar.gz
77 function getExtension(entry) {
78 if (entry.isFile) return entry.filePath.slice(entry.filePath.lastIndexOf('.') + 1);
79 return '';
80 }
81
82 function refresh() {
83 loadDirectory(app.path);
84 }
85
86 function loadDirectory(filePath) {
87 app.busy = true;
88
89 filePath = filePath ? sanitize(filePath) : '/';
90
91 superagent.get('/api/files/' + encode(filePath)).query({ access_token: localStorage.accessToken }).end(function (error, result) {
92 app.busy = false;
93
94 if (result && result.statusCode === 401) return logout();
95 if (error) return console.error(error);
96
97 result.body.entries.sort(function (a, b) { return a.isDirectory && b.isFile ? -1 : 1; });
98 app.entries = result.body.entries.map(function (entry) {
99 entry.previewUrl = getPreviewUrl(entry, filePath);
100 entry.extension = getExtension(entry);
101 return entry;
102 });
103 app.path = filePath;
104 app.pathParts = decode(filePath).split('/').filter(function (e) { return !!e; }).map(function (e, i, a) {
105 return {
106 name: e,
107 link: '#' + sanitize('/' + a.slice(0, i).join('/') + '/' + e)
108 };
109 });
110
111 // update in case this was triggered from code
112 window.location.hash = app.path;
113 });
114 }
115
116 function open(row, event, column) {
117 var path = sanitize(app.path + '/' + row.filePath);
118
119 if (row.isDirectory) {
120 window.location.hash = path;
121 return;
122 }
123
124 window.open(encode(path));
125 }
126
127 function up() {
128 window.location.hash = sanitize(app.path.split('/').slice(0, -1).filter(function (p) { return !!p; }).join('/'));
129 }
130
131 function uploadFiles(files) {
132 if (!files || !files.length) return;
133
134 app.uploadStatus.busy = true;
135 app.uploadStatus.count = files.length;
136 app.uploadStatus.done = 0;
137 app.uploadStatus.percentDone = 0;
138
139 asyncForEach(files, function (file, callback) {
140 var path = encode(sanitize(app.path + '/' + file.name));
141
142 var formData = new FormData();
143 formData.append('file', file);
144
145 superagent.post('/api/files' + path).query({ access_token: localStorage.accessToken }).send(formData).end(function (error, result) {
146 if (result && result.statusCode === 401) return logout();
147 if (result && result.statusCode !== 201) return callback('Error uploading file: ', result.statusCode);
148 if (error) return callback(error);
149
150 app.uploadStatus.done += 1;
151 app.uploadStatus.percentDone = Math.round(app.uploadStatus.done / app.uploadStatus.count * 100);
152
153 callback();
154 });
155 }, function (error) {
156 if (error) console.error(error);
157
158 app.uploadStatus.busy = false;
159 app.uploadStatus.count = 0;
160 app.uploadStatus.done = 0;
161 app.uploadStatus.percentDone = 100;
162
163 refresh();
164 });
165 }
166
167 function dragOver(event) {
168 event.preventDefault();
169 }
170
171 function drop(event) {
172 event.preventDefault();
173 uploadFiles(event.dataTransfer.files || []);
174 }
175
176 var app = new Vue({
177 el: '#app',
178 data: {
179 ready: false,
180 busy: true,
181 uploadStatus: {
182 busy: false,
183 count: 0,
184 done: 0,
185 percentDone: 50
186 },
187 path: '/',
188 pathParts: [],
189 session: {
190 valid: false
191 },
192 folderListingEnabled: false,
193 loginData: {
194 username: '',
195 password: ''
196 },
197 entries: []
198 },
199 methods: {
200 onLogin: function () {
201 app.busy = true;
202
203 superagent.post('/api/login').send({ username: app.loginData.username, password: app.loginData.password }).end(function (error, result) {
204 app.busy = false;
205
206 if (error) return console.error(error);
207 if (result.statusCode === 401) return console.error('Invalid credentials');
208
209 getProfile(result.body.accessToken, function (error) {
210 if (error) return console.error(error);
211
212 loadDirectory(window.location.hash.slice(1));
213 });
214 });
215 },
216 onOptionsMenu: function (command) {
217 if (command === 'folderListing') {
218 console.log('Not implemented');
219 } else if (command === 'about') {
220 this.$msgbox({
221 title: 'About Surfer',
222 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>.',
223 dangerouslyUseHTMLString: true,
224 confirmButtonText: 'OK',
225 showCancelButton: false,
226 type: 'info',
227 center: true
228 }).then(function () {}).catch(function () {});
229 } else if (command === 'logout') {
230 superagent.post('/api/logout').query({ access_token: localStorage.accessToken }).end(function (error) {
231 if (error) console.error(error);
232
233 app.session.valid = false;
234
235 delete localStorage.accessToken;
236 });
237 }
238 },
239 onDownload: function (entry) {
240 if (entry.isDirectory) return;
241 window.location.href = encode('/api/files/' + sanitize(app.path + '/' + entry.filePath)) + '?access_token=' + localStorage.accessToken;
242 },
243 onUpload: function () {
244 $(app.$refs.upload).on('change', function () {
245
246 // detach event handler
247 $(app.$refs.upload).off('change');
248
249 uploadFiles(app.$refs.upload.files || []);
250 });
251
252 // reset the form first to make the change handler retrigger even on the same file selected
253 app.$refs.upload.value = '';
254 app.$refs.upload.click();
255 },
256 onDelete: function (entry) {
257 var title = 'Really delete ' + (entry.isDirectory ? 'folder ' : '') + entry.filePath;
258 this.$confirm('', title, { confirmButtonText: 'Yes', cancelButtonText: 'No' }).then(function () {
259 var path = encode(sanitize(app.path + '/' + entry.filePath));
260
261 superagent.del('/api/files' + path).query({ access_token: localStorage.accessToken, recursive: true }).end(function (error, result) {
262 if (result && result.statusCode === 401) return logout();
263 if (result && result.statusCode !== 200) return console.error('Error deleting file: ', result.statusCode);
264 if (error) return console.error(error);
265
266 refresh();
267 });
268 }).catch(function () {
269 console.log('delete error:', arguments);
270 });
271 },
272 onRename: function (entry) {
273 var title = 'Rename ' + entry.filePath;
274 this.$prompt('', title, { confirmButtonText: 'Yes', cancelButtonText: 'No', inputPlaceholder: 'new filename', inputValue: entry.filePath }).then(function (data) {
275 var path = encode(sanitize(app.path + '/' + entry.filePath));
276 var newFilePath = sanitize(app.path + '/' + data.value);
277
278 superagent.put('/api/files' + path).query({ access_token: localStorage.accessToken }).send({ newFilePath: newFilePath }).end(function (error, result) {
279 if (result && result.statusCode === 401) return logout();
280 if (result && result.statusCode !== 200) return console.error('Error renaming file: ', result.statusCode);
281 if (error) return console.error(error);
282
283 refresh();
284 });
285 }).catch(function () {
286 console.log('rename error:', arguments);
287 });
288 },
289 onNewFolder: function () {
290 var title = 'Create New Folder';
291 this.$prompt('', title, { confirmButtonText: 'Yes', cancelButtonText: 'No', inputPlaceholder: 'new foldername' }).then(function (data) {
292 var path = encode(sanitize(app.path + '/' + data.value));
293
294 superagent.post('/api/files' + path).query({ access_token: localStorage.accessToken, directory: true }).end(function (error, result) {
295 if (result && result.statusCode === 401) return logout();
296 if (result && result.statusCode === 403) return console.error('Name not allowed');
297 if (result && result.statusCode === 409) return console.error('Directory already exists');
298 if (result && result.statusCode !== 201) return console.error('Error creating directory: ', result.statusCode);
299 if (error) return console.error(error);
300
301 refresh();
302 });
303 }).catch(function () {
304 console.log('create folder error:', arguments);
305 });
306 },
307 prettyDate: function (row, column, cellValue, index) {
308 var date = new Date(cellValue),
309 diff = (((new Date()).getTime() - date.getTime()) / 1000),
310 day_diff = Math.floor(diff / 86400);
311
312 if (isNaN(day_diff) || day_diff < 0)
313 return;
314
315 return day_diff === 0 && (
316 diff < 60 && 'just now' ||
317 diff < 120 && '1 minute ago' ||
318 diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago' ||
319 diff < 7200 && '1 hour ago' ||
320 diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago') ||
321 day_diff === 1 && 'Yesterday' ||
322 day_diff < 7 && day_diff + ' days ago' ||
323 day_diff < 31 && Math.ceil( day_diff / 7 ) + ' weeks ago' ||
324 day_diff < 365 && Math.round( day_diff / 30 ) + ' months ago' ||
325 Math.round( day_diff / 365 ) + ' years ago';
326 },
327 prettyFileSize: function (row, column, cellValue, index) {
328 return filesize(cellValue);
329 },
330 loadDirectory: loadDirectory,
331 up: up,
332 open: open,
333 drop: drop,
334 dragOver: dragOver
335 }
336 });
337
338 getProfile(localStorage.accessToken, function (error) {
339 if (error) return console.error(error);
340
341 loadDirectory(window.location.hash.slice(1));
342 });
343
344 $(window).on('hashchange', function () {
345 loadDirectory(window.location.hash.slice(1));
346 });
347
348 })();