This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
/
PydioDataModel.es6
769 lines (715 loc) · 22.3 KB
/
PydioDataModel.es6
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
/*
* Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <http://pyd.io/>.
*/
/**
* Full container of the data tree. Contains the SelectionModel as well.
*/
class PydioDataModel extends Observable{
/**
* Constructor
* > Warning, events are now LOCAL by default
*/
constructor(localEvents=true){
super();
this._currentRep = '/';
this._selectedNodes = [];
this._bEmpty = true;
this._globalEvents = !localEvents;
this._bUnique= false;
this._bFile= false;
this._bDir= false;
this._isRecycle= false;
this._pendingSelection=null;
this._selectionSource = {};
this._rootNode = null;
}
/**
* Sets the data source that will feed the nodes with children.
* @param iAjxpNodeProvider IAjxpNodeProvider
*/
setAjxpNodeProvider (iAjxpNodeProvider){
this._iAjxpNodeProvider = iAjxpNodeProvider;
}
/**
* Return the current data source provider
* @return IAjxpNodeProvider
*/
getAjxpNodeProvider (){
return this._iAjxpNodeProvider;
}
/**
* Changes the current context node.
* @param ajxpNode AjxpNode Target node, either an existing one or a fake one containing the target part.
* @param forceReload Boolean If set to true, the node will be reloaded even if already loaded.
*/
requireContextChange (ajxpNode, forceReload=false){
if(ajxpNode == null) return;
var path = ajxpNode.getPath();
if((path == "" || path == "/") && ajxpNode != this._rootNode){
ajxpNode = this._rootNode;
}
if(ajxpNode.getMetadata().has('paginationData') && ajxpNode.getMetadata().get('paginationData').has('new_page')
&& ajxpNode.getMetadata().get('paginationData').get('new_page') != ajxpNode.getMetadata().get('paginationData').get('current')){
var paginationPage = ajxpNode.getMetadata().get('paginationData').get('new_page');
forceReload = true;
}
if(ajxpNode != this._rootNode && (!ajxpNode.getParent() || ajxpNode.fake)){
// Find in arbo or build fake arbo
var fakeNodes = [];
ajxpNode = ajxpNode.findInArbo(this._rootNode, fakeNodes);
if(fakeNodes.length){
var firstFake = fakeNodes.shift();
firstFake.observeOnce("first_load", function(e){
this.requireContextChange(ajxpNode);
}.bind(this));
firstFake.observeOnce("error", function(message){
Logger.error(message);
firstFake.notify("node_removed");
var parent = firstFake.getParent();
parent.removeChild(firstFake);
//delete(firstFake);
this.requireContextChange(parent);
}.bind(this) );
this.publish("context_loading");
firstFake.load(this._iAjxpNodeProvider);
return;
}
}
ajxpNode.observeOnce("loaded", function(){
this.setContextNode(ajxpNode, true);
this.publish("context_loaded");
if(this.getPendingSelection()){
var selPath = ajxpNode.getPath() + (ajxpNode.getPath() == "/" ? "" : "/" ) +this.getPendingSelection();
var selNode = ajxpNode.findChildByPath(selPath);
if(selNode) {
this.setSelectedNodes([selNode], this);
}else{
if(ajxpNode.getMetadata().get("paginationData") && arguments.length < 3){
var newPage;
var currentPage = ajxpNode.getMetadata().get("paginationData").get("current");
this.loadPathInfoSync(selPath, function(foundNode){
newPage = foundNode.getMetadata().get("page_position");
}, {page_position:'true'});
if(newPage && newPage != currentPage){
ajxpNode.getMetadata().get("paginationData").set("new_page", newPage);
this.requireContextChange(ajxpNode, true, true);
return;
}
}
}
this.clearPendingSelection();
}
}.bind(this));
ajxpNode.observeOnce("error", function(message){
Logger.error(message);
this.publish("context_loaded");
}.bind(this));
this.publish("context_loading");
try{
if(forceReload){
if(paginationPage){
ajxpNode.getMetadata().get('paginationData').set('current', paginationPage);
}
ajxpNode.reload(this._iAjxpNodeProvider);
}else{
ajxpNode.load(this._iAjxpNodeProvider);
}
}catch(e){
this.publish("context_loaded");
}
}
requireNodeReload(nodeOrPath, completeCallback){
if(nodeOrPath instanceof String){
nodeOrPath = new AjxpNode(nodeOrPath);
}
var onComplete = null;
if(this._selectedNodes.length) {
var found = false;
this._selectedNodes.each(function(node){
if(node.getPath() == nodeOrPath.getPath()) found = node;
});
if(found){
// MAKE SURE SELECTION IS OK AFTER RELOAD
this._selectedNodes = this._selectedNodes.without(found);
this.publish("selection_changed", this);
onComplete = function(newNode){
this._selectedNodes.push(newNode);
this._selectionSource = {};
this.publish("selection_changed", this);
if(completeCallback) completeCallback(newNode);
}.bind(this);
}
}
this._iAjxpNodeProvider.refreshNodeAndReplace(nodeOrPath, onComplete);
}
loadPathInfoSync (path, callback, additionalParameters = {}){
this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, false, additionalParameters);
}
loadPathInfoAsync (path, callback){
this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, true);
}
/**
* Sets the root of the data store
* @param ajxpRootNode AjxpNode The parent node
*/
setRootNode (ajxpRootNode){
this._rootNode = ajxpRootNode;
this._rootNode.setRoot();
this._rootNode.observe("child_added", function(c){
//console.log(c);
});
this.publish("root_node_changed", this._rootNode);
this.setContextNode(this._rootNode);
}
/**
* Gets the current root node
* @returns AjxpNode
*/
getRootNode (){
return this._rootNode;
}
/**
* Sets the current context node
* @param ajxpDataNode AjxpNode
* @param forceEvent Boolean If set to true, event will be triggered even if the current node is already the same.
*/
setContextNode (ajxpDataNode, forceEvent){
if(this._contextNode && this._contextNode == ajxpDataNode && this._currentRep == ajxpDataNode.getPath() && !forceEvent){
return; // No changes
}
if(!ajxpDataNode) return;
if(this._contextNodeReplacedObserver && this._contextNode){
this._contextNode.stopObserving("node_replaced", this._contextNodeReplacedObserver);
}
this._contextNode = ajxpDataNode;
this._currentRep = ajxpDataNode.getPath();
this.publish("context_changed", ajxpDataNode);
if(!this._contextNodeReplacedObserver) this._contextNodeReplacedObserver = this.contextNodeReplaced.bind(this);
ajxpDataNode.observe("node_replaced", this._contextNodeReplacedObserver);
}
contextNodeReplaced(newNode){
this.setContextNode(newNode);
}
/**
*
*/
publish(eventName, optionalData){
var args = [];
if(this._globalEvents){
if(window.pydio){
args.push(eventName);
if(optionalData) args.push(optionalData);
pydio.fire.apply(pydio,args);
}else if(document.fire) {
args.push("ajaxplorer:"+eventName);
if(optionalData) args.push(optionalData);
document.fire.apply(document, args);
}
if(optionalData){
args = [eventName, {memo:optionalData}];
}else{
args = [eventName];
}
this.notify.apply(this,args);
}else{
if(optionalData){
args = [eventName, {memo:optionalData}];
}else{
args = [eventName];
}
this.notify.apply(this,args);
}
}
/**
* Get the current context node
* @returns AjxpNode
*/
getContextNode (){
return this._contextNode;
}
/**
* After a copy or move operation, many nodes may have to be reloaded
* This function tries to reload them in the right order and if necessary.
* @param nodes AjxpNodes[] An array of nodes
*/
multipleNodesReload (nodes){
for(var i=0;i<nodes.length;i++){
var nodePathOrNode = nodes[i];
var node;
if(nodePathOrNode instanceof String){
node = new AjxpNode(nodePathOrNode);
if(node.getPath() == this._rootNode.getPath()) node = this._rootNode;
else node = node.findInArbo(this._rootNode, []);
}else{
node = nodePathOrNode;
}
nodes[i] = node;
}
var children = [];
nodes.sort(function(a,b){
if(a.isParentOf(b)){
children.push(b);
return -1;
}
if(a.isChildOf(b)){
children.push(a);
return +1;
}
return 0;
});
children.each(function(c){
nodes = nodes.without(c);
});
nodes.each(this.queueNodeReload.bind(this));
this.nextNodeReloader();
}
/**
* Add a node to the queue of nodes to reload.
* @param node AjxpNode
*/
queueNodeReload (node){
if(!this.queue) this.queue = [];
if(node){
this.queue.push(node);
}
}
/**
* Queue processor for the nodes to reload
*/
nextNodeReloader (){
if(!this.queue.length) {
window.setTimeout(function(){
this.publish("context_changed", this._contextNode);
}.bind(this), 200);
return;
}
var next = this.queue.shift();
var observer = this.nextNodeReloader.bind(this);
next.observeOnce("loaded", observer);
next.observeOnce("error", observer);
if(next == this._contextNode || next.isParentOf(this._contextNode)){
this.requireContextChange(next, true);
}else{
next.reload(this._iAjxpNodeProvider);
}
}
/**
* Insert a node somewhere in the datamodel
* @param node AjxpNode
* @param setSelectedAfterAdd bool
*/
addNode(node, setSelectedAfterAdd=false){
var parentFake = new AjxpNode(PathUtils.getDirname(node.getPath()));
var parent = parentFake.findInArbo(this.getRootNode(), undefined);
if(!parent && PathUtils.getDirname(node.getPath()) == "") parent = this.getRootNode();
if(parent){
let addedNode = parent.addChild(node);
if(addedNode && setSelectedAfterAdd && this.getContextNode() == parent){
this.setSelectedNodes([addedNode], {});
}
}
}
/**
* Remove a node by path somewhere
* @param path string
* @param imTime integer|null
*/
removeNodeByPath(path, imTime = null){
var fake = new AjxpNode(path);
var n = fake.findInArbo(this.getRootNode(), undefined);
if(n){
if(imTime && n.getMetadata() && n.getMetadata().get("ajxp_im_time") && parseInt(n.getMetadata().get("ajxp_im_time")) >= imTime){
return false;
}
n.getParent().removeChild(n);
return true;
}
return false;
}
/**
* Update a node somewhere in the datamodel
* @param node AjxpNode
* @param setSelectedAfterUpdate bool
*/
updateNode(node, setSelectedAfterUpdate=false){
var original = node.getMetadata().get("original_path");
var fake, n;
if(original && original != node.getPath()
&& PathUtils.getDirname(original) != PathUtils.getDirname(node.getPath())){
// Node was really moved to another folder
fake = new AjxpNode(original);
n = fake.findInArbo(this.getRootNode(), undefined);
if(n){
n.getParent().removeChild(n);
}
var parentFake = new AjxpNode(getRepName(node.getPath()));
var parent = parentFake.findInArbo(this.getRootNode(), undefined);
if(!parent && getRepName(node.getPath()) == "") parent = this.getRootNode();
if(parent){
node.getMetadata().set("original_path", undefined);
parent.addChild(node);
}
}else{
if(node.getMetadata().get("original_path") === "/" && node.getPath() === "/"){
n = this.getRootNode();
n._metadata = node.getMetadata();
if(setSelectedAfterUpdate && this.getContextNode() == n) {
this.setSelectedNodes([n], {});
}
return;
}
fake = new AjxpNode(original);
n = fake.findInArbo(this.getRootNode(), undefined);
if(n && !n.isMoreRecentThan(node)){
node._isLoaded = n._isLoaded;
n.replaceBy(node, "override");
if(setSelectedAfterUpdate && this.getContextNode() == n.getParent()) {
this.setSelectedNodes([n], {});
}
}
}
}
/**
* Sets an array of nodes to be selected after the context is (re)loaded
* @param selection AjxpNode[]
*/
setPendingSelection (selection){
this._pendingSelection = selection;
}
/**
* Gets the array of nodes to be selected after the context is (re)loaded
* @returns AjxpNode[]
*/
getPendingSelection (){
return this._pendingSelection;
}
/**
* Clears the nodes to be selected
*/
clearPendingSelection (){
this._pendingSelection = null;
}
/**
* Set an array of nodes as the current selection
* @param ajxpDataNodes AjxpNode[] The nodes to select
* @param source String The source of this selection action
*/
setSelectedNodes (ajxpDataNodes, source){
if(this._selectedNodes.length == ajxpDataNodes.length){
if(ajxpDataNodes.length === 0) {
return;
}
var equal = true;
for(var k=0;k<ajxpDataNodes.length;k++){
equal = equal && ajxpDataNodes[k] == this._selectedNodes[k];
}
if(equal){
return;
}
}
if(!source){
this._selectionSource = {};
}else{
this._selectionSource = source;
}
this._selectedNodes = ajxpDataNodes;
this._bEmpty = ((ajxpDataNodes && ajxpDataNodes.length)?false:true);
this._bFile = this._bDir = this._isRecycle = false;
this._bUnique = false;
if(!this._bEmpty)
{
this._bUnique = (ajxpDataNodes.length == 1);
for(var i=0; i<ajxpDataNodes.length; i++)
{
var selectedNode = ajxpDataNodes[i];
if(selectedNode.isLeaf()) this._bFile = true;
else this._bDir = true;
if(selectedNode.isRecycle()) this._isRecycle = true;
}
}
this.publish("selection_changed", this);
}
/**
* Gets the currently selected nodes
* @returns AjxpNode[]
*/
getSelectedNodes (){
return this._selectedNodes;
}
/**
* Gets the source of the last selection action
* @returns String
*/
getSelectionSource (){
return this._selectionSource;
}
/**
* Manually sets the source of the selection
* @param object
*/
setSelectionSource (object){
this._selectionSource = object;
}
/**
* DEPRECATED
*/
getSelectedItems (){
throw new Error("Deprecated : use getSelectedNodes() instead");
}
/**
* Select all the children of the current context node
*/
selectAll (){
var nodes = [];
var childrenMap = this._contextNode.getChildren();
childrenMap.forEach(function(child){nodes.push(child)});
this.setSelectedNodes(nodes, "dataModel");
}
/**
* Whether the selection is empty
* @returns Boolean
*/
isEmpty (){
return (this._selectedNodes?(this._selectedNodes.length==0):true);
}
hasReadOnly (){
var test = false;
try{
this._selectedNodes.forEach(function(node){
if(node.hasMetadataInBranch("ajxp_readonly", "true")) {
test = true;
throw $break;
}
});
}catch(e){}
return test;
}
selectionHasRootNode (){
var found = false;
try{
this._selectedNodes.forEach(function(el){
if(el.isRoot()) {
found = true;
throw new Error();
}
});
}catch(e){}
return found;
}
/**
* Whether the selection is unique
* @returns Boolean
*/
isUnique (){
return this._bUnique;
}
/**
* Whether the selection has a file selected.
* Should be hasLeaf
* @returns Boolean
*/
hasFile (){
return this._bFile;
}
/**
* Whether the selection has a dir selected
* @returns Boolean
*/
hasDir (){
return this._bDir;
}
/**
* Whether the current context is the recycle bin
* @returns Boolean
*/
isRecycle (){
return this._isRecycle;
}
/**
* Whether the selection has more than one node selected
* @returns Boolean
*/
isMultiple (){
return this._selectedNodes && this._selectedNodes.length > 1;
}
/**
* Whether the selection has a file with one of the mimes
* @param mimeTypes Array Array of mime types
* @returns Boolean
*/
hasMime (mimeTypes){
if(mimeTypes.length==1 && mimeTypes[0] == "*") return true;
var has = false;
mimeTypes.each(function(mime){
if(has) return;
has = this._selectedNodes.any(function(node){
return (getAjxpMimeType(node) == mime);
});
}.bind(this) );
return has;
}
/**
* Get all selected filenames as an array.
* @param separator String Is a separator, will return a string joined
* @returns Array|String|bool
*/
getFileNames (separator){
if(!this._selectedNodes.length)
{
alert('Please select a file!');
return false;
}
var tmp = new Array(this._selectedNodes.length);
for(var i=0;i<this._selectedNodes.length;i++)
{
tmp[i] = this._selectedNodes[i].getPath();
}
if(separator){
return tmp.join(separator);
}else{
return tmp;
}
}
/**
* Get all the filenames of the current context node children
* @param separator String If passed, will join the array as a string
* @return Array|String|bool
*/
getContextFileNames (separator){
var allItems = this._contextNode.getChildren();
if(!allItems.length)
{
return false;
}
var names = [];
for(var i=0;i<allItems.length;i++)
{
names.push(getBaseName(allItems[i].getPath()));
}
if(separator){
return names.join(separator);
}else{
return names;
}
}
/**
* Whether the context node has a child with this basename
* @param newFileName String The name to check
* @returns Boolean
* @param local
* @param contextNode
*/
fileNameExists(newFileName, local, contextNode)
{
if(!contextNode){
contextNode = this._contextNode;
}
if(local){
var test = (contextNode.getPath()=="/"?"":contextNode.getPath()) + "/" + newFileName;
var found = false;
try{
contextNode.getChildren().forEach(function(c){
if(c.getPath() == test) {
found = true;
throw new Error();
}
});
}catch(e){}
return found;
}else{
var nodeExists = false;
this.loadPathInfoSync(contextNode.getPath() + "/" + newFileName, function(foundNode){
nodeExists = true;
});
return nodeExists;
}
}
applyCheckHook (node){
"use strict";
var client = PydioApi.getClient();
var result;
client.applyCheckHook(node, "before_create", node.getMetadata().get("filesize") || -1, function(transport){
result = client.parseXmlMessage(transport.responseXML);
});
if(result === false){
throw new Error("Check failed");
}
}
/**
* Gets the first name of the current selection
* @returns String
*/
getUniqueFileName (){
if(this.getFileNames().length) return this.getFileNames()[0];
return null;
}
/**
* Gets the first node of the selection, or Null
* @returns AjxpNode
*/
getUniqueNode (){
if(this._selectedNodes.length){
return this._selectedNodes[0];
}
return null;
}
/**
* Gets a node from the current selection
* @param i Integer the node index
* @returns AjxpNode
*/
getNode (i) {
return this._selectedNodes[i];
}
/**
* Will add the current selection nodes as serializable data to the element passed :
* either as hidden input elements if it's a form, or as query parameters if it's an url
* @param oFormElement HTMLForm The form
* @param sUrl String An url to complete
* @returns String
*/
updateFormOrUrl (oFormElement, sUrl){
// CLEAR FROM PREVIOUS ACTIONS!
if(oFormElement)
{
$(oFormElement).select('input[type="hidden"]').each(function(element){
if(element.name == "nodes[]" || element.name == "file")element.remove();
});
}
// UPDATE THE 'DIR' FIELDS
if(oFormElement && oFormElement['rep']) oFormElement['rep'].value = this._currentRep;
sUrl += '&dir='+encodeURIComponent(this._currentRep);
// UPDATE THE 'file' FIELDS
if(this.isEmpty()) return sUrl;
var fileNames = this.getFileNames();
for(var i=0;i<fileNames.length;i++)
{
sUrl += '&'+'nodes[]='+encodeURIComponent(fileNames[i]);
if(oFormElement) this._addHiddenField(oFormElement, 'nodes[]', fileNames[i]);
}
if(fileNames.length == 1){
sUrl += '&'+'file='+encodeURIComponent(fileNames[0]);
if(oFormElement) this._addHiddenField(oFormElement, 'file', fileNames[0]);
}
return sUrl;
}
_addHiddenField (oFormElement, sFieldName, sFieldValue){
oFormElement.insert(new Element('input', {type:'hidden', name:sFieldName, value:sFieldValue}));
}
}