]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blame - frontend/js/app.js
Make folder listing sortable
[perso/Immae/Projets/Nodejs/Surfer.git] / frontend / js / app.js
CommitLineData
6eb72d64
JZ
1(function () {
2'use strict';
3
4a27fce7
JZ
4function getProfile(accessToken, callback) {
5 callback = callback || function (error) { if (error) console.error(error); };
6
7 superagent.get('/api/profile').query({ access_token: accessToken }).end(function (error, result) {
8 app.busy = false;
9
10 if (error && !error.response) return callback(error);
11 if (result.statusCode !== 200) {
12 delete localStorage.accessToken;
13 return callback('Invalid access token');
14 }
15
16 localStorage.accessToken = accessToken;
17 app.session.username = result.body.username;
18 app.session.valid = true;
19
20 callback();
21 });
22}
23
6eb72d64
JZ
24function login(username, password) {
25 username = username || app.loginData.username;
26 password = password || app.loginData.password;
27
28 app.busy = true;
29
9b7a26fc 30 superagent.post('/api/login').send({ username: username, password: password }).end(function (error, result) {
6eb72d64
JZ
31 app.busy = false;
32
33 if (error) return console.error(error);
34 if (result.statusCode === 401) return console.error('Invalid credentials');
35
4a27fce7
JZ
36 getProfile(result.body.accessToken, function (error) {
37 if (error) return console.error(error);
d3312ed1 38
4a27fce7
JZ
39 loadDirectory(window.location.hash.slice(1));
40 });
6eb72d64
JZ
41 });
42}
43
44function logout() {
4a27fce7
JZ
45 superagent.post('/api/logout').query({ access_token: localStorage.accessToken }).end(function (error) {
46 if (error) console.error(error);
47
48 app.session.valid = false;
6eb72d64 49
4a27fce7
JZ
50 delete localStorage.accessToken;
51 });
6eb72d64
JZ
52}
53
d3312ed1
JZ
54function sanitize(filePath) {
55 filePath = '/' + filePath;
56 return filePath.replace(/\/+/g, '/');
57}
58
537bfb04
JZ
59function encode(filePath) {
60 return filePath.split('/').map(encodeURIComponent).join('/');
61}
62
04bc2989
JZ
63function decode(filePath) {
64 return filePath.split('/').map(decodeURIComponent).join('/');
65}
66
a26d1f9b
JZ
67var mimeTypes = {
68 images: [ '.png', '.jpg', '.jpeg', '.tiff', '.gif' ],
69 text: [ '.txt', '.md' ],
70 pdf: [ '.pdf' ],
71 html: [ '.html', '.htm', '.php' ],
72 video: [ '.mp4', '.mpg', '.mpeg', '.ogg', '.mkv' ]
73};
74
75function getPreviewUrl(entry, basePath) {
76 var path = '/_admin/img/';
77
78 if (entry.isDirectory) return path + 'directory.png';
79 if (mimeTypes.images.some(function (e) { return entry.filePath.endsWith(e); })) return sanitize(basePath + '/' + entry.filePath);
80 if (mimeTypes.text.some(function (e) { return entry.filePath.endsWith(e); })) return path +'text.png';
81 if (mimeTypes.pdf.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'pdf.png';
82 if (mimeTypes.html.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'html.png';
83 if (mimeTypes.video.some(function (e) { return entry.filePath.endsWith(e); })) return path + 'video.png';
84
85 return path + 'unknown.png';
86}
87
8a3d0eee
JZ
88// simple extension detection, does not work with double extension like .tar.gz
89function getExtension(entry) {
90 if (entry.isFile) return entry.filePath.slice(entry.filePath.lastIndexOf('.') + 1);
91 return '';
92}
93
537bfb04
JZ
94function refresh() {
95 loadDirectory(app.path);
96}
97
d3312ed1
JZ
98function loadDirectory(filePath) {
99 app.busy = true;
100
101 filePath = filePath ? sanitize(filePath) : '/';
102
4a27fce7 103 superagent.get('/api/files/' + encode(filePath)).query({ access_token: localStorage.accessToken }).end(function (error, result) {
d3312ed1
JZ
104 app.busy = false;
105
9209abec 106 if (result && result.statusCode === 401) return logout();
d3312ed1 107 if (error) return console.error(error);
d3312ed1 108
04bc2989 109 result.body.entries.sort(function (a, b) { return a.isDirectory && b.isFile ? -1 : 1; });
a26d1f9b
JZ
110 app.entries = result.body.entries.map(function (entry) {
111 entry.previewUrl = getPreviewUrl(entry, filePath);
8a3d0eee 112 entry.extension = getExtension(entry);
a26d1f9b
JZ
113 return entry;
114 });
d3312ed1 115 app.path = filePath;
51723cdf
J
116 app.pathParts = decode(filePath).split('/').filter(function (e) { return !!e; }).map(function (e, i, a) {
117 return {
118 name: e,
119 link: '#' + sanitize('/' + a.slice(0, i).join('/') + '/' + e)
120 };
121 });
04bc2989
JZ
122
123 // update in case this was triggered from code
124 window.location.hash = app.path;
3e98fb0c
JZ
125
126 Vue.nextTick(function () {
127 $(function () {
128 $('[data-toggle="tooltip"]').tooltip();
129 });
130 });
d3312ed1
JZ
131 });
132}
133
134function open(entry) {
5f43935e 135 var path = sanitize(app.path + '/' + entry.filePath);
d3312ed1 136
04bc2989
JZ
137 if (entry.isDirectory) {
138 window.location.hash = path;
139 return;
140 }
d3312ed1 141
5f43935e 142 window.open(encode(path));
d3312ed1
JZ
143}
144
f66b47bd
JZ
145function download(entry) {
146 if (entry.isDirectory) return;
147
c667d125 148 window.location.href = encode('/api/files/' + sanitize(app.path + '/' + entry.filePath)) + '?access_token=' + localStorage.accessToken;
f66b47bd
JZ
149}
150
d3312ed1 151function up() {
5f43935e 152 window.location.hash = sanitize(app.path.split('/').slice(0, -1).filter(function (p) { return !!p; }).join('/'));
d3312ed1
JZ
153}
154
b094fada
JZ
155function uploadFiles(files) {
156 if (!files || !files.length) return;
157
158 app.uploadStatus = {
159 busy: true,
160 count: files.length,
161 done: 0,
162 percentDone: 0
163 };
164
165 function uploadFile(file) {
166 var path = encode(sanitize(app.path + '/' + file.name));
167
168 var formData = new FormData();
169 formData.append('file', file);
170
4a27fce7 171 superagent.post('/api/files' + path).query({ access_token: localStorage.accessToken }).send(formData).end(function (error, result) {
b094fada
JZ
172 if (result && result.statusCode === 401) return logout();
173 if (result && result.statusCode !== 201) console.error('Error uploading file: ', result.statusCode);
174 if (error) console.error(error);
175
176 app.uploadStatus.done += 1;
177 app.uploadStatus.percentDone = Math.round(app.uploadStatus.done / app.uploadStatus.count * 100);
178
179 if (app.uploadStatus.done >= app.uploadStatus.count) {
180 app.uploadStatus = {
181 busy: false,
182 count: 0,
183 done: 0,
184 percentDone: 100
185 };
186
187 refresh();
188 }
189 });
190 }
191
192 for(var i = 0; i < app.uploadStatus.count; ++i) {
193 uploadFile(files[i]);
194 }
195}
196
537bfb04 197function upload() {
403359cf 198 $(app.$els.upload).on('change', function () {
537bfb04 199
403359cf
JZ
200 // detach event handler
201 $(app.$els.upload).off('change');
202
b094fada 203 uploadFiles(app.$els.upload.files || []);
537bfb04
JZ
204 });
205
e41fd8d8
JZ
206 // reset the form first to make the change handler retrigger even on the same file selected
207 $('#fileUploadForm')[0].reset();
208
537bfb04
JZ
209 app.$els.upload.click();
210}
211
9138d7d4
JZ
212function delAsk(entry) {
213 $('#modalDelete').modal('show');
214 app.deleteData = entry;
215}
216
217function del(entry) {
218 app.busy = true;
219
220 var path = encode(sanitize(app.path + '/' + entry.filePath));
221
4a27fce7 222 superagent.del('/api/files' + path).query({ access_token: localStorage.accessToken, recursive: true }).end(function (error, result) {
9138d7d4
JZ
223 app.busy = false;
224
9209abec
JZ
225 if (result && result.statusCode === 401) return logout();
226 if (result && result.statusCode !== 200) return console.error('Error deleting file: ', result.statusCode);
9138d7d4 227 if (error) return console.error(error);
9138d7d4
JZ
228
229 refresh();
230
231 $('#modalDelete').modal('hide');
232 });
233}
234
e628921a
JZ
235function renameAsk(entry) {
236 app.renameData.entry = entry;
237 app.renameData.error = null;
238 app.renameData.newFilePath = entry.filePath;
239
240 $('#modalRename').modal('show');
241}
242
243function rename(data) {
244 app.busy = true;
245
246 var path = encode(sanitize(app.path + '/' + data.entry.filePath));
247 var newFilePath = sanitize(app.path + '/' + data.newFilePath);
248
4a27fce7 249 superagent.put('/api/files' + path).query({ access_token: localStorage.accessToken }).send({ newFilePath: newFilePath }).end(function (error, result) {
e628921a
JZ
250 app.busy = false;
251
252 if (result && result.statusCode === 401) return logout();
253 if (result && result.statusCode !== 200) return console.error('Error renaming file: ', result.statusCode);
254 if (error) return console.error(error);
255
256 refresh();
257
258 $('#modalRename').modal('hide');
259 });
260}
261
403359cf
JZ
262function createDirectoryAsk() {
263 $('#modalcreateDirectory').modal('show');
264 app.createDirectoryData = '';
9209abec 265 app.createDirectoryError = null;
403359cf
JZ
266}
267
268function createDirectory(name) {
269 app.busy = true;
9209abec 270 app.createDirectoryError = null;
403359cf
JZ
271
272 var path = encode(sanitize(app.path + '/' + name));
273
4a27fce7 274 superagent.post('/api/files' + path).query({ access_token: localStorage.accessToken, directory: true }).end(function (error, result) {
403359cf
JZ
275 app.busy = false;
276
9209abec
JZ
277 if (result && result.statusCode === 401) return logout();
278 if (result && result.statusCode === 403) {
279 app.createDirectoryError = 'Name not allowed';
280 return;
281 }
282 if (result && result.statusCode === 409) {
283 app.createDirectoryError = 'Directory already exists';
284 return;
285 }
286 if (result && result.statusCode !== 201) return console.error('Error creating directory: ', result.statusCode);
403359cf 287 if (error) return console.error(error);
403359cf
JZ
288
289 app.createDirectoryData = '';
290 refresh();
291
292 $('#modalcreateDirectory').modal('hide');
293 });
294}
295
b094fada
JZ
296function dragOver(event) {
297 event.preventDefault();
298}
299
300function drop(event) {
301 event.preventDefault();
302 uploadFiles(event.dataTransfer.files || []);
303}
304
235212c4
JZ
305Vue.filter('prettyDate', function (value) {
306 var d = new Date(value);
307 return d.toDateString();
308});
309
8fce52f8
JZ
310Vue.filter('prettyFileSize', function (value) {
311 return filesize(value);
312});
313
6eb72d64
JZ
314var app = new Vue({
315 el: '#app',
316 data: {
317 busy: true,
fea6789c
JZ
318 uploadStatus: {
319 busy: false,
320 count: 0,
321 done: 0,
322 percentDone: 50
323 },
d3312ed1
JZ
324 path: '/',
325 pathParts: [],
6eb72d64
JZ
326 session: {
327 valid: false
328 },
d3312ed1 329 loginData: {},
9138d7d4 330 deleteData: {},
e628921a
JZ
331 renameData: {
332 entry: {},
333 error: null,
334 newFilePath: ''
335 },
403359cf 336 createDirectoryData: '',
9209abec 337 createDirectoryError: null,
d3312ed1 338 entries: []
6eb72d64
JZ
339 },
340 methods: {
341 login: login,
d3312ed1
JZ
342 logout: logout,
343 loadDirectory: loadDirectory,
344 open: open,
f66b47bd 345 download: download,
537bfb04 346 up: up,
9138d7d4
JZ
347 upload: upload,
348 delAsk: delAsk,
403359cf 349 del: del,
e628921a
JZ
350 renameAsk: renameAsk,
351 rename: rename,
403359cf 352 createDirectoryAsk: createDirectoryAsk,
b094fada
JZ
353 createDirectory: createDirectory,
354 drop: drop,
355 dragOver: dragOver
6eb72d64
JZ
356 }
357});
358
9209abec
JZ
359window.app = app;
360
906f293e
JZ
361getProfile(localStorage.accessToken, function (error) {
362 if (error) return console.error(error);
363
364 loadDirectory(window.location.hash.slice(1));
365});
6eb72d64 366
04bc2989
JZ
367$(window).on('hashchange', function () {
368 loadDirectory(window.location.hash.slice(1));
369});
370
9209abec
JZ
371// setup all the dialog focus handling
372['modalcreateDirectory'].forEach(function (id) {
373 $('#' + id).on('shown.bs.modal', function () {
374 $(this).find("[autofocus]:first").focus();
375 });
376});
377
6eb72d64 378})();