| 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 |
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
20
20
20
20
20
20
20
20
20
140
140
140
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
1
42
4
15
35
31
4
7
1396
2
2
2
4
3
1
1
1
1
12
3
6
6
6
4
2
4
4
3
3
2
2
2
1
1
1
1
1
1
4
9
6
3
3
1
1
1
5
5
1
1
4
4
1
1
3
3
3
1
1
2
4
4
4
1
3
3
3
3
3
3
3
3
3
4
3
3
3
3
3
3
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
| /* globals window, localStorage, navigator */
var FieldDBObject = require("./../FieldDBObject").FieldDBObject;
var Activity = require("./../activity/Activity").Activity;
var Authentication = require("./../authentication/Authentication").Authentication;
var Corpus = require("./../corpus/Corpus").Corpus;
var CorpusMask = require("./../corpus/CorpusMask").CorpusMask;
var Database = require("./../corpus/Database").Database;
var Connection = require("./../corpus/Connection").Connection;
var Corpora = require("./../corpus/Corpora").Corpora;
var DataList = require("./../data_list/DataList").DataList;
var Import = require("./../import/Import").Import;
var Search = require("./../search/Search").Search;
var Session = require("./../datum/Session").Session;
var Router = require("./../Router").Router;
var Contextualizer = require("./../locales/Contextualizer").Contextualizer;
var Q = require("q");
/**
* @class The App handles the reinitialization and loading of the app
* depending on which platform (Android, Chrome, web) the app is
* running, who is logged in etc.
*
* The App should be serializable to save state to local storage for the
* next run.
*
* @name App
*
* @property {Authentication} authentication The auth member variable is an
* Authentication object permits access to the login and logout
* functions, and the database of users depending on whether the
* app is online or not. The authentication is the primary way to access the current user.
*
* @property {Corpus} corpus The corpus is a Corpus object which will permit
* access to the datum, the data lists and the sessions. The corpus feeds the
* search object with indexes and fields for advanced search, the
* corpus has datalists, has teams with permissions, has a
* confidentiality_encryption key, it's datum have sessions, its
* datalists and datum have export.
*
* @property {Search} search The current search details.
*
* @property {Session} currentSession The session that is currently open.
*
* @property {DataList} currentDataList The datalist that is currently open.
* @extends FieldDBObject
* @tutorial tests/app/AppTest.js
* @constructs
*/
var App = function App(options) {
Eif (!this._fieldDBtype) {
this._fieldDBtype = "App";
}
this.debug("Constructing App ", options);
Iif (FieldDBObject.application && FieldDBObject.application instanceof App) {
this.warn("You shouldn't declare two apps at one time. Overwriting previous app.");
this.debug("previous app", FieldDBObject.application);
}
FieldDBObject.application = this;
FieldDBObject.apply(this, arguments);
Eif (!this.knownConnections || !this.knownConnections.length) {
// Let client apps show a list of conenctions, and create custom connections if the BASE_DB_URL isnt default
this.knownConnections = new Corpora({
primaryKey: "userFriendlyServerName"
});
for (var connection in Connection.knownConnections) {
Iif (connection && !Connection.knownConnections.hasOwnProperty(connection)) {
continue;
}
this.debug(" Adding connection ", connection);
this.knownConnections.add(Connection.knownConnections[connection]);
}
this.debug("Set up knownConnections" + this.knownConnections.length);
}
Eif (!this.selectedConnection) {
this.debug("Setting up the app's selectedConnection");
Eif (Database.prototype.BASE_AUTH_URL) {
this.debug("Looking for a selectedConnection for " + Database.prototype.BASE_AUTH_URL);
this.selectedConnection = Connection.defaultConnection(Database.prototype.BASE_AUTH_URL, "passByReference");
} else {
this.debug("Looking for a selectedConnection based on where this is running ");
this.selectedConnection = Connection.defaultConnection(null, "passByReference");
}
this.debug("Found a selectedConnection ", this.selectedConnection.corpusUrls);
Iif (Database.prototype.BASE_DB_URL && this.selectedConnection.corpusUrls.indexOf(Database.prototype.BASE_DB_URL) === -1) {
this.warn("Making a custom selectedConnection because the selectedConnection " , this.selectedConnection.corpusUrls , " doesnt fit with the database url " + Database.prototype.BASE_DB_URL);
this.selectedConnection = this.selectedConnection.clone();
this.selectedConnection.corpusUrl = Database.prototype.BASE_DB_URL;
this.selectedConnection.userFriendlyServerName = "Custom";
}
Iif (!this.knownConnections.find(this.selectedConnection).length) {
this.warn("Adding the selectedConnection to the list of knownConnections ", this.selectedConnection);
this.knownConnections.unshift(this.selectedConnection);
}
}
this.speakersList = this.speakersList || new DataList({
title: {
default: "locale_All_Speakers"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Speaker"
});
this.consultantsList = this.consultantsList || new DataList({
title: {
default: "locale_All_Language_Consultants"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Consultant"
});
this.participantsList = this.participantsList || new DataList({
title: {
default: "locale_All_Participants"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Participant"
});
this.usersList = this.usersList || new DataList({
title: {
default: "locale_All_Users"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "User"
});
this.sessionsList = this.sessionsList || new DataList({
title: {
default: "locale_All_Elicitation_Sessions"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Session",
// docs: [],
// docIds: []
});
this.datalistsList = this.datalistsList || new DataList({
title: {
default: "locale_All_Datalists"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Datalist"
});
this.datumsList = this.datumsList || new DataList({
title: {
default: "locale_All_Data"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
// debugMode:true,
api: "LanguageDatum"
});
this.commentsList = this.commentsList || new DataList({
title: {
default: "All Comments"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Comment"
});
this.responsesList = this.responsesList || new DataList({
title: {
default: "List of Responses"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Response"
});
this.experimentsList = this.experimentsList || new DataList({
title: {
default: "List of Experiment Results"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Experiment"
});
this.reportsList = this.reportsList || new DataList({
title: {
default: "List of Reports"
},
description: {
default: "This list was automatically generated by looking in the corpus."
},
api: "Report"
});
this.importer = this.importer || null;
this.search = this.search || null;
this.currentDoc = this.currentDoc || null;
this._corpus = this._corpus || null;
this.thisyear = (new Date()).getFullYear();
this.whiteListCORS = this.whiteListCORS || ["self"];
var self = this;
Q.nextTick(function() {
self.warn("An app of type " + self.fieldDBtype + " has become automagically available to all fielddb objects");
});
};
App.prototype = Object.create(FieldDBObject.prototype, /** @lends App.prototype */ {
constructor: {
value: App
},
authentication: {
get: function() {
return this._authentication || FieldDBObject.DEFAULT_OBJECT;
},
set: function(value) {
this.ensureSetViaAppropriateType("authentication", value);
}
},
application: {
get: function() {
return this;
},
set: function(value) {
this.warn("This is the application, the application cant be set on it.", value);
}
},
corpus: {
get: function() {
if (this._corpus) {
return this._corpus;
}
return Database.prototype;
},
set: function(value) {
this._corpus = value;
}
},
contextualizer: {
get: function() {
return this._contextualizer;
},
set: function(value) {
this.ensureSetViaAppropriateType("contextualizer", value);
Eif (this._contextualizer && typeof this._contextualizer.loadDefaults === "function") {
this._contextualizer.loadDefaults();
}
}
},
contextualize: {
value: function(value) {
if (this._contextualizer) {
return this._contextualizer.contextualize(value);
} else {
Eif (typeof value === "object" || value.default) {
return value.default;
}
return value;
}
}
},
prefs: {
get: function() {
if (this.corpus && this.corpus.prefs) {
return this.corpus.prefs;
}
if (this.authentication && this.authentication.user && this.authentication.user.prefs) {
return this.authentication.user.prefs;
}
}
},
brand: {
get: function() {
Iif (this.connection) {
return this.connection.brand;
}
return this._brand;
},
set: function(value) {
if (this.connection) {
this.connection.brand = value;
return;
}
this._brand = value;
}
},
brandLowerCase: {
get: function() {
if (this.connection) {
return this.connection.brandLowerCase;
}
return this._brandLowerCase;
},
set: function(value) {
if (this.connection) {
this.connection.brandLowerCase = value;
return;
}
this._brandLowerCase = value;
}
},
website: {
get: function() {
if (this.connection) {
return this.connection.website;
}
return this._website;
},
set: function(value) {
if (this.connection) {
this.connection.website = value;
return;
}
this._website = value;
}
},
connection: {
get: function() {
return this._connection;
},
set: function(value) {
this.ensureSetViaAppropriateType("connection", value);
}
},
enterDecryptedMode: {
value: function() {
var deferred = Q.defer(),
self = this;
var username;
if (this.authentication && this.authentication.user && this.authentication.user.username) {
username = this.authentication.user.username;
} else {
return;
}
this.whenDecryptionReady = deferred.promise;
// try {
// throw new Error("Decrypted mode was requested by the app. ");
// } catch (exception) {
// console.warn("Decrypted mode was requested by the app. ", exception.stack);
// }
this.prompt("Some data which you are about to view is encrypted. You can only view encrypted data if you confirm your identity. If you would like to edit or view the data we need to make sure that you are " + username).then(function(promptDetails) {
Eif (self.application && self.application.authentication && typeof self.application.authentication.confirmIdentity === "function") {
self.application.authentication.confirmIdentity({
password: promptDetails.response
}).then(function(confirmation) {
self.debug("Confirmed the user's identity", confirmation);
self._decryptedMode = true;
deferred.resolve(true);
}, function(error) {
self.debug("Unable to confirm the user's identity", error);
self._decryptedMode = false;
deferred.reject(false);
}).fail(function(error) {
self.debug("Error while confirming the user's identity", error);
self._decryptedMode = false;
deferred.reject(false);
});
} else {
self.warn("Not running in an application, but was able to simuli-prompt the user.");
self._decryptedMode = true;
deferred.resolve(true);
}
}, function(error) {
self.debug("Unable to prompt the user, the data will always be encrypted", error);
self._decryptedMode = false;
deferred.reject(false);
}).fail(function(error) {
self.debug("Error while prompting the user, the data will always be encrypted", error);
self._decryptedMode = false;
deferred.reject(false);
});
return this.whenDecryptionReady;
}
},
decryptedMode: {
get: function() {
if (this._decryptedMode !== undefined) {
return this._decryptedMode;
}
Eif (!this.whenDecryptionReady && !this.authentication.loggingIn) {
this.enterDecryptedMode();
}
},
set: function(value) {
Iif (value === this._decryptedMode) {
return;
}
Iif (value) {
this.warn("Cant set decryptedMode manually to true. ");
if (!this.whenDecryptionReady) {
this.enterDecryptedMode();
}
return;
}
this._decryptedMode = value;
}
},
fetch: {
value: function() {
this.todo("use same logic as the user from localStorage");
}
},
// Internal models: used by the parse function
INTERNAL_MODELS: {
value: {
connection: Connection,
corpus: Corpus,
contextualizer: Contextualizer,
authentication: Authentication,
currentSession: Session,
currentDataList: DataList,
search: Search
}
},
startApp: {
value: function(callback) {
/* Tell the app to render everything */
this.render();
if (typeof this.router === "function") {
/* Tell the router to render the home screen divs */
this.router = new Router();
this.router.renderDashboardOrNot(true);
FieldDBObject.history.start();
if (typeof callback === "function") {
this.debug("Calling back the startApps callback");
callback();
}
}
}
},
loading: {
get: function() {
return this._loading || this.fetching || false;
},
set: function(value) {
if (value === this._loading) {
return;
}
value = !!value;
if (value === true) {
this.status = "Loading dashboard";
}
this.loading = value;
}
},
/**
* This function creates the backbone objects, and links them up so that
* they are ready to be used in the views. This function should be called on
* app load, either by main, or by welcome new user. This function should
* not be called at any later time as it will break the connection between
* the views and the models. To load different models into the app after it
* has first loaded, use the loadFieldDBObjectsById function below.
*
* @param params An object containing key and value route parameters
*/
processRouteParams: {
value: function(routeParams) {
var self = this;
if (!routeParams) {
this.warn("Route params are undefined, not loading anything");
return;
}
this.routeParams = routeParams;
/*
* Handle precise routes
*/
if (routeParams.importType) {
self.debug("Creating an importer");
this.importer = this.importer || new Import({
importType: routeParams.importType
// corpus: this.corpus
});
} else Iif (routeParams.reportType) {
this.reportsList.filter = function(report) {
if (routeParams.reportType.match(report.fieldDBtype.toLowerCase())) {
return true;
} else {
return false;
}
};
} else Iif (routeParams.speakerType) {
this.speakersList.filter = function(speaker) {
if (routeParams.speakerType.match(speaker.fieldDBtype.toLowerCase())) {
return true;
} else {
return false;
}
};
} else if (routeParams.searchQuery) {
this.search = this.search || new Search({
searchQuery: routeParams.searchQuery
});
this.search.search(routeParams.searchQuery);
} else Iif (routeParams.docid) {
if (this.currentDoc && this.currentDoc.save) {
this.currentDoc.bug("Switching to another document without saving...");
}
new FieldDBObject({
id: routeParams.docid
}).fetch().then(function(result) {
// console.log(tempdoc);
self.currentDoc = FieldDBObject.convertDocIntoItsType(result);
self.render();
}, function(error) {
console.log("Unable to display this document.", error);
});
}
/*
* Letting the url determine which team is loaded
*/
Eif (routeParams.team) {
routeParams.team = Connection.validateUsername(routeParams.team).identifier;
if (!routeParams.corpusidentifier) {
this.todo("load the user's profile..." + routeParams.team);
} else {
/*
* Letting the url determine which corpus is loaded
*/
routeParams.corpusidentifier = Connection.validateIdentifier(routeParams.corpusidentifier).identifier;
this.currentCorpusDashboard = routeParams.team + "/" + routeParams.corpusidentifier;
var connection;
Iif (this.authentication &&
this.authentication.user &&
this.authentication.user.username &&
this.authentication.user.corpora &&
this.authentication.user.corpora.length > 0 &&
typeof this.authentication.user.corpora.findCorpusConnectionFromTitleAsUrl === "function") {
connection = this.authentication.user.corpora.findCorpusConnectionFromTitleAsUrl(routeParams.corpusidentifier, routeParams.team);
if (connection) {
// this.currentCorpusDashboardDBname = connection.dbname;
if (this.corpus && this.corpus.save && this.corpus.dbname !== connection.dbname) {
this.corpus.bug("Switching to another corpus without saving...");
}
this.corpus = new Corpus({
connection: connection,
dbname: connection.dbname
});
}
}
Eif (!connection) {
// this.status = "Please try another url of the form teamname/corpusname " + this.currentCorpusDashboardDBname + " is not valid.";
connection = Connection.defaultConnection();
connection.dbname = routeParams.team + "-" + routeParams.corpusidentifier;
this.corpus = new CorpusMask({
connection: connection,
dbname: connection.dbname
});
}
this.application.connection = connection;
}
}
/*
* Fetching corpus details if it is not complete
*/
if (this.corpus && this.corpus.dbname && !this.corpus.title) {
this.corpus.status = "Loading corpus details.";
return this.corpus.fetch().then(function(result) {
self.debug("Suceeded to download corpus details.", result);
self.corpus.status += "\n Loaded corpus details.";
self.status = "Loaded corpus details.";
if (self.application.importer) {
self.application.importer.corpus = self.corpus;
}
// self.render();
return self;
}, function(result) {
self.debug("Failed to download corpus details.", result);
self.corpus.error = result.userFriendlyErrors.join(" ");
self.status = self.corpus.status = "Failed to download corpus details. Are you sure this is the corpus you wanted to see: " + self.corpus.dbname;
// self.loginDetails.username = self.team.username;
// self.render();
return self;
}).fail(function(error) {
console.error(error.stack, self);
});
} else {
this.debug("Not fetching corpus ", this.corpus);
}
}
},
router: {
get: function() {
return this._router;
},
set: function(value) {
this.ensureSetViaAppropriateType("router", value);
}
},
showHelpOrNot: {
value: function() {
var self = this;
var username = this.authentication.user.username;
if (username === "public") {
//Dont show the help screen for the public user
return;
}
var helpShownCount = localStorage.getItem(username + "helpShownCount") || 0;
var helpShownTimestamp = localStorage.getItem(username + "helpShownTimestamp") || 0;
/*
* dont show the guide immediately if they are truely a new
* user, let them see the dashboard before they wonder how
* to use it. 60 seconds later, show the help.
*/
if (helpShownTimestamp === 0) {
self.helpCountReason = "Just in case you were wondering what all those buttons are for, check out Gretchen's Illustrated Guide to your dashboard! ";
self.helpCount = 3 - helpShownCount;
localStorage.setItem(username + "helpShownCount", ++helpShownCount);
localStorage.setItem(username + "helpShownTimestamp", Date.now());
self.timeout(function() {
self.router.navigate("help/illustratedguide", {
trigger: true
});
}, 60000);
return;
}
/*
* If this is not a brand new user:
*/
var milisecondsSinceLastHelp = Date.now() - helpShownTimestamp;
/* if its been more than 5 days, reset the help shown count to trigger the illustrated guide */
if (milisecondsSinceLastHelp > 432000000 && helpShownTimestamp !== 0) {
helpShownCount = 0;
self.helpCountReason = "Welcome back! It's been more than 5 days since you opened the app. ";
}
if (helpShownCount > 3) {
// do nothing
} else {
self.helpCount = 3 - helpShownCount;
localStorage.setItem(username + "helpShownCount", ++helpShownCount);
localStorage.setItem(username + "helpShownTimestamp", Date.now());
self.router.navigate("help/illustratedguide", {
trigger: true
});
}
}
},
renderHelp: function(helptype) {
this.render(helptype);
},
/**
* This function is used to save the entire app state that is needed to load when the app is re-opened.
* http://stackoverflow.com/questions/7794301/window-onunload-is-not-working-properly-in-chrome-browser-can-any-one-help-me
*
* $(window).on("beforeunload", function() {
return "Your own message goes here...";
});
*/
warnUserAboutSavedSyncedStateBeforeUserLeaves: {
value: function(e) {
this.debug("warnUserAboutSavedSyncedStateBeforeUserLeaves", e);
this.save();
var returntext = "";
if (this.view) {
if (this.view.totalUnsaved.length >= 1) {
returntext = "You have unsaved changes, click cancel to save them. \n\n";
}
if (this.view.totalUnsaved.length >= 1) {
returntext = returntext + "You have unsynced changes, click cancel and then click the sync button to sync them. This is only important if you want to back up your data or if you are sharing your data with a team. \n\n";
}
}
if (returntext === "") {
return; //don't show a pop up
} else {
return "Either you haven't been using the app and Chrome wants some of its memory back, or you want to leave the app.\n\n" + returntext;
}
}
},
/**
* Saves a json file via REST to a couchdb, must be online.
*
* @param bareActivityObject
*/
addActivity: {
value: function(bareActivityObject) {
var self = this;
bareActivityObject.verb = bareActivityObject.verb.replace("href=", "target='_blank' href=");
bareActivityObject.directobject = bareActivityObject.directobject.replace("href=", "target='_blank' href=");
bareActivityObject.indirectobject = bareActivityObject.indirectobject.replace("href=", "target='_blank' href=");
bareActivityObject.context = bareActivityObject.context.replace("href=", "target='_blank' href=");
self.debug("Saving activity: ", bareActivityObject);
var backboneActivity = new Activity(bareActivityObject);
var connection = this.connection;
var activitydb = connection.dbname + "-activity_feed";
if (bareActivityObject.teamOrPersonal !== "team") {
activitydb = this.authentication.user.username + "-activity_feed";
backboneActivity.attributes.user.set("gravatar", this.authentication.user.gravatar);
}
if (bareActivityObject.teamOrPersonal === "team") {
self.currentCorpusTeamActivityFeed.addActivity(bareActivityObject);
} else {
self.currentUserActivityFeed.addActivity(bareActivityObject);
}
}
},
/**
* This function saves the dashboard session, datalist and then corpus. Its success callback is called if all saves succeed, its fail is called if any fail.
* @param successcallback
* @param failurecallback
*/
save: {
value: function() {
var promises = [];
this.authentication.dispatchEvent("saveyourselfnow");
promises.push(this.currentSession.save());
promises.push(this.currentDataList.save());
promises.push(this.corpus.save());
promises.push(this.authentication.save());
this.authentication.staleAuthentication = true;
}
},
subscribers: {
value: {
any: []
}
},
subscribe: {
value: function(type, fn, context) {
type = type || "any";
fn = typeof fn === "function" ? fn : context[fn];
if (typeof this.subscribers[type] === "undefined") {
this.subscribers[type] = [];
}
this.subscribers[type].push({
fn: fn,
context: context || this
});
}
},
unsubscribe: {
value: function(type, fn, context) {
this.visitSubscribers("unsubscribe", type, fn, context);
}
},
publish: {
value: function(type, publication) {
this.visitSubscribers("publish", type, publication);
}
},
visitSubscribers: {
value: function(action, type, arg, context) {
var pubtype = type || "any";
var subscribers = this.subscribers[pubtype];
if (!subscribers || subscribers.length === 0) {
this.debug(pubtype + ": There were no subscribers.");
return;
}
var i;
var maxUnsubscribe = subscribers ? subscribers.length - 1 : 0;
var maxPublish = subscribers ? subscribers.length : 0;
if (action === "publish") {
// count up so that older subscribers get the message first
for (i = 0; i < maxPublish; i++) {
if (subscribers[i]) {
// TODO there is a bug with the subscribers they are getting lost, and
// it is trying to call fn of undefiend. this is a workaround until we
// figure out why subscribers are getting lost. Update: i changed the
// loop to count down and remove subscribers from the ends, now the
// size of subscribers isnt changing such that the subscriber at index
// i doesnt exist.
subscribers[i].fn.call(subscribers[i].context, arg);
}
}
this.debug("Visited " + subscribers.length + " subscribers.");
} else {
// count down so that subscribers index exists when we remove them
for (i = maxUnsubscribe; i >= 0; i--) {
try {
if (!subscribers[i].context) {
this.debug("This subscriber has no context. should we remove it? " + i);
}
if (subscribers[i].context === context) {
var removed = subscribers.splice(i, 1);
this.debug("Removed subscriber " + i + " from " + type, removed);
} else {
this.debug(type + " keeping subscriber " + i, subscribers[i].context);
}
} catch (e) {
this.debug("problem visiting Subscriber " + i, subscribers);
}
}
}
}
},
isAndroidApp: {
get: function() {
// Development tablet navigator.userAgent:
// Mozilla/5.0 (Linux; U; Android 3.0.1; en-us; gTablet Build/HRI66)
// AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13
// this.debug("The user agent is " + navigator.userAgent);
try {
return navigator.userAgent.indexOf("OfflineAndroidApp") > -1;
} catch (e) {
this.debug("Cant determine app type isAndroidApp, " + e);
return false;
}
}
},
isAndroid4: {
get: function() {
try {
return navigator.userAgent.indexOf("Android 4") > -1;
} catch (e) {
this.debug("Cant determine app type isAndroid4, " + e);
return false;
}
}
},
isChromeApp: {
get: function() {
try {
return window.location.href.indexOf("chrome-extension") > -1;
} catch (e) {
this.debug("Cant determine app type isChromeApp, " + e);
return false;
}
}
},
isCouchApp: {
get: function() {
try {
return window.location.href.indexOf("_design/") > -1;
} catch (e) {
this.debug("Cant determine app type isCouchApp, " + e);
return false;
}
}
},
isTouchDBApp: {
get: function() {
try {
return window.location.href.indexOf("localhost:8128") > -1;
} catch (e) {
this.debug("Cant determine app type isTouchDBApp, " + e);
return false;
}
}
},
isNodeJSApp: {
get: function() {
try {
return window.location.href !== undefined;
} catch (e) {
this.debug("Cant access window, app type isNodeJSApp, ", e);
return true;
}
}
},
isBackboneCouchDBApp: {
get: function() {
return false;
}
},
/**
* If not running offline on an android or in a chrome extension, assume we are
* online.
*
* @returns {Boolean} true if not on offline Android or on a Chrome Extension
*/
isOnlineOnly: {
get: function() {
return !this.isAndroidApp && !this.isChromeApp;
}
},
toJSON: {
value: function(includeEvenEmptyAttributes, removeEmptyAttributes) {
this.debug("Customizing toJSON ", includeEvenEmptyAttributes, removeEmptyAttributes);
var attributesNotToJsonify = ["corpus", "authentication"];
var json = FieldDBObject.prototype.toJSON.apply(this, [includeEvenEmptyAttributes, removeEmptyAttributes, attributesNotToJsonify]);
this.debug(json);
return json;
}
}
});
exports.App = App;
|