/
uploadfiles.js
678 lines (568 loc) · 23.9 KB
/
uploadfiles.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/**
* Adds a menu item with a submenu that lists all recently opened files
*
* @copyright 2010, Ajax.org B.V.
* @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
*/
define(function(require, exports, module) {
var ide = require("core/ide");
var ext = require("core/ext");
var util = require("core/util");
var css = require("text!ext/uploadfiles/uploadfiles.css");
var skin = require("text!ext/uploadfiles/skin.xml");
var markup = require("text!ext/uploadfiles/uploadfiles.xml");
var fs = require("ext/filesystem/filesystem");
var MAX_UPLOAD_SIZE_FILE = 52428800;
var MAX_OPENFILE_SIZE = 2097152;
var MAX_CONCURRENT_FILES = 1000;
module.exports = ext.register("ext/uploadfiles/uploadfiles", {
dev : "Ajax.org",
name : "Upload Files",
alone : true,
skin : {
id : "uploadfiles",
data : skin,
"media-path" : ide.staticPrefix + "/ext/uploadfiles/style/images/"
},
type : ext.GENERAL,
css : css,
markup : markup,
deps : [],
offline : false,
worker : null,
currentSettings : [],
nodes : [],
uploadQueue : [], // list of all files that are queued for upload
lockHideQueueItems: [], // list of completed downloads that still needs to be removed from the upload queue
hook : function(){
var _self = this;
ide.addEventListener("init.ext/tree/tree", function(){
_self.nodes.push(
ide.mnuFile.appendChild(new apf.item({
caption : "Upload Files",
onclick : function(){
ext.initExtension(_self);
winUploadFiles.show();
}
})),
winFilesViewer.insertBefore(new apf.button({
id : "btnUploadFiles",
top : "-22",
skin : "header-btn",
right : "56",
icon : "panel_upload.png",
onclick : "require('core/ext').initExtension(require('ext/uploadfiles/uploadfiles'));winUploadFiles.show()",
tooltip : "Upload Files"
}), btnTreeRefresh),
mnuCtxTree.insertBefore(new apf.item({
id : "mnuCtxTreeUpload",
match : "[folder]",
visible : "{trFiles.selected.getAttribute('type')=='folder'}",
caption : "Upload to this folder",
onclick : function(){
ext.initExtension(_self);
winUploadFiles.show();
}
}), itemCtxTreeNewFile),
mnuCtxTree.insertBefore(new apf.divider({
visible : "{mnuCtxTreeUpload.visible}"
}), itemCtxTreeNewFile)
);
ide.addEventListener("init.c9/ext/auth/auth", function(){
_self.nodes.push(
ide.mnuFile.appendChild(new apf.item({
caption : "Download Project",
onclick : function(){
window.open("/api/project/download/zip/" + ide.projectName);
}
})),
winFilesViewer.insertBefore(new apf.button({
top: "-22",
skin: "header-btn",
right: "56",
icon: "download-ico.png",
tooltip: "Download Files",
onclick : function(){
window.open("/api/project/download/zip/" + require("core/ide").projectName);
}
}), btnTreeRefresh)
);
btnUploadFiles.setProperty("right", "81");
});
});
},
init : function(){
var _self = this;
apf.importCssString(_self.css);
// disabled download project since it doesn't work anymore due to runvm changes
winUploadFiles.addEventListener("afterrender", function(){
this.filebrowser = fileUploadSelect.$ext;
this.filebrowser.addEventListener('change', handleFileSelect, false);
// enable webkit folder upload
if (apf.isWebkit) {
hboxUploadNoFolders.hide();
hboxUploadWithFolders.show();
apf.setStyleClass(fileUploadSelectBtn.$ext, "uploadWithFolders")
this.folderbrowser = folderUploadSelect.$ext;
this.folderbrowser.style.display = "block";
this.folderbrowser.addEventListener('change', handleFileSelect, false);
}
});
function handleFileSelect(e){
var files = e.target.files;
if (!(_self.checkUploadSize(files) && _self.checkNumberOfFiles(files)))
return false;
_self.startUpload(files);
};
ide.addEventListener("init.ext/tree/tree", function(){
/*
winFilesViewer.appendChild(new apf.vbox({
id : "vboxTreeContainer",
anchors: "0 0 0 0"
}));
vboxTreeContainer.appendChild(trFiles);
*/
vboxTreeContainer.appendChild(boxUploadActivity);
});
lstUploadActivity.$ext.addEventListener("mouseover", function(e) {
_self.lockHideQueue = true;
if (!apf.isChildOf(this, e.relatedTarget)) {
_self.lockHideQueue = true;
}
});
lstUploadActivity.$ext.addEventListener("mouseout", function(e) {
if (apf.isChildOf(this, e.relatedTarget))
return;
_self.lockHideQueue = false;
_self.clearCompletedUploads();
});
},
initWorker: function() {
var _self = this;
this.worker = new Worker('/static/ext/uploadfiles/uploadworker.js');
this.worker.onmessage = function(e) {
var data = e.data;
if (!data.type) {
//console.log(data);
return;
}
switch(data.type) {
case "complete":
_self.onComplete();
break;
case "progress":
_self.onProgress(data.value);
break;
case "paused":
ide.addEventListener("afteronline", function(e) {
// upload current file again
_self.upload();
});
break;
case "debug":
console.log(JSON.stringify(data));
break;
default:
console.log("unknown message from uploadworker: ", data.type);
}
};
},
onShow : function(){
if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
alert('The File APIs are not fully supported in this browser.');
return winUploadFiles.hide();
}
this.setTargetFolder();
// disable tabEditors dropzone for upload
tabEditors.$ext.disableDropbox = true;
trFiles.addEventListener("afterselect", this.setTargetFolder);
},
onClose : function() {
tabEditors.$ext.disableDropbox = false;
trFiles.removeEventListener("afterselect", this.setTargetFolder);
},
getTargetFolder : function(){
var target = trFiles.selected
? trFiles.selected.nodeName == "file"
? trFiles.selected.parentElement
: trFiles.selected
: trFiles.root.firstChild;
return target;
},
setTargetFolder: function() {
var targetfolder = require("ext/uploadfiles/uploadfiles").getTargetFolder();
if (!targetfolder)
trFiles.root.firstChild;
uplTargetFolder.$ext.innerHTML = targetfolder.getAttribute("name");
},
/* upload functionality */
onBeforeDrop: function(e) {
if (!(window.File && window.FileReader/* && window.FormData*/)) {
util.alert(
"Could not upload file(s)", "An error occurred while dropping this file(s)",
"Your browser does not offer support for drag and drop for file uploads. " +
"Please try with a recent version of Chrome or Firefox."
);
return false;
}
/** Dropped item is a folder */
if (e.dataTransfer.files.length == 0) {
ext.initExtension(this);
winNoFolderSupport.show();
if (!apf.isWebkit)
btnNoFolderSupportOpenDialog.hide();
return false;
}
var files = e.dataTransfer.files;
if (!(this.checkUploadSize(files) && this.checkNumberOfFiles(files)))
return false;
if (e.dataTransfer.files.length < 1)
return false;
if (e.currentTarget.id == "tabEditorsDropArea")
this.openOnUpload = true;
this.onDrop(e);
return true;
},
onDrop: function(e) {
ext.initExtension(this);
var dt = e.dataTransfer;
var files = dt.files;
this.startUpload(files);
},
startUpload: function(files) {
var _self = this;
this.numFilesUploaded = files.length;
var node = trFiles.selected;
if (!node)
node = trFiles.xmlRoot.selectSingleNode("folder");
if (node.getAttribute("type") != "folder" && node.tagName != "folder")
node = node.parentNode;
// hide upload window if visible
if (winUploadFiles.visible)
winUploadFiles.hide();
// show upload activity list
boxUploadActivity.show();
// set hidden files to true to support hidden files and folders
(davProject.realWebdav || davProject).setAttribute("showhidden", true);
// loop through all files to create the upload queue and create subfolders
apf.asyncForEach(files, function(file, next) {
file.targetFolder = node;
var folders = file.webkitRelativePath && file.webkitRelativePath.split("/");
if (!folders || !folders.length) {
addFile(file);
return next();
}
// a folder is uploaded
else {
//davProject.setProperty("showhidden", true);
folders.pop(); // remove filename from path
var targetPath = folders.join("/");
var nodePath = node.getAttribute("path");
var targetFolder = trFiles.getModel().data.selectSingleNode("//folder[@path='" + apf.escapeXML(nodePath) + "/" + apf.escapeXML(targetPath) + "']");
// check if folder with specified path already exists
if (targetFolder) {
// this is a folder, no need to add to upload queue
if (file.name == ".")
return next();
addFile(file, targetFolder);
return next();
}
// target folder not created yet, create first
else {
var subfolder;
var currentPath = nodePath;
apf.asyncForEach(folders, function(folder, next2) {
currentPath += "/" + folder;
subfolder = trFiles.getModel().data.selectSingleNode("//folder[@path='" + apf.escapeXML(currentPath) + "']");
// subfolder is already created
if (subfolder) {
trFiles.select(subfolder);
next2();
}
// subfolder does not exists, create first
else {
fs.createFolder(folder, trFiles, true, function(folder) {
if (!folder) {
_self.removeFromQueue(file.filepath);
next();
}
// check if there are subfolders to be created
trFiles.select(folder);
subfolder = folder;
next2();
});
}
}, function() {
// this is a folder, no need to add to upload queue
if (file.name == ".")
return next();
addFile(file, subfolder);
next();
});
}
}
}, function() {
if (!_self.uploadInProgress)
_self.uploadNextFile();
});
// add a file to the upload queue
function addFile(file, targetFolder) {
if (targetFolder)
file.targetFolder = targetFolder;
_self.addToQueue(file);
}
},
checkSelectableFile: function(event) {
if (event.selected && event.selected.getAttribute("type") == "fileupload")
return false;
},
addToQueue: function(file) {
console.log("addToQueue...", file.name);
// add files in dirty state
var parent = file.targetFolder;
var path = parent.getAttribute("path");
var filename = apf.escapeXML(file.name);
var filepath = apf.escapeXML(path) + "/" + apf.escapeXML(file.name);
// expand target folder in tree
trFiles.slideOpen(null, parent, true);
// add node to file tree
var xmlNode = "<file type='fileupload'" +
" name='" + filename + "'" +
" path='" + filepath + "'" +
"/>";
trFiles.add(xmlNode, parent);
file.treeNode = trFiles.queryNode("//file[@path='" + filepath + "'][@name='" + filename + "']");
file.filepath = filepath;
file.path = path;
// add file to upload activity list
var queueNode = '<file name="' + filename + '" filepath="' + filepath + '" />';
file.queueNode = mdlUploadActivity.appendXml(queueNode);
this.uploadQueue.push(file);
},
removeFromQueue: function(filepath) {
var file;
for (var i = 0, l = this.uploadQueue.length; i < l; i++) {
file = this.uploadQueue[i];
if (file.filepath == filepath) {
this.uploadQueue.splice(i, 1);
apf.xmldb.removeNode(file.queueNode);
apf.xmldb.removeNode(file.treeNode);
break;
}
}
},
removeCurrentUploadFile: function(name) {
var file = this.currentFile;
apf.xmldb.removeNode(file.queueNode);
apf.xmldb.removeNode(file.treeNode);
if (!mdlUploadActivity.data.childNodes.length) {
boxUploadActivity.hide();
}
},
// remove queued items from upload activity list that are completed uploading but were not removed yet
// because user had his mousecursor on the list.
clearCompletedUploads: function() {
var _self = this;
var completedUploads = mdlUploadActivity.queryNodes("file[@progress='100']");
apf.asyncForEach(completedUploads, function(item, next) {
if (_self.lockHideQueue)
return;
setTimeout(function() {
apf.xmldb.removeNode(item);
next();
}, 200);
}, function() {
});
},
uploadNextFile: function() {
var _self = this;
var file = this.currentFile = this.uploadQueue.shift();
// check if there is a file to upload
if (file) {
this.uploadInProgress = true;
if (this.hideUploadActivityTimeout) {
clearTimeout(this.hideUploadActivityTimeout);
this.hideUploadActivityTimeout = null;
}
/** Chrome, Firefox */
if (apf.hasFileApi) {
function checkFileExists(exists) {
if (exists) {
if (_self.existingOverwriteAll) {
_self.overwrite();
}
else if (_self.existingSkipAll) {
_self.removeCurrentUploadFile(file.name);
_self.uploadNextFile();
}
else {
winUploadFileExists.show();
if (_self.uploadQueue.length) {
btnUploadOverwriteAll.show();
btnUploadSkipAll.show();
}
else {
btnUploadOverwriteAll.hide();
btnUploadSkipAll.hide();
}
uploadFileExistsMsg.$ext.innerHTML = "\"" + apf.escapeXML(file.name) + "\" already exists, do you want to replace it? Replacing it will overwrite its current contents.";
}
}
else {
upload(file);
}
}
function upload(file) {
var file = file || _self.currentFile;
var node = file.queueNode;
apf.xmldb.setAttribute(node, "progress", 0);
if (!_self.worker)
_self.initWorker();
_self.worker.postMessage({cmd: 'connect', id: file.name, file: file, path: file.path});
}
_self.upload = upload;
fs.exists(file.path + "/" + file.name, checkFileExists);
}
}
// no files in queue, upload completed
else {
_self.uploadInProgress = false;
_self.existingOverwriteAll = false;
_self.existingSkipAll = false;
(davProject.realWebdav || davProject).setAttribute("showhidden", require('ext/settings/settings').model.queryValue("auto/projecttree/@showhidden"));
this.hideUploadActivityTimeout = setTimeout(function() {
mdlUploadActivity.load("<data />");
boxUploadActivity.hide();
}, 5000);
}
},
/** Check for files exceeding filesize limit */
checkUploadSize: function(files) {
console.log("Checking file sizes of all files");
var file;
var files_too_big = [];
for (var filesize, totalsize = 0, i = 0, l = files.length; i < l; ++i) {
file = files[i];
filesize = file.size;
totalsize += filesize;
if (filesize > MAX_UPLOAD_SIZE_FILE) {
files_too_big.push(file.name)
}
}
if (files_too_big.length) {
if (files_too_big.length == 1) {
util.alert(
"Maximum file-size exceeded", "A file exceeds our upload limit of 50MB per file.",
"Please remove the file '" + files_too_big[0] + "' from the list to continue."
);
}
else {
util.alert(
"Maximum file-size exceeded", "Some files exceed our upload limit of 50MB per file.",
"Please remove all files larger than 50MB from the list to continue."
);
}
return false;
}
return true;
},
/** Check the number of dropped files exceeds the limit */
checkNumberOfFiles: function(files) {
console.log("Checking number of files");
if (files.length > MAX_CONCURRENT_FILES) {
util.alert(
"Could not upload files", "An error occurred while dropping these files",
"You can only drop " + MAX_CONCURRENT_FILES + " files to upload at the same time. " +
"Please try again with " + MAX_CONCURRENT_FILES + " or fewer files."
);
return false;
}
return true;
},
skip: function() {
this.removeCurrentUploadFile(this.currentFile.name);
this.uploadNextFile();
},
skipAll: function() {
this.existingSkipAll = true;
this.skip();
},
overwrite: function() {
var file = this.currentFile;
var node = file.targetFolder;
var path = node.getAttribute("path");
var filename = file.name;
apf.xmldb.removeNode(file.treeNode);
fs.remove(path + "/" + filename, this.upload);
},
overwriteAll: function() {
this.existingOverwriteAll = true;
this.overwrite();
},
onProgress: function(perc) {
if(!this.currentFile) return;
var total = Math.floor(perc * 100);
var node = this.currentFile.queueNode;
var curPerc = node.getAttribute("progress")
apf.xmldb.setAttribute(node, "progress", Math.max(total, curPerc));
},
onComplete: function() {
console.log("onComplete");
var _self = this;
var file = this.currentFile;
var path = file.path;
apf.xmldb.setAttribute(file.queueNode, "progress", "100");
console.log("webdav readdir...");
fs.webdav.exec("readdir", [path], function(data) {
console.log("webdav readdir done...");
if (data instanceof Error) {
// @todo: in case of error, show nice alert dialog.
return _self.uploadNextFile();
}
var strXml = data.match(new RegExp(("(<file path='" + apf.escapeXML(path) +
"/" + apf.escapeXML(file.name) + "'.*?>)").replace(/\//g, "\\/"))) ||
data.match(new RegExp(('(<file path="' + apf.escapeXML(path) +
"/" + apf.escapeXML(file.name) + '".*?>)').replace(/\//g, "\\/")));;
if(!strXml) {
_self.uploadNextFile();
}
// change file from uploading to file to regular file in tree
apf.xmldb.setAttribute(file.treeNode, "type", "file");
// open file when it was dropped in the editor
if (_self.openOnUpload) {
if (file.size < MAX_OPENFILE_SIZE)
ide.dispatchEvent("openfile", {doc: ide.createDocument(file.treeNode)});
}
// remove file from upload activity list
setTimeout(function() {
if (!_self.lockHideQueue)
apf.xmldb.removeNode(file.queueNode);
else
_self.lockHideQueueItems.push(file);
}, 2000);
_self.uploadNextFile();
});
},
getFormData: function(file) {
var form = new FormData();
form.append("upload", file);
return form;
},
enable : function(){
this.nodes.each(function(item){
item.enable();
});
},
disable : function(){
this.nodes.each(function(item){
item.disable();
});
},
destroy : function(){
this.nodes.each(function(item){
item.destroy(true, true);
});
this.nodes = [];
}
});
});