/
sakai.api.content.js
2008 lines (1895 loc) · 101 KB
/
sakai.api.content.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
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
define(
[
"jquery",
"config/config_custom",
"sakai/sakai.api.server",
"sakai/sakai.api.groups",
"sakai/sakai.api.util",
"sakai/sakai.api.i18n",
"sakai/sakai.api.l10n",
"sakai/sakai.api.user",
"underscore",
"misc/parseuri"
],
function($, sakai_conf, sakai_serv, sakai_groups, sakai_util, sakai_i18n, sakai_l10n, sakai_user, _) {
var sakai_content = {
/**
* Parses a full profile as received from the loadFullProfile function
* @param {Object} data Object containing data as received from the loadFullProfile function.
* @param {Function} callback Function to execute when the function finishes
*/
parseFullProfile: function(data, callback){
// temporary object to store in parsedData
var contentItem = {};
// collection pseudoGroup info to retrieve
var collectionGroup = false;
var parseMembers = function(contentMembers, contentItem){
// results for members.json
// Members are parsed an put into a .viewers and .managers object in tempItem
contentMembers.viewers = contentMembers.viewers || {};
// Parse the viewers and add them to the .viewers object.
$.each(contentMembers.viewers, function(index, resultObject) {
contentMembers.viewers[index].picture = sakai_util.constructProfilePicture(contentMembers.viewers[index]);
if (contentMembers.viewers[index]["sakai:pseudoGroup"]){
contentMembers.viewers[index].pseudoGroup = true;
contentMembers.viewers[index]["sakai:group-title"] = contentMembers.viewers[index]["sakai:parent-group-title"] + " (" + sakai_i18n.getValueForKey(contentMembers.viewers[index]["sakai:role-title-plural"]) + ")";
contentMembers.viewers[index].parent = {};
contentMembers.viewers[index].parent["sakai:group-id"] = contentMembers.viewers[index]["sakai:parent-group-id"];
contentMembers.viewers[index].parent["sakai:group-title"] = contentMembers.viewers[index]["sakai:parent-group-title"];
contentMembers.viewers[index].parent["sakai:role-title"] = contentMembers.viewers[index]["sakai:group-title"];
}
});
contentMembers.managers = contentMembers.managers || {};
// Parse the managers and add them to the .managers object.
$.each(contentMembers.managers, function(index, resultObject) {
contentMembers.managers[index].picture = sakai_util.constructProfilePicture(contentMembers.managers[index]);
if (contentMembers.managers[index]["sakai:excludeSearch"] === "true"){
contentMembers.managers[index].pseudoGroup = true;
contentMembers.managers[index]["sakai:group-title"] = contentMembers.managers[index]["sakai:parent-group-title"] + " (" + sakai_i18n.getValueForKey(contentMembers.managers[index]["sakai:role-title-plural"]) + ")";
contentMembers.managers[index].parent = {};
contentMembers.managers[index].parent["sakai:group-id"] = contentMembers.managers[index]["sakai:parent-group-id"];
contentMembers.managers[index].parent["sakai:group-title"] = contentMembers.managers[index]["sakai:parent-group-title"];
contentMembers.managers[index].parent["sakai:role-title"] = contentMembers.managers[index]["sakai:group-title"];
}
});
// filter out the the everyone group and the anonymous user
contentMembers.viewers = $.grep(contentMembers.viewers, function(resultObject, index){
if (resultObject['sakai:group-id'] !== 'everyone' &&
resultObject['rep:userId'] !== 'anonymous') {
return true;
}
return false;
});
// Add counts for managers and viewers
contentMembers.counts = { people: 0, groups: 0, collections: 0};
$.each(contentMembers.viewers.concat(contentMembers.managers), function(i, member) {
if (member.hasOwnProperty("userid")) {
contentMembers.counts.people++;
} else if (sakai_content.Collections.isCollection(member)) {
contentMembers.counts.collections++;
} else {
contentMembers.counts.groups++;
}
});
// Add the members to the tempItem object
contentItem.members = contentMembers;
};
// Loops over results and gets the data to put in tempItem
// Each tempItem consists of 4 requests made by loadFullProfile, these are:
// - poolid.infinity.json -> Fetches all general data for a content item (description, tags, title,...)
// - members.json -> Fetches all viewers and managers for a content item
// - versions.json -> Fetches all versions for a content item
// - activityfeed.json -> Fetches all activity for a content item
$.each(data, function(i, dataItem){
// results for poolid.infinity.json
if(dataItem.url.indexOf(".infinity.json") > -1){
// Stores all general data on tempItem.data
contentItem = {};
contentItem.data = $.parseJSON(dataItem.body);
if (sakai_content.Collections.isCollection(contentItem.data)){
collectionGroup = true;
}
} else if(dataItem.url.indexOf(".members.json") > -1){
// If this content item is a collection, retrieve the list of members
// behind the pseudoGroup
if (!collectionGroup){
parseMembers($.parseJSON(dataItem.body), contentItem);
}
}
});
// Add in some extra data on the object about the content
// Is current user manager/viewer
contentItem.isManager = sakai_content.isUserAManager(contentItem.data, sakai_user.data.me);
contentItem.isViewer = sakai_content.isUserAViewer(contentItem.data, sakai_user.data.me);
// Set the mimetype of the content
var mimeType = sakai_content.getMimeType(contentItem.data);
contentItem.data.mimeType = mimeType;
if (sakai_conf.MimeTypes[mimeType]) {
contentItem.data.iconURL = sakai_conf.MimeTypes[mimeType].URL;
} else {
contentItem.data.iconURL = sakai_conf.MimeTypes["other"].URL;
}
// Add paths to the content item
contentItem.content_path = "/p/" + contentItem.data._path;
contentItem.smallPath = "/p/" + contentItem.data._path;
contentItem.url = sakai_conf.SakaiDomain + "/p/" + contentItem.data._path + "/" + sakai_util.safeURL(contentItem.data["sakai:pooled-content-file-name"]);
contentItem.path = "/p/" + contentItem.data._path + "/" + sakai_util.safeURL(contentItem.data["sakai:pooled-content-file-name"]);
if (collectionGroup){
sakai_groups.getMembers(sakai_content.Collections.getCollectionGroupId(contentItem.data), function(success, members){
members = members[sakai_content.Collections.getCollectionGroupId(contentItem.data)];
parseMembers({
"viewers": members.members.results,
"managers": members.managers.results
}, contentItem);
// If callback is supplied it is executed
if($.isFunction(callback)){
callback(contentItem);
}
}, false, true);
} else {
// If callback is supplied it is executed
if($.isFunction(callback)){
callback(contentItem);
}
}
},
/**
* Loads the full content profile containing:
* - poolid.infinity.json -> Fetches all general data for a content item (description, tags, title,...)
* - members.json -> Fetches all viewers and managers for a content item
* - versions.json -> Fetches all versions for a content item
* - activityfeed.json -> Fetches all activity for a content item
* and returns it in a callback function
* @param {String} Pooled content id for the item to load the content profile for
* @param {Function} callback Function that executes when all data thas been gathered,
* passes through the unparsed results.
*/
loadFullProfile: function(poolid, callback){
var batchRequests = [
{
"url": poolid + ".infinity.json",
"method":"GET",
"cache":false,
"dataType":"json"
},
{
"url": poolid + ".members.json",
"method":"GET",
"cache":false,
"dataType":"json"
}
];
sakai_serv.batch(batchRequests, function(success, data) {
if (success) {
if($.isFunction(callback)){
callback(success, data);
} else {
return data;
}
} else if($.isFunction(callback)){
callback(success);
}
return success;
});
},
/**
* Set the permissions for an array of uploaded files or links
* @param {String} permissionValue either 'public', 'everyone', 'group' or 'private'
* @param {Array} filesArray Array of files containing the 'hashpath' property per file. This hashpath is the resourceID of the file
* @param {Function} callback Function to call when the permissions have been saved or failed to save.
* The callback function is provided with a Boolean. True = permissions successfully set, False = permissions not set (error)
*/
setFilePermissions : function(filesArray, callback, groupID){
// Check which value was selected and fill in the data object accordingly
var data = [];
var file;
for (file in filesArray) {
if (filesArray.hasOwnProperty(file)) {
var contentPath = "/p/" + filesArray[file].hashpath;
var item;
switch (filesArray[file].permissions) {
// Logged in only
case "everyone":
item = {
"url": contentPath + ".members.html",
"method": "POST",
"parameters": {
":viewer": "everyone",
":viewer@Delete": "anonymous"
}
};
data[data.length] = item;
item = {
"url": contentPath + ".modifyAce.html",
"method": "POST",
"parameters": {
"principalId": "everyone",
"privilege@jcr:read": "granted"
}
};
data[data.length] = item;
item = {
"url": contentPath + ".modifyAce.html",
"method": "POST",
"parameters": {
"principalId": "anonymous",
"privilege@jcr:read": "denied"
}
};
data[data.length] = item;
break;
// Public
case "public":
item = {
"url": contentPath + ".members.html",
"method": "POST",
"parameters": {
":viewer": ["everyone", "anonymous"]
}
};
data[data.length] = item;
item = {
"url": contentPath + ".modifyAce.html",
"method": "POST",
"parameters": {
"principalId": ["everyone"],
"privilege@jcr:read": "granted"
}
};
data[data.length] = item;
item = {
"url": contentPath + ".modifyAce.html",
"method": "POST",
"parameters": {
"principalId": ["anonymous"],
"privilege@jcr:read": "granted"
}
};
data[data.length] = item;
break;
// Managers and viewers only
case "private":
item = {
"url": contentPath + ".members.html",
"method": "POST",
"parameters": {
":viewer@Delete": ["anonymous", "everyone"]
}
};
data[data.length] = item;
item = {
"url": contentPath + ".modifyAce.html",
"method": "POST",
"parameters": {
"principalId": ["everyone"],
"privilege@jcr:read": "denied"
}
};
data[data.length] = item;
item = {
"url": contentPath + ".modifyAce.html",
"method": "POST",
"parameters": {
"principalId": ["anonymous"],
"privilege@jcr:read": "denied"
}
};
data[data.length] = item;
break;
case "group":
item = {
"url": contentPath + ".members.html",
"method": "POST",
"parameters": {
":viewer": groupID
}
};
data[data.length] = item;
item = {
"url": contentPath + ".modifyAce.html",
"method": "POST",
"parameters": {
"principalId": ["everyone"],
"privilege@jcr:read": "denied"
}
};
data[data.length] = item;
item = {
"url": contentPath + ".modifyAce.html",
"method": "POST",
"parameters": {
"principalId": ["anonymous"],
"privilege@jcr:read": "denied"
}
};
data[data.length] = item;
break;
}
}
}
$.ajax({
url: sakai_conf.URL.BATCH,
traditional: true,
type: "POST",
cache: false,
data: {
requests: $.toJSON(data)
},
success: function(data){
if (callback) {
callback(true);
}
},
error: function(xhr, textStatus, thrownError){
if (callback) {
callback(false);
}
}
});
},
/**
* Sets the permissions of an Array of files to be the same as their parent
* Order of execution:
* - Load parent permissions
* - Set parent permission parameter on content nodes
* - Set ACLs on content node
* - Callback if present
* @param {Array} filesArray Array of files (PoolIDs)
* @param {String} parentSavePath savePath of the parent
* @param {Function} callback Executed on completion of the function
*/
setFilePermissionsAsParent: function(filesArray, parentSavePath, callback) {
/**
* Set parent permission parameter on content nodes
* @param {Array} filesToSetPermissions Array of files to set ACLs on
* @param {Array} batchRequests Array of requests to set permission parameter on content nodes
*/
var setDataOnContent = function(filesToSetPermissions, batchRequests) {
sakai_serv.batch(batchRequests, function(success) {
if (success) {
// Apply the same permissions to the filesArray
sakai_content.setFilePermissions(filesToSetPermissions, function(success) {
// Execute callback
if ($.isFunction(callback)) {
callback(success);
}
});
} else {
if ($.isFunction(callback)) {
callback(success);
}
}
});
};
/**
* Get the permissons set on the parent
*/
var getParentPermissions = function() {
sakai_serv.loadJSON(parentSavePath, function(success, data) {
if (success) {
var permissions = data['sakai:permissions'];
var filesToSetPermissions = [];
var batchRequests = [];
$.each(filesArray, function(index, item) {
filesToSetPermissions.push({
'hashpath': item,
'permissions': permissions
});
batchRequests.push({
'url': '/p/' + item,
'method': 'POST',
'parameters': {
'sakai:permissions': permissions
}
});
});
setDataOnContent(filesToSetPermissions, batchRequests);
} else {
if($.isFunction(callback)) {
callback(success);
}
}
});
};
getParentPermissions();
},
/**
* Sets ACLs on a specified path and executes a callback if specified.
* @param {String} _path The path on which the ACLs need to be set or an array of paths on which to set ACLs
* @param {String} _permission 'anonymous', 'everyone', 'contacts' or 'private' determining what ACLs need to be set
* This should be an array of equal length of _path is an array
* @param {String} me Userid of the currently logged in user
* @param {Function} callback Function to execute when permissions have been set or failed to be set
*/
setACLsOnPath: function(_path, _permission, me, callback){
var paths = []; var permissions = []; var ACLs = [];
if (typeof _path === "string"){
paths.push(_path);
permissions.push(_permission);
} else {
paths = _path;
permissions = _permission;
}
for (var i = 0; i < paths.length; i++){
var path = paths[i] + ".modifyAce.html";
var permission = permissions[i];
switch (permission) {
case "anonymous":
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "everyone",
"privilege@jcr:read": "granted"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "anonymous",
"privilege@jcr:read": "granted"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "g-contacts-" + me,
"privilege@jcr:read": "granted"
}
});
break;
case "everyone":
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "g-contacts-" + me,
"privilege@jcr:read": "granted"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "everyone",
"privilege@jcr:read": "granted"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "anonymous",
"privilege@jcr:read": "denied"
}
});
break;
case "contacts":
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": me,
"privilege@jcr:write": "granted",
"privilege@jcr:read": "granted"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "g-contacts-" + me,
"privilege@jcr:read": "granted"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "everyone",
"privilege@jcr:read": "denied"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "anonymous",
"privilege@jcr:read": "denied"
}
});
break;
case "private":
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": me,
"privilege@jcr:write": "granted",
"privilege@jcr:read": "granted"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "g-contacts-" + me,
"privilege@jcr:read": "denied"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "everyone",
"privilege@jcr:read": "denied"
}
});
ACLs.push({
"url": path,
"method": "POST",
"parameters": {
"principalId": "anonymous",
"privilege@jcr:read": "denied"
}
});
break;
}
}
$.ajax({
url: sakai_conf.URL.BATCH,
traditional: true,
type: "POST",
cache: false,
data: {
requests: $.toJSON(ACLs)
},
success: function(data){
if ($.isFunction(callback)) {
callback(true, data);
}
},
error: function(xhr, textStatus, thrownError){
debug.error(xhr, textStatus, thrownError);
if ($.isFunction(callback)) {
callback(false, xhr);
}
}
});
},
/**
* Check whether a user has specific access to a piece of content, either by being a direct or
* indirect (through group membership) manager/viewer
* @param {Object} content content profile data as defined in loadContentProfile()
* @param {Object} meObj me object of the user you are checking permissions for
* @param {String} permission specifies the type of access to check (manager or viewer)
* @param {Object} directOnly specifies whether or not the relationship needs to be direct
*/
checkPermissions: function(content, meObj, permission, directOnly) {
var authorizable = false;
if (content && content['sakai:pooled-content-' + permission]) {
for (var i = 0; i < content['sakai:pooled-content-' + permission].length; i++) {
authorizable = content['sakai:pooled-content-' + permission][i];
// Direct association
if (authorizable === meObj.user.userid) {
return true;
// Indirect association
} else if (!directOnly && sakai_groups.isCurrentUserAMember(authorizable, meObj)) {
return true;
}
}
}
if (content && content.members && content.members[permission + "s"]) {
for (var j = 0; j < content.members[permission + 's'].length; j++) {
authorizable = content.members[permission + 's'][j];
// Check if this user/group library is a manager/viewer
if (authorizable.groupid === meObj.user.userid || authorizable.userid === meObj.user.userid) {
return true;
}
}
}
return false;
},
/**
* Check whether a user can manage a piece of content, either by being a direct or
* indirect (through group membership) manager
* @param {Object} content content profile data as defined in loadContentProfile()
* @param {Object} meObj me object of the user you are checking manager permissions for
* @param {Object} directOnly specifies whether or not the manager relationship needs to be direct
*/
isUserAManager: function(content, meObj, directOnly) {
return sakai_content.checkPermissions(content, meObj, 'manager', directOnly);
},
/**
* Check whether a user is a viewer of a piece of content, either by being a direct or
* indirect (through group membership) viewer
* @param {Object} content content profile data as defined in loadContentProfile()
* @param {Object} meObj me object of the user you are checking manager permissions for
* @param {Object} directOnly specifies whether or not the manager relationship needs to be direct
*/
isUserAViewer: function(content, meObj, directOnly) {
return sakai_content.checkPermissions(content, meObj, 'viewer', directOnly);
},
/**
* Check whether a given content item lives in a specific content library (either a
* personal library or a group library
* @param {Object} content content profile data as defined in loadContentProfile()
* @param {Object} userid authorizable id for which we're checking presence in the library
*/
isContentInLibrary: function(content, userid){
if (!content) {
return false;
}
// check if the content is a collection and the ID is the same collection
var collectionId = false;
if (content.data && sakai_content.Collections.isCollection(content.data)) {
collectionId = sakai_content.Collections.getCollectionGroupId(content.data);
} else if (sakai_content.Collections.isCollection(content)) {
collectionId = sakai_content.Collections.getCollectionGroupId(content);
}
if (collectionId === userid) {
return true;
}
var fakeMeObj = {
'user': {
'userid': userid
}
};
return sakai_content.isUserAViewer(content, fakeMeObj, true) || sakai_content.isUserAManager(content, fakeMeObj, true);
},
/**
* Shares content with a user and sets permissions for the user.
* This function can handle single user/content or multiple user/content items in an array
* @param {Object} contentId Unique pool id of the content being added to the library
* @param {Object} userId Authorizable id of the library to add this content in
* @param {Boolean} canManage Set to true if the user that's being shared with should have managing permissions
* @param {Object} callBack Function to call once the content has been added to the library
*/
addToLibrary: function(contentId, userId, canManage, callBack){
// content array
var toAdd = [];
if (_.isString(contentId)){
toAdd.push(contentId);
} else {
toAdd = contentId;
}
// user array
var addTo = [];
if (_.isString(userId)){
addTo.push(userId);
} else {
addTo = userId;
}
var batchRequests = [];
for (var i = 0; i < addTo.length; i++){
var params = {};
if (canManage){
params = {
":manager": addTo[i]
};
} else {
params = {
":viewer": addTo[i]
};
}
for (var j = 0; j < toAdd.length; j++){
batchRequests.push({
url: "/p/" + toAdd[j] + ".members.json",
parameters: params,
method: "POST"
});
}
}
if (batchRequests.length > 0) {
sakai_serv.batch(batchRequests, function(success, data){
if (success) {
// adjust content count in the UI so it accurately reflects the added content without needing a new request
$.each(sakai_user.data.me.groups, function(index, group){
if (group && group.counts && group.groupid === userId) {
group.counts.contentCount++;
}
});
if (callBack) {
callBack(contentId, userId);
}
}
else {
debug.error("sharecontent failed to change content " +
"permission to 'viewer' for member: " +
userId);
debug.error("xhr data returned: " + data);
}
}, null, true);
} else {
if (callBack) {
callBack(contentId, userId);
}
}
},
/**
* Removes multiple users from the specified role for multiple content items
*
* @param role content profile data as defined in loadContentProfile()
* @param {String} role The role to remove user(s) from
* @param {String/Array} contentId The content to remove the user from
* @param {String/Array} userId The user to remove
* @param {Function} callback Callback function
*/
removeUser: function(role, contentId, userId, callback){
var batchRequests = [];
var userIds = [];
var contentIds = [];
if (_.isString(userId)){
userIds.push(userId);
} else if (_.isArray(userId)){
userIds = userId;
}
if (_.isString(contentId)){
contentIds.push(contentId);
} else if (_.isArray(contentId)){
contentIds = contentId;
}
for (var c = 0; c < contentIds.length; c++) {
for (var i = 0; i < userIds.length; i++) {
var parameter = {":viewer@Delete": userIds[i]};
if (role === "manager"){
parameter = {":manager@Delete": userIds[i]};
}
batchRequests.push({
url: "/p/" + contentIds[c] + ".members.json",
parameters: parameter,
method: "POST"
});
}
}
sakai_serv.batch(batchRequests, function(success, data){
if ($.isFunction(callback)) {
callback(success);
}
});
},
/**
* Checks for autosaved documents for a sakai doc and returns that data
*
* @param {Boolean} Indicating if the sakai doc is a new page that can't have a autosaved page yet
* @param {String} Path to the sakai document in the system
* @param {Function} Callback function to execute on finish
*/
checkAutosave: function(newPage, pagePath, callback) {
if (newPage){
// a new page won't have an autosave yet
if($.isFunction(callback)){
callback(true, {"safeToEdit": true});
}
} else {
sakai_serv.loadJSON(pagePath + ".infinity.json", function(success, data) {
if($.isFunction(callback)){
// if there is an editing flag and it is less than 10 seconds ago, and you aren't the most recent editor, then
// someone else is editing the page right now.
data.safeToEdit = true;
if(data.editing && sakai_util.Datetime.getCurrentGMTTime() - data.editing.time < 10000 && data.editing._lastModifiedBy !== sakai_user.data.me.user.userid){
data.safeToEdit = false;
}
if (data.autosave && data.hasOwnProperty("page") && data.autosave._lastModified > data._lastModified) {
data.hasAutosave = true;
}
callback(success, data);
}
});
}
},
/**
* Returns a preview URL for known services, empty string otherwise
*
* @param url The url of the content in an external service that you'd like a preview of
*/
getPreviewUrl : function(url) {
var uri = parseUri(url);
var result = {};
result.type = "iframe";
result.url = url;
if (/vimeo\.com$/.test(uri.host)) {
if (uri.path !== "") {
result.url = "http://player.vimeo.com/video" + uri.path;
}
} else if (/picasaweb\.google\.com$/.test(uri.host)) {
var splitPath = uri.path.split('/');
if (splitPath.length >= 3 && uri.anchor !== "") {
var userId = splitPath[1];
var albumName = splitPath[2];
var photoId = uri.anchor;
$.ajax({
url: "/var/proxy/google/picasaGetPhoto.json",
type: "GET",
async: false,
cache: false,
data: {
"userId" : userId,
"albumName" : albumName,
"photoId" : photoId
},
success: function(data){
var splitPath = data.feed.icon["$t"].split('/');
// insert the size we want as the second to last
// entry in the array
splitPath.splice(-2, 1, "s920");
result.url = splitPath.join('/');
result.type = "image";
}
});
}
} else if (/youtube\.com$/.test(uri.host)) {
if (uri.queryKey.v){
result.url = url;
result.type = "video";
result.avatar = "//img.youtube.com/vi/" + uri.queryKey.v + "/0.jpg";
}
} else if (/amazon\.com$/.test(uri.host)) {
var asin = uri.path.split("/");
if (asin && asin[asin.indexOf('dp')] !== -1){
asin = asin[asin.indexOf('dp')+1];
result.url = "http://kindleweb.s3.amazonaws.com/app/1.0.11.053.093655/KindleReaderApp.html?asin=" + asin + "&containerID=kindleReaderDiv59&tophostname=localhost&iframeName=kindleReaderIFrame1300121366106&dp=0";
result.type = "iframe";
}
} else if (/videolectures\.net$/.test(uri.host)) {
var lectureId = uri.path.split('/')[1];
if (lectureId) {
$.ajax({
url: "/var/proxy/videolectures/videoLecturesGetSnippet.json",
type: "GET",
async: false,
cache: false,
data: {
"lectureId" : lectureId
},
success: function(data){
result.url = $($(data).find("textarea").val()).find("img").attr("src");
result.type = "image";
}
});
}
} else if (/flickr\.com$/.test(uri.host)) {
var fPhotoId = uri.path.split('/')[3];
if (fPhotoId) {
$.ajax({
url: "/var/proxy/flickr/flickrGetPhotoInfo.json",
type: "GET",
async: false,
cache: false,
dataType: "json",
data: {
"photoId": fPhotoId
},
success: function(data){
result.url = "http://farm" + data.photo.farm + ".static.flickr.com/" + data.photo.server + "/" + data.photo.id + "_" + data.photo.secret + "_b.jpg";
result.type = "image";
}
});
}
} else if (/slideshare\.net$/.test(uri.host)) {
if (uri.path !== "") {
$.ajax({
url: "/var/proxy/slideshare/slideshareGetSlideshow.json",
type: "GET",
dataType: "xml",
async: false,
cache: false,
data: {
"slideshow_url": uri.source
},
success: function(data){
if (!$(data).find("SlideShareServiceError").text()){
var embed = $($(data).find("Embed").text());
// resize to fit contentpreview
embed.find('*[style*="width"]').css("width", "100%");
embed.find('*[style*="height"]').css("height", "500px");
embed.find('*[width="425"]').attr("width", "100%");
embed.find('*[height="355"]').attr("height", "500");
result.url = embed.html();
result.type = "embed";
}
}
});
}
} else if (/maps\.google\.com$/.test(uri.host)) {
if (uri.path !== "") {
result.url = uri.source;
result.type = "googlemap";
}
}
return result;
},
/**
* Returns an object with data for the provided mimetype
*
* @param mimetype standard mimetype string (i.e. "image/png", "application/pdf", etc.)
* @return if we have a match for the given mimetype, an Object with
* the following params will be returned:
* - cssClass: css class to assign a small (~16px) sprite image as the background
* image for an element
* - URL: path to an image (~128px) that represents this content type
* - description: internationalizable bundle key for a short description
* for this content type (i.e. "PDF document")
* If there is no match, a general "Other document" object is returned
*/
getMimeTypeData: function (mimetype) {
if (mimetype && typeof(mimetype) === "string") {
var mimetypeObj = sakai_conf.MimeTypes[mimetype];
if (mimetypeObj) {
return mimetypeObj;
}
}
return sakai_conf.MimeTypes.other;
},
getMimeType : function(content){
var mimeType = "other";
if (content['_mimeType']){
mimeType = content['_mimeType'];
} else if (content['mimeType']){
mimeType = content['mimeType'];
}
return mimeType;
},
getThumbnail : function(content){
var thumbnail = "";
var mimeType = sakai_content.getMimeType(content);
if (content['sakai:pagecount'] && content['sakai:pagecount'] !== "0") {
thumbnail = "/p/" + content['_path'] + "/page1.small.jpg";
} else if (mimeType.indexOf("image") !== -1 && mimeType !== "image/tiff" && mimeType !== "image/jp2") {