-
Notifications
You must be signed in to change notification settings - Fork 1
/
storage.js
473 lines (419 loc) · 13.1 KB
/
storage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
function Storage(defaults) {
var ls = window.localStorage || null
, gAPICallback = 'storage_googleAPILoaded'
, $dialog=$('#storagedialog')
, dsave = null
, driveFilesCallback = null
, lsave = {};
// default options and option fill-in-from-defaults method
defaults = defaults || {};
function augment(a,b) {
a=a||{};
for (k in b) {
if (b.hasOwnProperty(k) && !(k in a)) { a[k] = b[k]; }
}
}
augment(defaults, { basename: 'file', binary: true, data: '' });
var handler = {
local: null,
file: null,
drive: null,
server: null
}
function run(action) {
if (handler[action]) {
$('button',$dialog).attr('disabled','disabled');
handler[action]();
}
}
// hook up buttons
$('.local button',$dialog).on('click', function() { run('local'); });
$('.file button',$dialog).on('click', function() { run('file'); });
$('.drive button',$dialog).on('click', function() { run('drive'); });
$('.server button',$dialog).on('click', function() { run('server'); });
$('.file a.downloadlink',$dialog).on('click', function() { run('download'); });
// select/input behaviour
$('.local select',$dialog).on('change', function() { $('.local input',$dialog).val('')});
$('.local input',$dialog).on('keydown', function() { $('.local option.null').attr('selected', 'selected'); } );
$('.drive select',$dialog).on('change', function() { $('.drive input',$dialog).val('')});
$('.drive input',$dialog).on('keydown', function() { $('.drive option.null').attr('selected', 'selected'); } );
/* options
{
binary: true,
local: 'keyname',
server: [ list of server URLs for open only ],
callback: function(file) file=data or true on success, file===false on user abort
error: function(error) called for save errors
|| undefined (just call callback(false))
basename: dialog title and default filename
extension: (list for open)
data: file data for saving
}
*/
function common(options) {
// insert the basename in the dialog text
$('.basename',$dialog).text(options.basename || 'file');
// local files
if (ls!==null && options.local) {
lsave = JSON.parse(ls.getItem(options.local)||'{}');
fillLocalSelect(options.pattern||'');
$('.local',$dialog).show();
} else {
$('.local',$dialog).hide();
}
// drive
driveFilesCallback = function() { // in case we have an ongoing login process
fillDriveSelect(options.pattern||'');
}
handler.refresh = retrieveAllFiles; // manual refresh
fillDriveSelect(options.pattern||''); // populate select with cached dsave data now
// pattern
$('input[type=text]',$dialog).attr('pattern',options.pattern||'');
// enable buttons
$('button',$dialog).removeAttr('disabled');
// show dialog
$dialog.fadeIn();
}
function save(options) {
options = options || {};
augment(options,defaults);
function callback(success,msg) {
$dialog.fadeOut();
if (options.callback) options.callback(success,msg);
}
// process save data (handles strings, arrays of numbers, Uint8Arrays etc.)
var stringified, base64Data, l, data=options.data;
if (data.length===undefined || data.length===0) {
callback(false,"Empty or unknown data type.");
return;
}
if (typeof data === 'string') {
stringified = data;
} else if (typeof data[0] === 'number') {
stringified = '';
l = data.length;
for (i=0;i<l;++i) {
stringified += String.fromCharCode(data[i]);
}
} else {
callback(false,"Unknown options.data type in Storage.");
return;
}
base64Data = btoa(stringified);
// save in localStorage
function local() {
var name = $('.local select',this.$dialog).val() || $('.local input',this.$dialog).val();
// empty name
if (name=='') {
callback(false);
return;
}
// save to localstorage
lsave[name] = base64Data;
ls.setItem(options.local,JSON.stringify(lsave));
callback(true);
}
// save on Google Drive
function drive() {
var id = $('.drive select',$dialog).val() || null
, name = $('.drive input',$dialog).val()
, boundary = '-------314159265358979323846'
, delimiter = "\r\n--" + boundary + "\r\n"
, close_delim = "\r\n--" + boundary + "--"
, metadata;
if (id === null) {
if (name=='') {
callback(false);
return;
}
} else {
if (dsave===null || !(id in dsave)) {
callback(false);
return;
}
name = dsave[id].title;
}
// specify original metadata and use method 'PUT' to allow update of existing file
if (id) {
metadata = dsave[id];
id='/'+id; // append /id to xhr url causes an update of an existing file
method='PUT';
} else {
metadata = {
'title': name,
'mimeType': 'application/octet-stream'
};
id='';
method='POST';
}
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: application/octet-stream\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim
, request = gapi.client.request({
'path': '/upload/drive/v2/files'+id,
'method': method, 'alt': 'json',
'params': {'uploadType': 'multipart', 'alt': 'json'},
'headers': { 'Content-Type': 'multipart/mixed; boundary="' + boundary + '"' },
'body': multipartRequestBody
});
request.execute(function(e){
// refresh the dsave cache (file list)
driveFilesCallback = null; // no need to perform any further action
retrieveAllFiles();
callback(true,"Save complete.");
return;
});
}
// condition dialog
common(options);
$('.open',$dialog).hide();
$('.save',$dialog).show();
$('.null',$dialog).removeAttr('disabled');
// prepare downloadlink
handler.download = function(e) {
$('.file a.downloadlink',$dialog).attr('href','data:application/octet-stream;base64,'+base64Data);
}
// handlers
handler.local = local;
handler.file = null;
handler.drive = drive;
handler.server = null;
}
function open(options) {
options = options || {};
augment(options,defaults);
function callback(data) {
$dialog.fadeOut();
if (options.binary===false) {
var stringified = '', l = data.length;
for (i=0;i<l;++i) {
stringified += String.fromCharCode(data[i]);
}
data = stringified;
}
if (options.callback) options.callback(data);
}
function local() {
var name = $('.local select').val();
if (name in lsave) {
callback(atob(lsave[name]));
return;
} else {
callback(null);
return;
}
/*
function(data) {
var e=restoreOpts,
if (e==null) {
throw Error('No z_restore options available!');
}
FS.createDataFile('/', 'save.sav', data, true, true);
restoreOpts=null;
zRestore(e.count,e.o0,e.o1,e.o2);
FS.unlink('save.sav');
step();
}
*/
}
function file() {
fl = $('.file input[type=file]',$dialog)[0].files;
if (fl.length!==1) {
callback(null);
return;
}
var f=fl[0];
// instantiate a new FileReader
var reader = new FileReader();
reader.onload=function(e) {
callback(e.target.result);
return;
}
reader.readAsBinaryString(f);
}
function drive() {
var id = $('.drive select').val()
, accessToken = gapi.auth.getToken().access_token
, url = dsave[id].downloadUrl
, xhr = new XMLHttpRequest();
if (dsave===null || !(id in dsave)) {
callback(null);
return;
}
xhr.open('GET', url);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
if (xhr.status == 200) {
callback(new Uint8Array(xhr.response));
return;
} else {
callback(null);
return;
}
};
xhr.onerror = function() {
callback(null);
return;
};
xhr.send();
}
function fillServerSelect() {
var g,$s=$('.server select',$dialog).empty();
for (g in options.server) {
if (options.server.hasOwnProperty(g)) {
$s.append($('<option></option>').text(options.server[g]).attr('value',g));
}
}
}
function server() {
var url = $('.server select').val()
, xhr = new XMLHttpRequest();
if (!(url in options.server)) {
callback(null);
return;
}
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
if (xhr.status == 200) {
callback(new Uint8Array(xhr.response));
return;
} else {
callback(null);
return;
}
};
xhr.onerror = function() {
callback(null);
return;
};
xhr.send();
}
// condition dialog
common(options);
$('.open',$dialog).show();
$('.save',$dialog).hide()
$('.null',$dialog).attr('disabled','disabled');
// server
if (!('server' in options)) {
$('.server',$dialog).hide();
handler.server = null;
} else {
fillServerSelect(options.pattern||'');
$('.server',$dialog).show();
handler.server = server;
}
// handlers
handler.download = null;
handler.local = local;
handler.file = file;
handler.drive = drive;
}
function onSignIn(googleUser) {
if (googleUser && !googleUser.error) {
// Access token has been successfully retrieved, requests can be sent to the API.
$('.signedin',$dialog).show();
$('.signedout',$dialog).hide();
// fetch list of files
gapi.client.load('drive', 'v2', function() {
console.log("Google Drive API loaded.");
retrieveAllFiles();
});
}
}
function retrieveAllFiles() {
var retrievePageOfFiles = function(request, result) {
request.execute(function(resp) {
result = result.concat(resp.items);
var nextPageToken = resp.nextPageToken, num, suf;
if (nextPageToken) {
request = gapi.client.drive.files.list({'pageToken': nextPageToken });
retrievePageOfFiles(request, result);
} else {
// retrieved result, build dsave list of eligible files that are not in trash
dsave = {};
for (var i=0; i<result.length; ++i ) {
if (result[i].mimeType == 'application/octet-stream' &&
result[i].labels.trashed == false) {
dsave[result[i].id] = result[i];
}
}
// a dialog may have requested an update as soon as the dsave list is retrieved
if (driveFilesCallback) driveFilesCallback();
}
});
}
var initialRequest = gapi.client.drive.files.list();
retrievePageOfFiles(initialRequest, []);
}
function fillLocalSelect(pattern) {
var g,$s=$('.local optgroup',$dialog),nofiles=true
, regexp = new RegExp(pattern)
, prev = $s.parent().val();
$s.empty();
for (g in lsave) {
if (lsave.hasOwnProperty(g) && regexp.test(g)) {
if(!prev) { prev=g; }
$s.append($('<option></option>').text(g).attr('value',g));
n=false;
}
}
if (nofiles) {
$('.local .hasfiles',$dialog).hide();
} else {
$('.local .hasfiles',$dialog).show();
$s.parent().val(prev);
}
}
function fillDriveSelect(pattern) {
if (dsave===null) { return; }
var g,$s=$('.drive optgroup',$dialog),nofiles=true
, regexp = new RegExp(pattern)
, prev = $s.parent().val();
$s.empty();
for (g in dsave) {
if (dsave.hasOwnProperty(g) && regexp.test(dsave[g].title)) {
if(!prev) { prev=g; }
$s.append($('<option></option>').text(dsave[g].title).attr('value',g));
nofiles=false;
}
}
if (nofiles) {
$('.drive .hasfiles',$dialog).hide()
} else {
$('.drive .hasfiles',$dialog).show()
$s.parent().val(prev);
}
return nofiles;
}
// $('.signedout',$dialog).append($('<div id="google_signin_button"></div>'));
// $('.open',$dialog).hide();
//
// // load Google API
// if (!(gAPICallback in window)) {
// window[gAPICallback] = function(){
// var options = {
// 'callback' : handleAuthResult,
// 'clientid' : CLIENT_ID,
// 'scope': SCOPES,
// 'cookiepolicy' : 'single_host_origin'
// };
//
// gapi.signin.render('google_signin_button', options);
// }
// $('<script></script').appendTo('body').attr('src','https://apis.google.com/js/client:platform.js?onload='+gAPICallback);
// }
return {
save: save,
open: open,
onSignIn: onSignIn
};
}