-
Notifications
You must be signed in to change notification settings - Fork 45
/
FieldDBObject.js
2236 lines (2044 loc) · 75.7 KB
/
FieldDBObject.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
/* globals alert, confirm, prompt, navigator, Android, FieldDB */
"use strict";
var Diacritics = require("diacritics");
var Q = require("q");
var packageJson;
try {
packageJson = require("./../package.json");
} catch (e) {
console.log("failed to load package.json", e);
packageJson = {
version: "x.x.x"
};
}
// var FieldDBDate = function FieldDBDate(options) {
// // this.debug("In FieldDBDate ", options);
// Object.apply(this, arguments);
// if (options) {
// this.timestamp = options;
// }
// };
// FieldDBDate.prototype = Object.create(Object.prototype, /** @lends FieldDBDate.prototype */ {
// constructor: {
// value: FieldDBDate
// },
// timestamp: {
// get: function() {
// return this._timestamp || 0;
// },
// set: function(value) {
// if (value === this._timestamp) {
// return;
// }
// if (!value) {
// delete this._timestamp;
// return;
// }
// if (value.replace) {
// try {
// value = value.replace(/["\\]/g, "");
// value = new Date(value);
// /* Use date modified as a timestamp if it isnt one already */
// value = value.getTime();
// } catch (e) {
// this.warn("Upgraded timestamp" + value);
// }
// }
// this._timestamp = value;
// }
// },
// toJSON: {
// value: function(includeEvenEmptyAttributes, removeEmptyAttributes) {
// var result = this._timestamp;
// if (includeEvenEmptyAttributes) {
// result = this._timestamp || 0;
// }
// if (removeEmptyAttributes && !this._timestamp) {
// result = 0;
// }
// return result;
// }
// }
// });
/**
* @class An extendable object which can recieve new parameters on creation.
*
* @param {Object} options Optional json initialization object
* @property {String} dbname This is the identifier of the corpus, it is set when
* a corpus is created. It must be a file save name, and be a permitted
* name in CouchDB which means it is [a-z] with no uppercase letters or
* symbols, by convention it cannot contain -, but _ is acceptable.
* @extends Object
* @tutorial tests/FieldDBObjectTest.js
*/
var FieldDBObject = function FieldDBObject(json) {
if (json && (json instanceof this.constructor || json.constructor.toString() === this.constructor.toString())) {
json.debug("This was already the right type, not converting it.");
return json;
}
// if (!this._fieldDBtype) {
// this._fieldDBtype = "FieldDBObject";
// }
if (json && json.id) {
this.useIdNotUnderscore = true;
}
if (json && json.api && this.api) {
if (json.api !== this.api) {
console.log("Using " + this.api + " when the api of the incoming model was " + json.api);
}
delete json.api;
}
this.verbose("In parent an json", json);
// Set the confidential first, so the rest of the fields can be encrypted
// if (json && json.corpus) {
// this.corpus = json.corpus;
// }
if (json && json.confidential && this.INTERNAL_MODELS["confidential"]) {
this.confidential = new this.INTERNAL_MODELS["confidential"](json.confidential);
}
if (json && json.fields && this.INTERNAL_MODELS["fields"]) {
this.fields = new this.INTERNAL_MODELS["fields"](json.fields);
}
if (this.INTERNAL_MODELS) {
this.debug("parsing with ", this.INTERNAL_MODELS);
}
var simpleModels = [];
for (var member in json) {
if (!json.hasOwnProperty(member)) {
continue;
}
this.debug("JSON: " + member);
if (json[member] &&
this.INTERNAL_MODELS &&
this.INTERNAL_MODELS[member] &&
typeof this.INTERNAL_MODELS[member] === "function" &&
!(json[member] instanceof this.INTERNAL_MODELS[member]) &&
!(this.INTERNAL_MODELS[member].compatibleWithSimpleStrings && typeof json[member] === "string")) {
json[member] = new this.INTERNAL_MODELS[member](json[member]);
} else {
simpleModels.push(member);
}
try {
this[member] = json[member];
} catch (e) {
this.warn(e.stack);
}
}
if (simpleModels.length > 0) {
this.debug("simpleModels", simpleModels.join(", "));
}
Object.apply(this, arguments);
// if (!this._rev) {
if (!this.id && !this._dateCreated) {
this.dateCreated = Date.now();
}
};
FieldDBObject.internalAttributesToNotJSONify = [
"$$hashKey",
"application",
"bugMessage",
"confirmMessage",
"confirmMergePromises",
"contextualizer",
"corpus",
"currentDoc",
"currentSession",
"datalist",
"database",
"db",
"debugMessages",
"decryptedMode",
"dontRecurse",
"fetching",
"fieldsInColumns",
"fossil",
"loaded",
"loading",
"newDatum",
"parent",
"perObjectAlwaysConfirmOkay",
"perObjectDebugMode",
"promptMessage",
"saved",
"saving",
"selected",
"temp",
"unsaved",
"useIdNotUnderscore",
"warnMessage",
"whenReady"
];
FieldDBObject.internalAttributesToAutoMerge = FieldDBObject.internalAttributesToNotJSONify.concat([
"appVersionWhenCreated",
"authServerVersionWhenCreated",
"created_at",
"dateCreated",
"dateModified",
"fieldDBtype",
"modifiedByUser",
"rev",
"roles",
"updated_at",
"version"
]);
FieldDBObject.ignore = function(property, ignorelist) {
if (!ignorelist) {
throw new Error("missing the list of ignores");
}
if (ignorelist.indexOf(property) > -1 || ignorelist.indexOf(property.replace(/^_/, "")) > -1) {
return true;
}
};
FieldDBObject.software = {};
FieldDBObject.hardware = {};
FieldDBObject.DEFAULT_STRING = "";
FieldDBObject.DEFAULT_OBJECT = {};
FieldDBObject.DEFAULT_ARRAY = [];
FieldDBObject.DEFAULT_COLLECTION = [];
FieldDBObject.DEFAULT_VERSION = "v" + packageJson.version;
FieldDBObject.DEFAULT_DATE = 0;
FieldDBObject.render = function(options) {
this.debug("Rendering, but the render was not injected for this " + this.fieldDBtype, options);
};
FieldDBObject.verbose = function(message, message2, message3, message4) {
try {
if (navigator && navigator.appName === "Microsoft Internet Explorer") {
return;
}
} catch (e) {
//do nothing, we are in node or some non-friendly browser.
}
if (this.verboseMode) {
var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
console.log(type.toUpperCase() + " VERBOSE: " + message);
if (message2) {
console.log(message2);
}
if (message3) {
console.log(message3);
}
if (message4) {
console.log(message4);
}
}
};
FieldDBObject.debugMode = false;
FieldDBObject.debug = function(message, message2, message3, message4) {
try {
if (navigator && navigator.appName === "Microsoft Internet Explorer") {
return;
}
} catch (e) {
//do nothing, we are in node or some non-friendly browser.
}
if (this.debugMode) {
var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
console.log(type.toUpperCase() + " DEBUG: " + message);
if (message2) {
console.log(message2);
}
if (message3) {
console.log(message3);
}
if (message4) {
console.log(message4);
}
}
};
FieldDBObject.todo = function(message, message2, message3, message4) {
var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
console.warn(type.toUpperCase() + " TODO: " + message);
if (message2) {
console.warn(message2);
}
if (message3) {
console.warn(message3);
}
if (message4) {
console.warn(message4);
}
};
FieldDBObject.popup = function(message) {
try {
alert(message);
} catch (e) {
this.warn(" Couldn't tell user about a popup: " + message);
// console.log("Alert is not defined, this is strange.");
}
var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
console.log(type.toUpperCase() + " POPUP: " + message);
};
FieldDBObject.bug = function(message) {
try {
alert(message);
} catch (e) {
this.warn(" Couldn't tell user about a bug: " + message);
// console.log("Alert is not defined, this is strange.");
}
var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
//outputing a stack trace
console.error(type.toUpperCase() + " BUG: " + message);
};
FieldDBObject.warn = function(message, message2, message3, message4) {
var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
// putting out a stacktrace
console.warn(type.toUpperCase() + " WARN: " + message);
if (message2) {
console.warn(message2);
}
if (message3) {
console.warn(message3);
}
if (message4) {
console.warn(message4);
}
};
FieldDBObject.prompt = function(message, optionalLocale, providedInput) {
var deferred = Q.defer(),
self = this;
Q.nextTick(function() {
var response;
if (self.alwaysReplyToPrompt !== undefined) {
response = providedInput || self.alwaysReplyToPrompt;
console.warn(self.fieldDBtype.toUpperCase() + " NOT PROMPTING USER: " + message + " \nThe code decided that they would probably reply `" + response + "` and it wasnt worth prompting.");
} else {
try {
response = prompt(message, providedInput);
// Let the user enter info, even JSON
if (response === "yes") {
response = providedInput;
} else if (response !== null) {
if (typeof providedInput !== "string" && typeof providedInput !== "number") {
try {
var parsed = JSON.parse(response);
response = parsed;
} catch (e) {
FieldDB.FieldDBObject.bug("There was a problem parsing your input.").then(function() {
FieldDB.FieldDBObject.prompt(message, optionalLocale, providedInput);
});
}
}
}
} catch (e) {
response = null;
console.warn(self.fieldDBtype.toUpperCase() + " UNABLE TO PROMPT USER: " + message + " pretending they said `" + response + "`");
}
}
if (response !== null && response !== undefined && typeof response.trim === "function") {
response = response.trim();
}
if (response) {
deferred.resolve({
message: message,
optionalLocale: optionalLocale,
response: response
});
} else {
deferred.reject({
message: message,
optionalLocale: optionalLocale,
response: response
});
}
});
return deferred.promise;
};
FieldDBObject.confirm = function(message, optionalLocale) {
var deferred = Q.defer(),
self = this;
Q.nextTick(function() {
var response;
if (self.alwaysConfirmOkay) {
console.warn(self.fieldDBtype.toUpperCase() + " NOT ASKING USER: " + message + " \nThe code decided that they would probably yes and it wasnt worth asking.");
response = self.alwaysConfirmOkay;
} else {
try {
response = confirm(message);
} catch (e) {
console.warn(self.fieldDBtype.toUpperCase() + " UNABLE TO ASK USER: " + message + " pretending they said " + self.alwaysConfirmOkay);
response = self.alwaysConfirmOkay;
}
}
if (response) {
deferred.resolve({
message: message,
optionalLocale: optionalLocale,
response: response
});
} else {
deferred.reject({
message: message,
optionalLocale: optionalLocale,
response: response
});
}
});
return deferred.promise;
};
/* set the application if you want global state (ie for checking if a user is authorized) */
// FieldDBObject.application = {}
/**
* The uuid generator uses a "GUID" like generation to create a unique string.
*
* @returns {String} a string which is likely unique, in the format of a
* Globally Unique ID (GUID)
*/
FieldDBObject.uuidGenerator = function() {
var S4 = function() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
return Date.now() + (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
};
FieldDBObject.regExpEscape = function(s) {
return String(s).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, "\\$1").
replace(/\x08/g, "\\x08");
};
FieldDBObject.getHumanReadableTimestamp = function() {
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var hour = today.getHours();
var minute = today.getMinutes();
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
if (hour < 10) {
hour = "0" + hour;
}
if (minute < 10) {
minute = "0" + minute;
}
return year + "-" + month + "-" + day + "_" + hour + "." + minute;
};
FieldDBObject.guessType = function(doc) {
if (!doc || JSON.stringify(doc) === {}) {
return "FieldDBObject";
}
FieldDBObject.debug("Guessing type " + doc._id);
var guessedType = doc.previousFieldDBtype || doc.jsonType || doc.collection || "FieldDBObject";
if (doc.api && doc.api.length > 0) {
FieldDBObject.debug("using api" + doc.api);
guessedType = doc.api[0].toUpperCase() + doc.api.substring(1, doc.api.length);
}
guessedType = guessedType.replace(/s$/, "");
guessedType = guessedType[0].toUpperCase() + guessedType.substring(1, guessedType.length);
if (guessedType === "Datalist") {
guessedType = "DataList";
}
if (guessedType === "FieldDBObject") {
if (doc.session) {
guessedType = "Datum";
if (doc.fields && doc.fields[0] === "judgement") {
guessedType = "LanguageDatum";
}
} else if (doc.datumFields && doc.sessionFields) {
guessedType = "Corpus";
} else if (doc.collection === "sessions" && doc.sessionFields) {
guessedType = "Session";
} else if (doc.text && doc.username && doc.timestamp && doc.gravatar) {
guessedType = "Comment";
} else if (doc.symbol && doc.tipa !== undefined) {
guessedType = "UnicodeSymbol";
}
}
FieldDBObject.debug("Guessed type " + doc._id + " is a " + guessedType);
return guessedType;
};
FieldDBObject.convertDocIntoItsType = function(doc, clone) {
// this.debugMode = true;
var guessedType,
typeofAnotherObjectsProperty = Object.prototype.toString.call(doc);
if (clone) {
var cloneDoc;
if (typeof doc.clone === "function") {
// if (doc instanceof FieldDBObject || typeof doc.fuzzyFind === "function") {
// wasnt able to make it what it should be, but it was at least some extension of FieldDBObject or Collection
cloneDoc = doc.clone();
doc = new doc.constructor(cloneDoc);
} else
// Return a clone of simple types, or a new clone of the json of this object
if (typeofAnotherObjectsProperty === "[object Boolean]") {
return !!doc;
} else if (typeofAnotherObjectsProperty === "[object String]") {
return doc + "";
} else if (typeofAnotherObjectsProperty === "[object Number]") {
return doc + 0;
} else if (typeofAnotherObjectsProperty === "[object Date]") {
return new Date(doc);
} else if (typeofAnotherObjectsProperty === "[object Array]") {
return doc.concat([]);
} else {
clone = doc.toJSON ? doc.toJSON() : doc;
doc = new doc.constructor(clone);
}
} else {
// Return the doc if its a simple type
if (typeofAnotherObjectsProperty === "[object Boolean]") {
return doc;
} else if (typeofAnotherObjectsProperty === "[object String]") {
return doc;
} else if (typeofAnotherObjectsProperty === "[object Number]") {
return doc;
} else if (typeofAnotherObjectsProperty === "[object Date]") {
return doc;
} else if (typeofAnotherObjectsProperty === "[object Array]") {
return doc;
}
}
if (typeof doc.debug === "function" && doc.constructor !== FieldDBObject) {
// if (doc instanceof FieldDBObject || typeof doc.fuzzyFind === "function") {
// wasnt able to make it what it should be, but it was at least some extension of FieldDBObject or Collection
return doc;
}
try {
guessedType = doc.fieldDBtype;
if (!guessedType || guessedType === "FieldDBObject") {
FieldDBObject.debug(" requesting guess type ");
guessedType = FieldDBObject.guessType(doc);
FieldDBObject.debug("request complete");
}
FieldDBObject.debug("Converting doc into type " + guessedType);
if (FieldDB && FieldDB[guessedType]) {
if (doc instanceof FieldDB[guessedType]) {
return doc;
}
doc = new FieldDB[guessedType](doc);
// FieldDBObject.warn("Converting doc into guessed type " + guessedType);
} else {
doc = new FieldDBObject(doc);
FieldDBObject.debug("This doc does not have a type than is known to the FieldDB system. It might display oddly ", doc);
}
} catch (e) {
FieldDBObject.debug("Couldn't convert this doc to its type " + guessedType + ", it will be a base FieldDBObject: " + JSON.stringify(doc));
FieldDBObject.debug(" error: ", e);
var checkPreviousTypeWithoutS = doc.previousFieldDBtype ? doc.previousFieldDBtype.replace(/s$/, "") : "";
if (guessedType !== "FieldDBObject" && guessedType !== checkPreviousTypeWithoutS) {
doc.previousFieldDBtype = doc.previousFieldDBtype || "";
doc.previousFieldDBtype = doc.previousFieldDBtype + guessedType;
}
doc = new FieldDBObject(doc);
}
return doc;
};
/** @lends FieldDBObject.prototype */
FieldDBObject.prototype = Object.create(Object.prototype, {
constructor: {
value: FieldDBObject
},
fieldDBtype: {
configurable: true,
get: function() {
return this._fieldDBtype || "FieldDBObject";
},
set: function(value) {
if (value !== this.fieldDBtype) {
this.debug("Using type " + this.fieldDBtype + " when the incoming object was " + value);
}
}
},
/**
* Can be set to true to debug all objects, or false to debug no objects and true only on the instances of objects which
* you want to debug.
*
* @type {Boolean}
*/
debugMode: {
get: function() {
if (this.perObjectDebugMode === undefined) {
return false;
} else {
return this.perObjectDebugMode;
}
},
set: function(value) {
if (value === this.perObjectDebugMode) {
return;
}
if (value === null || value === undefined) {
delete this.perObjectDebugMode;
return;
}
this.perObjectDebugMode = value;
}
},
debug: {
value: function( /* message, message2, message3, message4 */ ) {
if (this.debugMode) {
FieldDBObject.debug.apply(this, arguments);
}
}
},
verboseMode: {
get: function() {
if (this.perObjectVerboseMode === undefined) {
return false;
} else {
return this.perObjectVerboseMode;
}
},
set: function(value) {
if (value === this.perObjectVerboseMode) {
return;
}
if (value === null || value === undefined) {
delete this.perObjectVerboseMode;
return;
}
this.perObjectVerboseMode = value;
}
},
verbose: {
value: function( /* message, message2, message3, message4 */ ) {
if (this.verboseMode) {
FieldDBObject.verbose.apply(this, arguments);
}
}
},
bug: {
value: function(message) {
if (this.bugMessage) {
if (this.bugMessage.indexOf(message) > -1) {
this.warn("Not repeating bug message: " + message);
return;
}
this.bugMessage += ";;; ";
} else {
this.bugMessage = "";
}
this.bugMessage = this.bugMessage + message;
FieldDBObject.bug.apply(this, arguments);
}
},
popup: {
value: function(message) {
if (this.popupMessage) {
if (this.popupMessage.indexOf(message) > -1) {
this.warn("Not repeating popup message: " + message);
return;
}
this.popupMessage += ";;; ";
} else {
this.popupMessage = "";
}
this.popupMessage = this.popupMessage + message;
FieldDBObject.popup.apply(this, arguments);
}
},
alwaysConfirmOkay: {
get: function() {
if (this.perObjectAlwaysConfirmOkay === undefined) {
return false;
} else {
return this.perObjectAlwaysConfirmOkay;
}
},
set: function(value) {
if (value === this.perObjectAlwaysConfirmOkay) {
return;
}
if (value === null || value === undefined) {
delete this.perObjectAlwaysConfirmOkay;
return;
}
this.perObjectAlwaysConfirmOkay = value;
}
},
prompt: {
value: function(message) {
if (this.promptMessage) {
this.promptMessage += "\n";
} else {
this.promptMessage = "";
}
this.promptMessage = this.promptMessage + message;
return FieldDBObject.prompt.apply(this, arguments);
}
},
confirm: {
value: function(message) {
if (this.confirmMessage) {
this.confirmMessage += "\n";
} else {
this.confirmMessage = "";
}
this.confirmMessage = this.confirmMessage + message;
return FieldDBObject.confirm.apply(this, arguments);
}
},
warn: {
value: function(message) {
if (this.warnMessage) {
this.warnMessage += ";;; ";
} else {
this.warnMessage = "";
}
this.warnMessage = this.warnMessage + message;
FieldDBObject.warn.apply(this, arguments);
}
},
todo: {
value: function( /* message, message2, message3, message4 */ ) {
FieldDBObject.todo.apply(this, arguments);
}
},
decryptedMode: {
get: function() {
if (this.application) {
return this.application.decryptedMode;
}
// if not running in an app, dont need to demonstrate a mask the data if its decryptable
return this._decryptedMode;
},
set: function(value) {
if (this.application) {
this.application.decryptedMode = value;
} else {
this._decryptedMode = value;
}
}
},
render: {
configurable: true,
writable: true,
value: function(options) {
this.debug("Calling render with options", options);
FieldDBObject.render.apply(this, arguments);
}
},
ensureSetViaAppropriateType: {
value: function(propertyname, value, optionalInnerPropertyName) {
this.debug("ensureSetViaAppropriateType on " + propertyname, this.INTERNAL_MODELS);
if (!propertyname) {
console.error("Invalid call to ensureSetViaAppropriateType", value);
throw new Error("Invalid call to ensureSetViaAppropriateType");
}
optionalInnerPropertyName = optionalInnerPropertyName || "_" + propertyname;
if (value === this[optionalInnerPropertyName]) {
return this[optionalInnerPropertyName];
}
if (!value) {
delete this[optionalInnerPropertyName];
return;
}
if (this.INTERNAL_MODELS &&
this.INTERNAL_MODELS[propertyname] &&
typeof this.INTERNAL_MODELS[propertyname] === "function" &&
!(value instanceof this.INTERNAL_MODELS[propertyname]) &&
!(this.INTERNAL_MODELS[propertyname].compatibleWithSimpleStrings && typeof value === "string")) {
this.debug("Converting this into type for " + propertyname, value.constructor.toString());
value = new this.INTERNAL_MODELS[propertyname](value);
}
// This trims all strings in the system...
if (typeof value.trim === "function") {
value = value.trim();
}
this[optionalInnerPropertyName] = value;
return this[optionalInnerPropertyName];
}
},
unsaved: {
get: function() {
return this._unsaved;
},
set: function(value) {
this._unsaved = !!value;
}
},
calculateUnsaved: {
value: function() {
if (!this.fossil) {
this._unsaved = true;
return;
}
var previous = new this.constructor(this.fossil);
var current = new this.constructor(this.toJSON());
current.debugMode = this.debugMode;
if (previous.equals(current)) {
this.warn("The " + this.id + " didnt actually change. Not marking as edited");
this._unsaved = false;
} else {
this._unsaved = true;
}
return this._unsaved;
}
},
createSaveSnapshot: {
value: function(selfOrSnapshot, optionalUserWhoSaved) {
var self = this;
selfOrSnapshot = this;
this.debug(" Running snapshot...");
//update to selfOrSnapshot version
selfOrSnapshot.version = FieldDBObject.DEFAULT_VERSION;
try {
FieldDBObject.software = FieldDBObject.software || {};
FieldDBObject.software.appCodeName = navigator.appCodeName;
FieldDBObject.software.appName = navigator.appName;
FieldDBObject.software.appVersion = navigator.appVersion;
FieldDBObject.software.cookieEnabled = navigator.cookieEnabled;
FieldDBObject.software.doNotTrack = navigator.doNotTrack;
FieldDBObject.software.hardwareConcurrency = navigator.hardwareConcurrency;
FieldDBObject.software.language = navigator.language;
FieldDBObject.software.languages = navigator.languages;
FieldDBObject.software.maxTouchPoints = navigator.maxTouchPoints;
FieldDBObject.software.onLine = navigator.onLine;
FieldDBObject.software.platform = navigator.platform;
FieldDBObject.software.product = navigator.product;
FieldDBObject.software.productSub = navigator.productSub;
FieldDBObject.software.userAgent = navigator.userAgent;
FieldDBObject.software.vendor = navigator.vendor;
FieldDBObject.software.vendorSub = navigator.vendorSub;
if (navigator && navigator.geolocation && typeof navigator.geolocation.getCurrentPosition === "function") {
navigator.geolocation.getCurrentPosition(function(position) {
self.debug("recieved position information");
FieldDBObject.software.location = position.coords;
});
}
} catch (e) {
this.debug("Error loading software ", e);
FieldDBObject.software = FieldDBObject.software || {};
FieldDBObject.software.version = process.version;
FieldDBObject.software.appVersion = "PhantomJS unknown";
try {
var avoidmontagerequire = require;
var os = avoidmontagerequire("os");
FieldDBObject.hardware = FieldDBObject.hardware || {};
FieldDBObject.hardware.endianness = os.endianness();
FieldDBObject.hardware.platform = os.platform();
FieldDBObject.hardware.hostname = os.hostname();
FieldDBObject.hardware.type = os.type();
FieldDBObject.hardware.arch = os.arch();
FieldDBObject.hardware.release = os.release();
FieldDBObject.hardware.totalmem = os.totalmem();
FieldDBObject.hardware.cpus = os.cpus().length;
} catch (e) {
this.debug(" hardware is unknown.", e);
FieldDBObject.hardware = FieldDBObject.hardware || {};
FieldDBObject.software.appVersion = "Device unknown";
}
}
if (!optionalUserWhoSaved) {
optionalUserWhoSaved = {
name: "",
username: "unknown"
};
try {
if (this.corpus && this.corpus.connectionInfo && this.corpus.connectionInfo.userCtx) {
optionalUserWhoSaved.username = this.corpus.connectionInfo.userCtx.name;
} else if (FieldDBObject.application && FieldDBObject.application.user && FieldDBObject.application.user.username) {
optionalUserWhoSaved.username = optionalUserWhoSaved.username || FieldDBObject.application.user.username;
optionalUserWhoSaved.gravatar = optionalUserWhoSaved.gravatar || FieldDBObject.application.user.gravatar;
}
} catch (e) {
this.warn("Can't get the corpus connection info to guess who saved this.", e);
}
}
// optionalUserWhoSaved._name = optionalUserWhoSaved.name || optionalUserWhoSaved.username || optionalUserWhoSaved.browserVersion;
if (typeof optionalUserWhoSaved.toJSON === "function") {
var asJson = optionalUserWhoSaved.toJSON();
asJson.name = optionalUserWhoSaved.name;
optionalUserWhoSaved = asJson;
} else {
optionalUserWhoSaved.name = optionalUserWhoSaved.name;
}
// optionalUserWhoSaved.browser = browser;
this.debug(" Calculating userWhoSaved...");
var userWhoSaved = {
username: optionalUserWhoSaved.username,
name: optionalUserWhoSaved.name,
lastname: optionalUserWhoSaved.lastname,
firstname: optionalUserWhoSaved.firstname,
gravatar: optionalUserWhoSaved.gravatar
};
if (!selfOrSnapshot._rev) {
selfOrSnapshot._dateCreated = Date.now();
var enteredByUser = selfOrSnapshot.enteredByUser || {};
if (selfOrSnapshot.fields && selfOrSnapshot.fields.enteredbyuser) {
enteredByUser = selfOrSnapshot.fields.enteredbyuser;
} else if (!selfOrSnapshot.enteredByUser) {
selfOrSnapshot.enteredByUser = enteredByUser;
}
enteredByUser.value = userWhoSaved.name || userWhoSaved.username;
enteredByUser.json = enteredByUser.json || {};
enteredByUser.json.user = userWhoSaved;
enteredByUser.json.software = FieldDBObject.software;
try {
enteredByUser.json.hardware = Android ? Android.deviceDetails : FieldDBObject.hardware;
} catch (e) {
this.debug("Cannot detect the hardware used for selfOrSnapshot save.", e);
enteredByUser.json.hardware = FieldDBObject.hardware;
}
} else {
selfOrSnapshot._dateModified = Date.now();
var modifiedByUser = selfOrSnapshot.modifiedByUser || {};
if (selfOrSnapshot.fields && selfOrSnapshot.fields.modifiedbyuser) {
modifiedByUser = selfOrSnapshot.fields.modifiedbyuser;
} else if (!selfOrSnapshot.modifiedByUser) {
selfOrSnapshot.modifiedByUser = modifiedByUser;
}
if (selfOrSnapshot.modifiedByUsers) {
modifiedByUser = {
json: {
users: selfOrSnapshot.modifiedByUsers
}
};
delete selfOrSnapshot.modifiedByUsers;
}
modifiedByUser.value = modifiedByUser.value ? modifiedByUser.value + ", " : "";
modifiedByUser.value += userWhoSaved.name || userWhoSaved.username;
modifiedByUser.json = modifiedByUser.json || {};
if (modifiedByUser.users) {
modifiedByUser.json.users = modifiedByUser.users;
delete modifiedByUser.users;
}
modifiedByUser.json.users = modifiedByUser.json.users || [];
userWhoSaved.software = FieldDBObject.software;
userWhoSaved.hardware = FieldDBObject.hardware;
modifiedByUser.json.users.push(userWhoSaved);
}
if (FieldDBObject.software && FieldDBObject.software.location) {
var location;
if (selfOrSnapshot.location) {
location = selfOrSnapshot.location;
} else if (selfOrSnapshot.fields && selfOrSnapshot.fields.location) {
location = selfOrSnapshot.fields.location;
}
if (location) {
location.json = location.json || {};
location.json.previousLocations = location.json.previousLocations || [];
if (location.json && location.json.location && location.json.location.latitude) {
location.json.previousLocations.push(location.json.location);
}
this.debug("overwriting location ", location);
location.json.location = FieldDBObject.software.location;
location.value = location.json.location.latitude + "," + location.json.location.longitude;
}
}
this.debug(" Serializing to send object to selfOrSnapshotbase...");