forked from adsabs/bumblebee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library_controller.js
600 lines (510 loc) · 19.3 KB
/
library_controller.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
define([
'backbone',
'js/components/generic_module',
'js/mixins/hardened',
'js/components/api_targets',
'js/components/api_request',
'js/components/api_feedback',
'js/components/api_query',
'js/mixins/dependon'
],
function (
Backbone,
GenericModule,
Hardened,
ApiTargets,
ApiRequest,
ApiFeedback,
ApiQuery,
Dependon
) {
var LibraryModel = Backbone.Model.extend({
defaults: function () {
// this is the data we expect to get from the server
return {
'num_documents': 0,
'date_last_modified': undefined,
'permission': undefined,
'description': '',
'public': false,
'num_users': 1,
'owner': undefined,
'date_created': undefined,
'id': undefined,
'title': ''
};
}
});
var LibraryCollection = Backbone.Collection.extend({
model: LibraryModel
});
var LibraryController = GenericModule.extend({
initialize: function () {
// store all metadata entries here
this.collection = new LibraryCollection();
},
activate: function (beehive) {
var self = this;
this.setBeeHive(beehive.getHardenedInstance());
var pubsub = this.getBeeHive().getService('PubSub');
pubsub.subscribe(pubsub.INVITING_REQUEST, _.bind(this.updateCurrentQuery, this));
pubsub.subscribe(pubsub.USER_ANNOUNCEMENT, _.bind(this.handleUserAnnouncement, this));
pubsub.subscribe(pubsub.CUSTOM_EVENT, function (event) {
if (event === 'invalidate-library-metadata') {
self._metadataLoaded = false;
}
});
/*
* the three events that come from changing a collection:
* -change if a model's contents were changed
* -add if models were added
* -reset if the entire collection was reset
* -remove when a model is removed (library deleted)
* */
_.each(['change', 'add', 'reset', 'remove'], function (ev) {
this.listenTo(this.collection, ev, function (arg1, arg2) {
if (ev == 'change' && arg1 instanceof Backbone.Model) {
// a single model changed, widgets might want to know which one
pubsub.publish(pubsub.LIBRARY_CHANGE, this.collection.toJSON(), { ev: ev, id: arg1.id });
// also clear out the bibcode cache if necessary
delete this._libraryBibcodeCache[arg1.id];
} else {
pubsub.publish(pubsub.LIBRARY_CHANGE, this.collection.toJSON(), { ev: ev });
}
});
}, this);
},
handleUserAnnouncement: function (event) {
if (event == 'user_signed_in') {
this._fetchAllMetadata();
} else if (event == 'user_signed_out') {
this.collection.reset({});
}
},
/*
* private methods
*/
updateCurrentQuery: function (apiQuery) {
this._currentQuery = apiQuery;
},
composeRequest: function (target, method, options) {
var request,
options = options || {},
data = options.data || undefined;
// using "endpoint" to mean the actual url string
// get data from the relevant model based on the endpoint
var deferred = $.Deferred();
function done() {
var args = [_.extend(arguments[0], options.extraArguments), [].slice(arguments, 1)];
deferred.resolve.apply(undefined, args);
}
function fail(error) {
// on fail, send a custom event to alert library widgets
var ps = this.getPubSub();
ps.publish(ps.CUSTOM_EVENT, 'libraries:request:fail', error);
deferred.reject.apply(undefined, arguments);
}
request = new ApiRequest({
target: target,
options: {
context: this,
type: method,
data: JSON.stringify(data),
contentType: 'application/json',
done: done,
fail: fail
}
});
this.getBeeHive().getService('Api').request(request);
return deferred.promise();
},
_executeApiRequest: function (apiQuery) {
var req = new ApiRequest({
target: ApiTargets.SEARCH,
query: apiQuery
});
var defer = $.Deferred();
var pubsub = this.getPubSub();
pubsub.subscribeOnce(pubsub.DELIVERING_RESPONSE, _.bind(function (data) {
defer.resolve(data);
}), this);
pubsub.publish(pubsub.EXECUTE_REQUEST, req);
return defer.promise();
},
_getBibcodes: function (options) {
var deferred = $.Deferred(),
that = this;
if (options.bibcodes == 'all') {
var limit = options.limit || 2000,
start = 0,
rows = 100,
bibcodes = [];
var q = this._currentQuery.clone();
q.unlock();
q.set('rows', 100);
q.set('fl', 'bibcode');
function makeRequest() {
q.set('start', start);
this._executeApiRequest(q).done(function (apiResponse) {
var bibs = _.map(apiResponse.get('response.docs'), function (d) {
return d.bibcode;
});
[].push.apply(bibcodes, bibs);
start += rows;
if (start < limit) {
makeRequest.call(that);
} else {
deferred.resolve(bibcodes);
}
});
}
makeRequest.call(this);
} else if (options.bibcodes == 'selected') {
var bibs = this.getBeeHive().getObject('AppStorage').getSelectedPapers();
deferred.resolve(bibs);
}
// for abstract widget
else if (_.isArray(options.bibcodes)) {
deferred.resolve(options.bibcodes);
} else {
throw new Error('should we add all bibcodes or only selected ones?');
}
return deferred.promise();
},
_fetchAllMetadata: function () {
var that = this;
var endpoint = ApiTargets.LIBRARIES;
return this.composeRequest(endpoint, 'GET').done(function (data) {
that._metadataLoaded = true;
that.collection.reset(data.libraries);
});
},
/*
* public methods
*
*/
/*
* this is how widgets/controllers can learn about
* all libraries
* if you provide an id, you just get info
* about the lib with that id
* */
getLibraryMetadata: function (id) {
// check to see if the id is even in the collection,
// if not return fetchLibraryMetadata;
if (id && !this.collection.get(id)) {
return this.fetchLibraryMetadata(id);
}
var deferred = $.Deferred();
var that = this;
// if this is the initial check, just wait until we can load the metadata
if (!this._metadataLoaded) {
this._fetchAllMetadata().done(function (data) {
// make sure the collection is refilled before this promise is resolved
setTimeout(function () {
var data = id ? that.collection.get(id).toJSON() : that.collection.toJSON();
deferred.resolve(data);
}, 1);
});
} else {
var data = id ? that.collection.get(id).toJSON() : that.collection.toJSON();
deferred.resolve(data);
}
return deferred.promise();
},
/*
* fetch the data especially -- useful for public libraries but also
* in case the new data hasn't been added to the collection yet
* */
fetchLibraryMetadata: function (id) {
var that = this;
if (!id) throw new Error('need to provide a library id');
var deferred = $.Deferred();
this.composeRequest(ApiTargets.LIBRARIES + '/' + id)
.done(function (data) {
deferred.resolve(data.metadata);
// set into collection
that.collection.add(data.metadata, { merge: true });
})
.fail(function () {
// just navigate to a 404 page
that.getPubSub().publish(that.getPubSub().NAVIGATE, '404');
});
return deferred.promise();
},
/*
*
* here, store lists of bibcodes requested from the 'getLibraryBibcodes'
* method. they are stored here so that if a user quickly toggles back
* and forth between the export/metrics/vis widget, we won't have to re-fetch
* the bibcodes
* */
_libraryBibcodeCache: {},
/*
* get list of 2000 bibcodes,
* this is used for fetching data for export, metrics, etc
*
* */
getLibraryBibcodes: function (id) {
var deferred = $.Deferred(),
that = this,
// hard limit, no more than 10,000 records can be exported to search results page
maxReturned = 10000;
// we already have it in the cache, so just resolve + return promise
if (this._libraryBibcodeCache[id]) {
deferred.resolve(this._libraryBibcodeCache[id]);
return deferred.promise();
}
var limit = maxReturned,
// start gets incremented
start = 0,
rows = 100,
bibcodes = [],
endpoint = ApiTargets.LIBRARIES + '/' + id,
that = this;
// this function gets called repeatedly
function done(data) {
limit = data.solr.response.numFound > maxReturned ? maxReturned : data.solr.response.numFound;
var bibs = _.pluck(data.solr.response.docs, 'bibcode');
[].push.apply(bibcodes, bibs);
start += rows;
if (start < limit) { makeRequest(); } else {
that._libraryBibcodeCache[id] = bibcodes;
deferred.resolve(bibcodes);
}
}
function makeRequest() {
var q = new ApiQuery();
q.set('rows', 100);
q.set('fl', 'bibcode');
q.set('start', start);
var request = new ApiRequest({
target: endpoint,
query: q,
options: {
context: this,
contentType: 'application/x-www-form-urlencoded',
done: done,
fail: this.handleError
}
});
that.getBeeHive().getService('Api').request(request);
}
makeRequest.call(this);
return deferred.promise();
},
/*
* requires id, name, description
*/
createLibrary: function (data) {
var that = this;
var endpoint = ApiTargets.LIBRARIES;
return this.composeRequest(endpoint, 'POST', { data: data })
.done(function () {
// refresh collection
that._fetchAllMetadata();
});
},
deleteLibrary: function (id, name) {
var that = this,
endpoint = ApiTargets.DOCUMENTS + '/' + id,
name;
var promise = this.composeRequest(endpoint, 'DELETE')
.done(function () {
// delete library from internal representation
that.collection.remove(id);
// take care of ui
that.getBeeHive().getService('PubSub').publish(that.getBeeHive().getService('PubSub').NAVIGATE, 'AllLibrariesWidget', 'libraries');
var message = 'Library <b>' + name + '</b> was successfully deleted';
that.getBeeHive().getService('PubSub').publish(that.getBeeHive().getService('PubSub').ALERT, new ApiFeedback({ code: 0, msg: message, type: 'success' }));
})
.fail(function (jqXHR) {
var error = JSON.parse(jqXHR.responseText).error;
var message = 'Library <b>' + name + '</b> could not be deleted : (' + error + ')';
that.getBeeHive().getService('PubSub').publish(that.getBeeHive().getService('PubSub').ALERT, new ApiFeedback({ code: 0, msg: message, type: 'danger' }));
});
return promise;
},
/*
* @param id
* @param updateData e.g. {bibcode:[1,2,3], action: "add/remove" }
*
*/
updateLibraryContents: function (id, updateData) {
var that = this,
data = { data: updateData, extraArguments: { numBibcodesRequested: updateData.bibcode.length } };
var endpoint = ApiTargets.DOCUMENTS + '/' + id;
return this.composeRequest(endpoint, 'POST', data)
.done(function () {
that.fetchLibraryMetadata(id);
})
.fail(function (jqXHR) {
var error = JSON.parse(jqXHR.responseText).error;
var message = 'Library <b>' + that.collection.get(id).title + '</b> could not be updated: (' + error + ')';
that.getBeeHive().getService('PubSub').publish(that.getBeeHive().getService('PubSub').ALERT, new ApiFeedback({ code: 0, msg: message, type: 'danger' }));
});
},
performLibraryOperation: function (libId, options) {
if (!options) {
throw new Error('must provide options object with action and set of secondary libraries (if necessary)');
}
var data = {};
var action = options.action && options.action.toLowerCase();
var libraries = options.libraries;
var name = options.name;
var isAdvancedAction = /^(union|intersection|difference)$/.test(action);
var isCopyAction = /^copy$/.test(action);
var isEmptyAction = /^empty$/.test(action);
if (!_.isString(action) || (!isAdvancedAction && !isCopyAction && !isEmptyAction)) {
throw new Error(action +' is not one of the defined actions');
}
if (!_.isString(libId)) {
throw new Error('must pass library ID as first parameter');
}
if (isAdvancedAction && (!_.isArray(libraries))) {
throw new Error('libraries must be an array');
}
if (isCopyAction && (!_.isArray(libraries) || libraries.length !== 1)) {
throw new Error('for copy action, libraries must have exactly 1 entry');
}
// make sure that we don't send duplicate library ids
libraries = _.unique(libraries);
_.extend(data, { action });
if (isAdvancedAction) {
_.extend(data, { libraries, name });
} else if (isCopyAction) {
_.extend(data, { libraries });
}
var endpoint = ApiTargets.LIBRARIES + '/operations/' + libId;
return this.composeRequest(endpoint, 'POST', { data: data });
},
transferOwnership: function (libId, newOwnerEmail) {
if (!newOwnerEmail || !_.isString(newOwnerEmail)) {
throw 'new owner email address must be a string';
}
if (!libId || !_.isString(libId)) {
throw 'library Id must be a string';
}
const endpoint = ApiTargets.LIBRARY_TRANSFER + '/' + libId;
const data = { email: newOwnerEmail };
return this.composeRequest(endpoint, 'POST', { data });
},
// /*
// * email, permission, value
// * */
//
// updateLibraryPermissions : function(id, data){
//
// var that = this;
//
// var endpoint = ApiTargets["PERMISSIONS"] + "/" + id;
// return this.composeRequest(endpoint, "POST", {data : data})
// .done(function(data){
// this.collection.get(id).set(data);
// })
// .fail(function(jqXHR){
// var error = JSON.parse(jqXHR.responseText).error;
// var message = "Library <b>" + that.collection.get(id).title + "</b> could not be updated: (" + error + ")";
// that.getBeeHive().getService("PubSub").publish(that.key, that.getBeeHive().getService("PubSub").ALERT, new ApiFeedback({code: 0, msg: message, type : "danger"}));
// });
//
// },
updateLibraryMetadata: function (id, data) {
var that = this;
var endpoint = ApiTargets.DOCUMENTS + '/' + id;
return this.composeRequest(endpoint, 'PUT', { data: data })
.done(function (data) {
that.collection.get(id).set(data);
})
.fail(function (jqXHR) {
var error = JSON.parse(jqXHR.responseText).error;
var message = 'Library <b>' + that.collection.get(id).get('name') + '</b> could not be updated: (' + error + ')';
that.getBeeHive().getService('PubSub').publish(that.getBeeHive().getService('PubSub').ALERT, new ApiFeedback({ code: 0, msg: message, type: 'danger' }));
});
},
/* fetches bibcodes, then submits them to library endpoint
*
* @param data e.g. {"library": [library_id], "bibcodes": ["all"/ "selected"]}
*
*/
addBibcodesToLib: function (data) {
var that = this,
promise = this._getBibcodes(data).then(function (bibcodes) {
// should return success or fail message
return that.updateLibraryContents(data.library, { bibcode: bibcodes, action: 'add' })
.fail(function () {
var message = 'Library <b>' + that.collection.get(data.library).title + '</b> could not be updated';
that.getBeeHive().getService('PubSub').publish(that.getBeeHive().getService('PubSub').ALERT, new ApiFeedback({ code: 0, msg: message, type: 'danger' }));
});
});
return promise;
},
/* fetch the bibcodes, then POST to the create endpoint with the bibcodes
*
* @param data: e.g. {bibcodes: ["all"/"selected"], name: "ddddd"}
*
*/
createLibAndAddBibcodes: function (data) {
var that = this,
promise = this._getBibcodes(data).then(function (bibcodes) {
if (!bibcodes) {
throw new Error('Solr returned no bibcodes, can\'t put them in the new library');
}
data.bibcode = bibcodes;
var createLibraryPromise = that.createLibrary(data)
.fail(function () {
var message = 'Library <b>' + name + '</b> could not be created';
that.getBeeHive().getService('PubSub').publish(that.getBeeHive().getService('PubSub').ALERT, new ApiFeedback({ code: 0, msg: message, type: 'danger' }));
});
return createLibraryPromise;
});
return promise;
},
importLibraries: function (service) {
var endpoint,
d = $.Deferred(),
that = this;
if (service === 'classic') {
endpoint = ApiTargets.LIBRARY_IMPORT_CLASSIC_TO_BBB;
} else if (service === 'twopointoh') {
endpoint = ApiTargets.LIBRARY_IMPORT_ADS2_TO_BBB;
} else {
console.error('didn\'t recognize library endpoint! should be one of \'classic\' or \'twopointoh\' ');
return;
}
this.getBeeHive().getService('Api').request(new ApiRequest({
target: endpoint,
options: {
done: function (data) {
d.resolve.apply(undefined, [].slice.apply(arguments));
// re-fetch metadata, since new libs were imported
that._fetchAllMetadata();
},
fail: function (data) {
d.reject.apply(undefined, [].slice.apply(arguments));
}
}
}));
return d.promise();
},
hardenedInterface: {
getLibraryMetadata: 'returns json list of libraries, optional lib id as param',
createLibrary: 'createLibrary',
// these two functions fetch bibcodes based on the arguments given
createLibAndAddBibcodes: 'createLibAndAddBibcodes',
addBibcodesToLib: 'addBibcodesToLib',
deleteLibrary: 'deleteLibrary',
updateLibraryContents: 'updateLibraryContents',
// updateLibraryPermissions : "updateLibraryPermissions",
updateLibraryMetadata: 'updateLibraryMetadata',
importLibraries: 'importLibraries',
transferOwnership: 'transferOwnership',
// currently called by library individual widget to get
// lists of bibs to pass to export, metrics, vis widgets etc
getLibraryBibcodes: 'getLibraryBibcodes',
performLibraryOperation: 'performLibraryOperation'
}
});
_.extend(LibraryController.prototype, Hardened, Dependon.BeeHive);
return LibraryController;
});