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