]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blob - frontend/js/app.js
Use accessTokens instead of username/password
[perso/Immae/Projets/Nodejs/Surfer.git] / frontend / js / app.js
1 (function () {
2 'use strict';
3
4 function 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
24 function login(username, password) {
25 username = username || app.loginData.username;
26 password = password || app.loginData.password;
27
28 app.busy = true;
29
30 superagent.post('/api/login').query({ username: username, password: password }).end(function (error, result) {
31 app.busy = false;
32
33 if (error) return console.error(error);
34 if (result.statusCode === 401) return console.error('Invalid credentials');
35
36 getProfile(result.body.accessToken, function (error) {
37 if (error) return console.error(error);
38
39 loadDirectory(window.location.hash.slice(1));
40 });
41 });
42 }
43
44 function logout() {
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;
49
50 delete localStorage.accessToken;
51 });
52 }
53
54 function sanitize(filePath) {
55 filePath = '/' + filePath;
56 return filePath.replace(/\/+/g, '/');
57 }
58
59 function encode(filePath) {
60 return filePath.split('/').map(encodeURIComponent).join('/');
61 }
62
63 function decode(filePath) {
64 return filePath.split('/').map(decodeURIComponent).join('/');
65 }
66
67 var 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
75 function 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
88 function refresh() {
89 loadDirectory(app.path);
90 }
91
92 function loadDirectory(filePath) {
93 app.busy = true;
94
95 filePath = filePath ? sanitize(filePath) : '/';
96
97 superagent.get('/api/files/' + encode(filePath)).query({ access_token: localStorage.accessToken }).end(function (error, result) {
98 app.busy = false;
99
100 if (result && result.statusCode === 401) return logout();
101 if (error) return console.error(error);
102
103 result.body.entries.sort(function (a, b) { return a.isDirectory && b.isFile ? -1 : 1; });
104 app.entries = result.body.entries.map(function (entry) {
105 entry.previewUrl = getPreviewUrl(entry, filePath);
106 return entry;
107 });
108 app.path = filePath;
109 app.pathParts = decode(filePath).split('/').filter(function (e) { return !!e; }).map(function (e, i, a) {
110 return {
111 name: e,
112 link: '#' + sanitize('/' + a.slice(0, i).join('/') + '/' + e)
113 };
114 });
115
116 // update in case this was triggered from code
117 window.location.hash = app.path;
118
119 Vue.nextTick(function () {
120 $(function () {
121 $('[data-toggle="tooltip"]').tooltip();
122 });
123 });
124 });
125 }
126
127 function open(entry) {
128 var path = sanitize(app.path + '/' + entry.filePath);
129
130 if (entry.isDirectory) {
131 window.location.hash = path;
132 return;
133 }
134
135 window.open(encode(path));
136 }
137
138 function up() {
139 window.location.hash = sanitize(app.path.split('/').slice(0, -1).filter(function (p) { return !!p; }).join('/'));
140 }
141
142 function uploadFiles(files) {
143 if (!files || !files.length) return;
144
145 app.uploadStatus = {
146 busy: true,
147 count: files.length,
148 done: 0,
149 percentDone: 0
150 };
151
152 function uploadFile(file) {
153 var path = encode(sanitize(app.path + '/' + file.name));
154
155 var formData = new FormData();
156 formData.append('file', file);
157
158 superagent.post('/api/files' + path).query({ access_token: localStorage.accessToken }).send(formData).end(function (error, result) {
159 if (result && result.statusCode === 401) return logout();
160 if (result && result.statusCode !== 201) console.error('Error uploading file: ', result.statusCode);
161 if (error) console.error(error);
162
163 app.uploadStatus.done += 1;
164 app.uploadStatus.percentDone = Math.round(app.uploadStatus.done / app.uploadStatus.count * 100);
165
166 if (app.uploadStatus.done >= app.uploadStatus.count) {
167 app.uploadStatus = {
168 busy: false,
169 count: 0,
170 done: 0,
171 percentDone: 100
172 };
173
174 refresh();
175 }
176 });
177 }
178
179 for(var i = 0; i < app.uploadStatus.count; ++i) {
180 uploadFile(files[i]);
181 }
182 }
183
184 function upload() {
185 $(app.$els.upload).on('change', function () {
186
187 // detach event handler
188 $(app.$els.upload).off('change');
189
190 uploadFiles(app.$els.upload.files || []);
191 });
192
193 // reset the form first to make the change handler retrigger even on the same file selected
194 $('#fileUploadForm')[0].reset();
195
196 app.$els.upload.click();
197 }
198
199 function delAsk(entry) {
200 $('#modalDelete').modal('show');
201 app.deleteData = entry;
202 }
203
204 function del(entry) {
205 app.busy = true;
206
207 var path = encode(sanitize(app.path + '/' + entry.filePath));
208
209 superagent.del('/api/files' + path).query({ access_token: localStorage.accessToken, recursive: true }).end(function (error, result) {
210 app.busy = false;
211
212 if (result && result.statusCode === 401) return logout();
213 if (result && result.statusCode !== 200) return console.error('Error deleting file: ', result.statusCode);
214 if (error) return console.error(error);
215
216 refresh();
217
218 $('#modalDelete').modal('hide');
219 });
220 }
221
222 function renameAsk(entry) {
223 app.renameData.entry = entry;
224 app.renameData.error = null;
225 app.renameData.newFilePath = entry.filePath;
226
227 $('#modalRename').modal('show');
228 }
229
230 function rename(data) {
231 app.busy = true;
232
233 var path = encode(sanitize(app.path + '/' + data.entry.filePath));
234 var newFilePath = sanitize(app.path + '/' + data.newFilePath);
235
236 superagent.put('/api/files' + path).query({ access_token: localStorage.accessToken }).send({ newFilePath: newFilePath }).end(function (error, result) {
237 app.busy = false;
238
239 if (result && result.statusCode === 401) return logout();
240 if (result && result.statusCode !== 200) return console.error('Error renaming file: ', result.statusCode);
241 if (error) return console.error(error);
242
243 refresh();
244
245 $('#modalRename').modal('hide');
246 });
247 }
248
249 function createDirectoryAsk() {
250 $('#modalcreateDirectory').modal('show');
251 app.createDirectoryData = '';
252 app.createDirectoryError = null;
253 }
254
255 function createDirectory(name) {
256 app.busy = true;
257 app.createDirectoryError = null;
258
259 var path = encode(sanitize(app.path + '/' + name));
260
261 superagent.post('/api/files' + path).query({ access_token: localStorage.accessToken, directory: true }).end(function (error, result) {
262 app.busy = false;
263
264 if (result && result.statusCode === 401) return logout();
265 if (result && result.statusCode === 403) {
266 app.createDirectoryError = 'Name not allowed';
267 return;
268 }
269 if (result && result.statusCode === 409) {
270 app.createDirectoryError = 'Directory already exists';
271 return;
272 }
273 if (result && result.statusCode !== 201) return console.error('Error creating directory: ', result.statusCode);
274 if (error) return console.error(error);
275
276 app.createDirectoryData = '';
277 refresh();
278
279 $('#modalcreateDirectory').modal('hide');
280 });
281 }
282
283 function dragOver(event) {
284 event.preventDefault();
285 }
286
287 function drop(event) {
288 event.preventDefault();
289 uploadFiles(event.dataTransfer.files || []);
290 }
291
292 Vue.filter('prettyDate', function (value) {
293 var d = new Date(value);
294 return d.toDateString();
295 });
296
297 Vue.filter('prettyFileSize', function (value) {
298 return filesize(value);
299 });
300
301 var app = new Vue({
302 el: '#app',
303 data: {
304 busy: true,
305 uploadStatus: {
306 busy: false,
307 count: 0,
308 done: 0,
309 percentDone: 50
310 },
311 path: '/',
312 pathParts: [],
313 session: {
314 valid: false
315 },
316 loginData: {},
317 deleteData: {},
318 renameData: {
319 entry: {},
320 error: null,
321 newFilePath: ''
322 },
323 createDirectoryData: '',
324 createDirectoryError: null,
325 entries: []
326 },
327 methods: {
328 login: login,
329 logout: logout,
330 loadDirectory: loadDirectory,
331 open: open,
332 up: up,
333 upload: upload,
334 delAsk: delAsk,
335 del: del,
336 renameAsk: renameAsk,
337 rename: rename,
338 createDirectoryAsk: createDirectoryAsk,
339 createDirectory: createDirectory,
340 drop: drop,
341 dragOver: dragOver
342 }
343 });
344
345 window.app = app;
346
347 getProfile(localStorage.accessToken);
348
349 $(window).on('hashchange', function () {
350 loadDirectory(window.location.hash.slice(1));
351 });
352
353 // setup all the dialog focus handling
354 ['modalcreateDirectory'].forEach(function (id) {
355 $('#' + id).on('shown.bs.modal', function () {
356 $(this).find("[autofocus]:first").focus();
357 });
358 });
359
360 })();