forked from Sefaria/Sefaria-Mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sefaria.js
1992 lines (1923 loc) · 73.5 KB
/
sefaria.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
import { Alert, Platform } from 'react-native';
//import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge'; //https://github.com/idehub/react-native-google-analytics-bridge/blob/master/README.md
import { unzip } from 'react-native-zip-archive'; //for unzipping -- (https://github.com/plrthink/react-native-zip-archive)
import AsyncStorage from '@react-native-async-storage/async-storage';
import crashlytics from '@react-native-firebase/crashlytics';
import VersionNumber from 'react-native-version-number';
import { Search } from '@sefaria/search';
import sanitizeHtml from 'sanitize-html'
import Api from './api';
import History from './history';
import LinkContent from './LinkContent';
import { initAsyncStorage } from './StateManager';
import { VOCALIZATION } from './VocalizationEnum';
import URL from 'url-parse';
import analytics from '@react-native-firebase/analytics';
import {FileSystem} from 'react-native-unimodules'
import {
packageSetupProtocol,
downloadUpdate,
autoUpdateCheck,
checkUpdatesFromServer,
loadJSONFile,
fileExists, FILE_DIRECTORY,
simpleDelete,
} from './DownloadControl'
import { Topic } from './Topic';
const ERRORS = {
NOT_OFFLINE: 1,
NO_CONTEXT: 2,
CANT_GET_SECTION_FROM_DATA: "Couldn't find section in depth 3+ text",
};
Sefaria = {
_auth: {},
recentQueries: [],
people: {},
init: async function(dispatch) {
// numTimesOpenedApp
const numTimesOpenedApp = await AsyncStorage.getItem("numTimesOpenedApp");
Sefaria.numTimesOpenedApp = !!numTimesOpenedApp ? parseInt(numTimesOpenedApp) : 0;
if (Sefaria.numTimesOpenedApp === 0) { AsyncStorage.setItem('lastSyncTime', '0'); }
AsyncStorage.setItem("numTimesOpenedApp", JSON.stringify(Sefaria.numTimesOpenedApp + 1));
Sefaria.lastAppUpdateTime = await Sefaria.getLastAppUpdateTime();
await Sefaria._loadTOC();
await Sefaria.history._loadHistoryItems();
await initAsyncStorage(dispatch);
},
postInitSearch: function() {
return Sefaria._loadRecentQueries()
.then(Sefaria._loadSearchTOC);
},
postInit: function(networkSetting='wifiOnly') {
return Sefaria._loadPeople()
.then(Sefaria._loadHebrewCategories)
.then(packageSetupProtocol)
.then(autoUpdateCheck).then(async checkServer => {
if (checkServer) {
await checkUpdatesFromServer();
}
try {
await downloadUpdate(networkSetting, false); // this method compares what the user requested to what is on disk and retrieves anything missing
} catch (e) {
console.log('postInit download error');
console.log(e);
}
})
},
getLastAppUpdateTime: async function() {
// returns epoch time of last time the app was updated. used to compare if sources files are newer than downloaded files
const lastAppVersionString = await AsyncStorage.getItem("lastAppVersionString");
const currAppVersionString = VersionNumber.appVersion;
let lastAppUpdateTime;
if (lastAppVersionString !== currAppVersionString) {
// app has updated
lastAppUpdateTime = (new Date).getTime();
AsyncStorage.setItem("lastAppUpdateTime", JSON.stringify(lastAppUpdateTime));
AsyncStorage.setItem("lastAppVersionString", VersionNumber.appVersion);
} else {
// get stored time
lastAppUpdateTime = await AsyncStorage.getItem("lastAppUpdateTime");
lastAppUpdateTime = !!lastAppUpdateTime ? parseInt(lastAppUpdateTime) : 0;
}
return lastAppUpdateTime;
},
/*
if `context` and you're using API, only return section no matter what. default is true
versions is object with keys { en, he } specifying version titles of requested ref
*/
data: function(ref, context, versions) {
if (typeof context === "undefined") { context = true; }
return new Promise(function(resolve, reject) {
const bookRefStem = Sefaria.textTitleForRef(ref);
Sefaria.loadOfflineFile(ref, context, versions)
.then(data => { Sefaria.processFileData(ref, data).then(resolve); })
.catch(error => {
if (error === ERRORS.NOT_OFFLINE) {
Sefaria.loadFromApi(ref, context, versions, bookRefStem)
.then(data => { Sefaria.processApiData(ref, context, versions, data).then(resolve); })
.catch(error => {
if (error.error === ERRORS.NO_CONTEXT) {
resolve(error.data);
} else {
reject(error);
}
})
} else {
reject(error);
}
})
});
},
getSectionFromJsonData: function(ref, data) {
if ("content" in data) {
return data;
} else {
// If the data file represents multiple sections, pick the appropriate one to return
const refUpOne = Sefaria.refUpOne(ref);
//console.log(ref, data.sections);
if (ref in data.sections) {
return data.sections[ref];
} else if (refUpOne in data.sections) {
return data.sections[refUpOne];
} else {
return;
}
}
},
refUpOne: function(ref) {
//return ref up one level, assuming you can
return ref.lastIndexOf(":") !== -1 ? ref.slice(0, ref.lastIndexOf(":")) : ref;
},
processFileData: function(ref, data) {
return new Promise((resolve, reject) => {
// Store data in in memory cache if it's not there already
const result = Sefaria.getSectionFromJsonData(ref, data);
if (!result) { reject(ERRORS.CANT_GET_SECTION_FROM_DATA); }
// Annotate link objects with useful fields not included in export
result.content.forEach(segment => {
if ("links" in segment) {
segment.links.map(link => {
link.textTitle = Sefaria.textTitleForRef(link.sourceRef);
if (!("category" in link)) {
link.category = Sefaria.primaryCategoryForTitle(link.textTitle);
}
});
}
});
result.requestedRef = ref;
result.isSectionLevel = (ref === result.sectionRef);
Sefaria.cacheVersionInfo(result, true);
resolve(result);
});
},
processApiData: function(ref, context, versions, data) {
return new Promise((resolve, reject) => {
Sefaria.api.textCache(ref, context, versions, data);
Sefaria.cacheVersionInfo(data, true);
//console.log(data);
resolve(data);
});
},
shouldLoadFromApi: function(versions) {
// there are currently two cases where we load from API even if the index is downloaded
// 1) debugNoLibrary is true 2) you're loading a non-default version
return Sefaria.util.objectHasNonNullValues(versions) || Sefaria.debugNoLibrary;
},
loadOfflineFile: async function(ref, context, versions) {
var fileNameStem = ref.split(":")[0];
var bookRefStem = Sefaria.textTitleForRef(ref);
//if you want to open a specific version, there is no json file. force an api call instead
const shouldLoadFromApi = Sefaria.shouldLoadFromApi(versions);
if (shouldLoadFromApi) { throw ERRORS.NOT_OFFLINE; }
var jsonPath = Sefaria._JSONSourcePath(fileNameStem);
var zipPath = Sefaria._zipSourcePath(bookRefStem);
// Pull data from in memory cache if available
if (jsonPath in Sefaria._jsonData) {
return Sefaria._jsonData[jsonPath];
}
const preResolve = data => {
if (!(jsonPath in Sefaria._jsonData)) {
Sefaria._jsonData[jsonPath] = data;
}
return data;
};
let data;
try {
data = await Sefaria._loadJSON(jsonPath);
return preResolve(data);
} catch (e) {
const exists = await fileExists(zipPath);
if (exists) {
const path = await Sefaria._unzip(zipPath);
try {
data = await Sefaria._loadJSON(jsonPath);
return preResolve(data);
} catch (e2) {
// Now that the file is unzipped, if there was an error assume we have a depth 1 text
// NOAH 10/30/2019 not sure if this path is ever reached
var depth1FilenameStem = fileNameStem.substr(0, fileNameStem.lastIndexOf(" "));
var depth1JSONPath = Sefaria._JSONSourcePath(depth1FilenameStem);
try {
data = await Sefaria._loadJSON(depth1JSONPath);
return preResolve(data);
} catch (e3) {
console.error("Error loading JSON file: " + jsonPath + " OR " + depth1JSONPath);
throw ERRORS.NOT_OFFLINE;
}
}
} else {
throw ERRORS.NOT_OFFLINE;
}
}
},
loadFromApi: function(ref, context, versions, bookRefStem) {
return new Promise((resolve, reject) => {
// The zip doesn't exist yet, so make an API call
const cacheValue = Sefaria.api.textCache(ref, context, versions);
if (cacheValue) {
// Don't check the API cahce until we've checked for a local file, because the API
// cache may be left in a state with text but without links.
resolve(cacheValue);
}
Sefaria.api._text(ref, { context, versions, stripItags: true })
.then(data => {
if (context) { resolve(data); }
else { reject({error: ERRORS.NO_CONTEXT, data}); }
})
.catch(function(error) {
//console.error("Error with API: ", Sefaria.api._toURL(ref, false, 'text', true));
reject(error);
});
});
},
_jsonData: {}, // in memory cache for JSON data
_apiData: {}, // in memory cache for API data
textTitleForRef: function(ref) {
// Returns the book title named in `ref` by examining the list of known book titles.
if (!ref) { return null; }
for (let i = ref.length; i >= 0; i--) {
let book = ref.slice(0, i);
if (book in Sefaria.booksDict) {
return book;
}
}
return null;
},
sheetIdToUrl: sheetId => {
return `https://www.sefaria.org/sheets/${sheetId}`;
},
refToFullUrl: ref => {
return `https://www.sefaria.org/${Sefaria.refToUrl(ref)}`
},
refToUrl: ref => {
// TODO: ideally should be using Sefaria.makeRef() (from Sefaria-Project) to urlify
// this method works, but it doesn't generate identical urls to what the web client sends (last space before sections is a _ instead of .)
// this means that it will not hit the same cache as the web client
const book = Sefaria.textTitleForRef(ref);
let url = ref;
if (!book || ref.substr(book.length, 1) === ",") {
// if complex, we don't know what the complex nodes are so use naive method which works but makes the last space before sections a _ instead of .
url = ref.replace(/:/g,'.').replace(/ /g,'_');
} else {
// use book list to find last space before sections
url = `${book.replace(/ /g, '_')}${ref.substring(book.length).replace(/:/g, '.').replace(/ (?=[^ ]+$)/, '.')}`
}
return url;
},
urlToRef: url => {
// url: tref as it would appear in a url
url = url.replace(/\./, ' '); // first period is guarenteed to be separation between title and sections
url = url.replace(/_/g, ' ');
const title = Sefaria.textTitleForRef(url);
if (!title) { return { ref: url, title }; }
const ref = url.replace(/\./g, ':');
return { ref, title };
},
primaryCategoryForTitle: function(title, isSheet) {
if (isSheet) { return ["Sheets"]; }
const index = Sefaria.index(title);
if (!index) { return null; }
return index.primary_category;
},
categoriesForTitle: function(title, isSheet) {
if (isSheet) { return ["Sheets"]; }
const index = Sefaria.index(title);
if (!index) { return null;}
return index.categories;
},
categoryForRef: function(ref) {
return Sefaria.primaryCategoryForTitle(Sefaria.textTitleForRef(ref));
},
categoriesForRef: ref => Sefaria.categoriesForTitle(Sefaria.textTitleForRef(ref)),
getTitle: function(ref, heRef, isCommentary, isHe) {
// This function seems to have been the source of a bug which only presented itself on Android Hermes
// Fix was to avoid using this function: https://github.com/Sefaria/Sefaria-iOS/commit/facd85a541e434c6eb6c6e44fa272e5c68735ae3
// Try to find an alternative to using this function
const bookTitle = Sefaria.textTitleForRef(ref);
const collectiveTitles = Sefaria.collectiveTitlesDict[bookTitle];
if (collectiveTitles && isCommentary) {
if (isHe) { return collectiveTitles.he; }
else { return collectiveTitles.en; }
}
if (isHe) {
var engTitle = ref; //backwards compatibility for how this function was originally written
ref = heRef;
var engSeg = engTitle.split(":")[1];
var engFileNameStem = engTitle.split(":")[0];
var engSec = engFileNameStem.substring(engFileNameStem.lastIndexOf(" ")+1,engFileNameStem.length);
var heDaf = Sefaria.hebrew.encodeHebrewDaf(engSec,"long");
if (heDaf != null) {
var fullHeDaf = heDaf + ":" + Sefaria.hebrew.encodeHebrewNumeral(engSeg);
}
}
if (fullHeDaf) {
var find = '[״׳]'; //remove geresh and gershaim
var re = new RegExp(find, 'g');
ref = ref.replace(re, '');
var bookRefStem = ref.split(" " + fullHeDaf)[0];
} else {
var fileNameStem = ref.split(":")[0];
var bookRefStem = fileNameStem.substring(0, fileNameStem.lastIndexOf(" "));
}
if (isCommentary) {
var onInd = isHe ? bookRefStem.indexOf(" על ") : bookRefStem.indexOf(" on ");
if (onInd != -1)
bookRefStem = bookRefStem.substring(0,onInd);
}
return bookRefStem;
},
toHeSegmentRef: function(heSectionRef, enSegmentRef) {
if (!heSectionRef) {
try {
// try to convert with some heuristics
const enTitle = Sefaria.textTitleForRef(enSegmentRef);
if (!enTitle) { return enSegmentRef; }
const enSectionStr = enSegmentRef.replace(enTitle + ' ', '');
const heTitle = Sefaria.index(enTitle).heTitle;
if (enSectionStr.match(/(?:\d+:)*\d+(?:\-(?:\d+:)*\d)?$/)) {
// simple text
const heStartSections = enSectionStr.split('-')[0].split(':').map(s => Sefaria.hebrew.encodeHebrewNumeral(parseInt(s))).join(':');
let heEndSections = '';
if (enSectionStr.indexOf('-') !== -1) {
heEndSections = '-' + enSectionStr.split('-')[1].split(':').map(s => Sefaria.hebrew.encodeHebrewNumeral(parseInt(s))).join(':');
}
return `${heTitle} ${heStartSections}${heEndSections}`;
}
return enSegmentRef;
} catch (e) {
return enSegmentRef;
}
}
const enSections = enSegmentRef.substring(enSegmentRef.lastIndexOf(" ")+1).split(":");
const heSections = heSectionRef.substring(heSectionRef.lastIndexOf(" ")+1).split(":");
if (enSections.length === heSections.length) { return heSectionRef; } // already segment level
else if (heSections.length + 1 === enSections.length) {
const segNum = parseInt(enSections[enSections.length-1]);
if (!segNum) { return heSectionRef; }
return `${heSectionRef}:${Sefaria.hebrew.encodeHebrewNumeral(segNum)}׳`
} else {
console.log("weirdness", heSectionRef, enSegmentRef);
return heSectionRef;
}
},
booksDict: {},
collectiveTitlesDict: {},
_index: {}, // Cache for text index records
index: function(text, index) {
if (!index) {
return this._index[text];
} else {
this._index[text] = index;
}
},
showSegmentNumbers: function(text) {
let index = Sefaria.index(text);
if (!index) return true; //default to true
return ['Liturgy'].indexOf(index.categories[0]) == -1;
},
canBeContinuous: function(text) {
const index = Sefaria.index(text);
if (!index) { return false; } // default to false
// removing Talmud for now because cts mode is broken
return [].indexOf(index.categories[0]) != -1
},
canHaveAliyot: function(text) {
const index = Sefaria.index(text);
if (!index) { return false; }
return index.categories.length === 2 && index.categories[1] === "Torah";
},
vowelToggleAvailability: function(segmentArray) {
if(!segmentArray || segmentArray.length == 0) return VOCALIZATION.NONE;
const sample = segmentArray[0]['he'];
const vowels_re = /[\u05b0-\u05c3\u05c7]/g;
const cantillation_re = /[\u0591-\u05af]/g;
if (cantillation_re.test(sample)) {
return VOCALIZATION.TAAMIM_AND_NIKKUD;
} else if(vowels_re.test(sample)) {
return VOCALIZATION.NIKKUD;
} else {
return VOCALIZATION.NONE;
}
},
_loadTOC: function() {
return Sefaria.util.openFileInSources("toc.json").then(data => {
Sefaria.toc = data;
Sefaria._cacheIndexFromToc(data, true);
});
},
search_toc: null,
_loadSearchTOC: function() {
return Sefaria.util.openFileInSources('search_toc.json').then(data => {
Sefaria.search_toc = data;
});
},
_loadHebrewCategories: function() {
return Sefaria.util.openFileInSources("hebrew_categories.json").then(data => {
Sefaria.hebrewCategories = data;
Sefaria.englishCategories = {}; // used for classifying cats in autocomplete
Object.entries(data).forEach(([key, value]) => {
Sefaria.englishCategories[value] = 1;
});
});
},
_loadPeople: function() {
return Sefaria.util.openFileInSources("people.json").then(data => {
Sefaria.people = data;
});
},
//for debugging
_removeBook: function(toc, book) {
findCats = function(toc, book, cats) {
for (let i = 0; i < toc.length; i++) {
if ('title' in toc[i]) {
if (toc[i].title == book) {
cats.push(i);
return cats;
}
} else {
let newCats = cats.slice(0);
newCats.push(i);
let ret = findCats(toc[i].contents, book, newCats);
if (ret) {
return ret;
}
}
}
}
var cats = findCats(toc, book, []);
var newToc = Sefaria.util.clone(toc);
var tempToc = newToc;
for (var j = 0; j < cats.length-1; j++) {
tempToc = tempToc[cats[j]].contents;
}
tempToc.splice(cats[cats.length-1],1);
return newToc;
},
_cacheIndexFromToc: function(toc, isTopLevel=false) {
// Unpacks contents of Sefaria.toc into index cache.
if (isTopLevel) {
Sefaria.topLevelCategories = [];
Sefaria.booksDict = {};
Sefaria.collectiveTitlesDict = {};
Sefaria._index = {};
}
for (var i = 0; i < toc.length; i++) {
if ("category" in toc[i]) {
if (isTopLevel) { Sefaria.topLevelCategories.push(toc[i].category); }
Sefaria._cacheIndexFromToc(toc[i].contents)
} else {
Sefaria.index(toc[i].title, toc[i]);
Sefaria.booksDict[toc[i].title] = 1;
if (toc[i].collectiveTitle) {
Sefaria.collectiveTitlesDict[toc[i].title] = {en: toc[i].collectiveTitle, he: toc[i].heCollectiveTitle};
}
}
}
},
topLevelCategories: [], // useful for ordering categories in linkSummary
toc: null,
tocItemsByCategories: function(cats) {
// Returns the TOC items that correspond to the list of categories 'cats'
var list = Sefaria.toc
for (var i = 0; i < cats.length; i++) {
var found = false;
for (var k = 0; k < list.length; k++) {
if (list[k].category == cats[i]) {
list = Sefaria.util.clone(list[k].contents);
found = true;
break;
}
}
if (!found) {
return [];
}
}
return list;
},
_versionInfo: {},
cacheVersionInfo: function(data, isSection) {
//isSection = true if data has `sectionRef`. false if data has `title`
attrs = ['versionTitle','heVersionTitle','versionNotes','heVersionNotes','license','heLicense','versionSource','heVersionSource','versionTitleInHebrew','heVersionTitleInHebrew','versionNotesInHebrew','heVersionNotesInHebrew'];
cacheKey = isSection ? data.sectionRef : data.title;
Sefaria._versionInfo[cacheKey] = {};
attrs.map((attr)=>{
Sefaria._versionInfo[cacheKey][attr] = data[attr];
});
//console.log("SETTING VERSION INFO", cacheKey, isSection,Sefaria._versionInfo[cacheKey]);
},
versionInfo: function(ref, title, vlang) {
let versionInfo = {};
let sectionInfo = Sefaria._versionInfo[ref];
if (!sectionInfo) sectionInfo = {};
let indexInfo = Sefaria._versionInfo[title];
if (!indexInfo) indexInfo = {};
attrs = ['versionTitle', 'versionTitleInHebrew', 'versionNotes', 'versionNotesInHebrew', 'license', 'versionSource'];
let allFieldsUndefined = true;
attrs.map((attr)=>{
//if 'he', prepend 'he' to attr
const enAttr = attr;
if (vlang === 'hebrew') { attr = 'he' + attr[0].toUpperCase() + attr.substring(1); }
versionInfo[enAttr] = !!sectionInfo[attr] ? sectionInfo[attr] : indexInfo[attr];
if (!!versionInfo[enAttr]) { allFieldsUndefined = false; }
});
if (allFieldsUndefined) { versionInfo = null; }
return versionInfo;
},
commentaryList: function(title) {
// Returns the list of commentaries for 'title' which are found in Sefaria.toc
var index = this.index(title);
if (!index) { return []; }
var cats = [index.categories[0], "Commentary"]; //NOTE backwards compatibility
var isCommentaryRefactor = this.isTOCCommentaryRefactor();
if (isCommentaryRefactor) {
cats = [index.categories[0]];
}
var branch = this.tocItemsByCategories(cats);
var commentariesInBranch = function(title, branch) {
// Recursively walk a branch of TOC, return a list of all commentaries found on `title`.
var results = [];
for (var i=0; i < branch.length; i++) {
if (branch[i].title) {
if (isCommentaryRefactor) {
if (branch[i].dependence === "Commentary" && !!branch[i].base_text_titles && branch[i].base_text_titles.includes(title)) {
results.push(branch[i]);
}
} else {
var split = branch[i].title.split(" on ");
if (split.length == 2 && split[1] === title) {
results.push(branch[i]);
}
}
} else {
results = results.concat(commentariesInBranch(title, branch[i].contents));
}
}
return results;
};
let comms = commentariesInBranch(title, branch);
//console.log("isComms", isCommentaryRefactor, "comms",comms);
return comms;
},
isTOCCommentaryRefactor: function() {
var list = Sefaria.toc;
var leafSeen = false; // once we see the first leaf, we can check for `dependence` field
while (!leafSeen) {
if (list[0].hasOwnProperty('title')) {
leafSeen = true;
return list[0].hasOwnProperty('dependence');
} else {
list = list[0].contents;
}
}
return false;
},
_commentatorListBySection: {},
commentatorListBySection: function(ref) {
return Sefaria._commentatorListBySection[ref];
},
cacheCommentatorListBySection: function(ref, data) {
if (ref in Sefaria._commentatorListBySection) { return; }
const en = new Set();
const he = new Set();
for (let i = 0; i < data.length; i++) {
if (!("links" in data[i])) { continue; }
for (let j =0; j < data[i].links.length; j++) {
const link = data[i].links[j];
if (link.category === "Commentary") {
const tempIndex = Sefaria.index(link.textTitle);
if (!tempIndex) { continue; }
const enTitle = link.collectiveTitle || link.textTitle;
let heTitle = link.heCollectiveTitle || tempIndex.heTitle;
if (!enTitle || !heTitle) { continue; }
en.add(enTitle);
he.add(heTitle);
}
}
}
const commentators = {
en: [...en],
he: [...he]
}
Sefaria._commentatorListBySection[ref] = commentators;
},
_textToc: {},
textToc: function(title) {
return new Promise((resolve, reject) => {
const resolver = function(data) {
data = Sefaria._fixTalmudAltStructAddressTypes(data);
Sefaria._textToc[title] = data;
Sefaria.cacheVersionInfo(data,false);
resolve(data);
};
if (title in Sefaria._textToc) {
resolve(Sefaria._textToc[title]);
} else {
const path = Sefaria._JSONSourcePath(title + "_index");
Sefaria
._loadJSON(path)
.then(resolver)
.catch(()=>{Sefaria.api._request(title, 'index', true, {}).then(resolver)});
}
});
},
_fixTalmudAltStructAddressTypes: function(textToc) {
// This is a bandaid on what may or may not be bad data. For Talmud alt struct "Chapter", we want to display
// sections with Talmud address type, but the data current lists them as Integer.
if (textToc.categories.length == 3 &&
textToc.categories[0] == "Talmud" &&
textToc.categories[1] == "Bavli" &&
textToc.categories[2].indexOf("Seder ") != -1) {
for (var i = 0; i < textToc.alts.Chapters.nodes.length; i++) {
textToc.alts.Chapters.nodes[i].addressTypes = ["Talmud"];
}
}
return textToc;
},
reformatTalmudContent(segment) {
return segment
.replace(/<span\s+class="gemarra-regular">(.+?)<\/span>/g, '<gemarraregular>$1</gemarraregular>')
.replace(/<span\s+class="gemarra-italic">(.+?)<\/span>/g, '<gemarraitalic>$1</gemarraitalic>')
.replace(/<span\s+class="it-text">(.+?)<\/span>/g, '<i>$1</i>')
},
categoryAttribution: function(categories) {
var attributions = [
{
categories: ["Talmud", "Bavli"],
english: "The William Davidson Talmud",
hebrew: "תלמוד מהדורת ויליאם דוידסון",
link: "https://www.sefaria.org/william-davidson-talmud"
}
];
var attribution = null;
for (var i = 0; i < attributions.length; i++) {
if (categories && categories.length >= attributions[i].categories.length &&
Sefaria.util.compareArrays(attributions[i].categories, categories.slice(0, attributions[i].categories.length))) {
attribution = attributions[i];
break;
}
}
return attribution;
},
calendar: null,
_loadCalendar: async function() {
const data = await Sefaria.util.openFileInSources("calendar.json");
Sefaria.calendar = data;
},
topic_toc: null,
loadTopicToc: async function () {
const data = await Sefaria.util.openFileInSources("topic_toc.json");
Sefaria.topic_toc = data;
Sefaria._initTopicTocPages();
},
_topicTocPages: null,
_topicTocObjectMap: {}, // dictionary from slug to topic object as it appears in topicToc
_initTopicTocPages: function() {
Sefaria._topicTocPages = Sefaria.topic_toc.reduce(Sefaria._initTopicTocReducer, {});
Sefaria._topicTocPages[Sefaria._topicTocPageKey(null)] = Sefaria.topic_toc.map(({children, ...goodstuff}) => goodstuff);
},
_initTopicTocReducer: function(a,c) {
Sefaria._topicTocObjectMap[c.slug] = new Topic({...c, title: {en: c.en, he: c.he}});
if (!c.children) { return a; }
a[Sefaria._topicTocPageKey(c.slug)] = c.children;
for (let sub_c of c.children) {
Sefaria._initTopicTocReducer(a, sub_c);
}
return a;
},
_topicTocCategory: null,
_initTopicTocCategory: function() {
Sefaria._topicTocCategory = Sefaria.topic_toc.reduce(Sefaria._initTopicTocCategoryReducer, {});
},
_initTopicTocCategoryReducer: function(a,c) {
if (!c.children) {
a[c.slug] = c.parent;
return a;
}
for (let sub_c of c.children) {
sub_c.parent = { en: c.en, he: c.he, slug: c.slug };
Sefaria._initTopicTocCategoryReducer(a, sub_c);
}
return a;
},
_topicTocPageKey: slug => "_" + slug,
topicTocPage: function(parent) {
// if parent === null, return toc page for root
if (!Sefaria.topic_toc) { return; }
const key = Sefaria._topicTocPageKey(parent);
return Sefaria._topicTocPages[key];
},
getTopicTocObject: (slug) => {
return Sefaria._topicTocObjectMap[slug];
},
topicTocCategory: function(slug) {
// return category english and hebrew for slug
// return null if slug has no category (useful for passing result into topicTocPage())
if (!this._topicTocCategory) { this._initTopicTocCategory(); }
return this._topicTocCategory[slug] || null;
},
isTopicTopLevel: function(slug) {
// returns true is `slug` is part of the top level of topic toc
return Sefaria.topic_toc.filter(x => x.slug == slug).length > 0;
},
galusOrIsrael: null,
getGalusStatus: function() {
return fetch('https://www.geoip-db.com/json')
.then(res => res.json())
.then(data => {
if (data.country_code == "IL") {
Sefaria.galusOrIsrael = "israel"
} else {
Sefaria.galusOrIsrael = "diaspora"
}
return Sefaria.galusOrIsrael;
})
.catch(()=> {Sefaria.galusOrIsrael = "diaspora";})
},
getCalendars: function(custom, diaspora) {
if (!Sefaria.calendar) { return []; }
const dateString = Sefaria._dateString();
const cal_obj = Sefaria.calendar[dateString];
if (!cal_obj) { return []; }
const preference_key = `${diaspora ? 1 : 0}|${custom[0]}`;
const cal_items = cal_obj[preference_key] || [];
const existing_items = new Set(cal_items.map(c => c.title.en));
for (let c of cal_obj.d) {
if (!existing_items.has(c.title.en)) {
cal_items.push(c);
}
}
return cal_items.sort((a, b) => a.order - b.order);
},
_dateString: function(date) {
// Returns of string in the format "DD/MM/YYYY" for either `date` or today.
var date = typeof date === 'undefined' ? new Date() : date;
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth()+1)).slice(-2); //January is 0!
var year = date.getFullYear();
return `${year}-${month}-${day}`;
},
saveRecentQuery: function(query, type, key, pic) {
//type = ["ref", "book", "person", "toc", "query", "topic", "user"]
const newQuery = {query, type, key, pic};
if (Sefaria.recentQueries.length > 0 && Sefaria.recentQueries[0].query === newQuery.query && Sefaria.recentQueries[0].type === newQuery.type) {
return; // don't add duplicate queries in a row
}
Sefaria.recentQueries.unshift(newQuery);
Sefaria.recentQueries = Sefaria.recentQueries.slice(0,100);
AsyncStorage.setItem("recentQueries", JSON.stringify(Sefaria.recentQueries)).catch(function(error) {
console.error("AsyncStorage failed to save: " + error);
});
},
_loadRecentQueries: function() {
//return AsyncStorage.setItem("recentQueries", JSON.stringify([]));
return AsyncStorage.getItem("recentQueries").then(function(data) {
Sefaria.recentQueries = JSON.parse(data) || [];
});
},
_deleteUnzippedFiles: function() {
return new Promise((resolve, reject) => {
FileSystem.readDirectoryAsync(FileSystem.documentDirectory).then(fileList => {
for (let f of fileList) {
if (f.endsWith(".json")) {
//console.log('deleting', f.path);
simpleDelete(`${FileSystem.documentDirectory}/${f}`).then(() => {});
}
}
resolve();
});
});
},
_unzip: function(zipSourcePath) {
return unzip(zipSourcePath, FileSystem.documentDirectory);
},
_loadJSON: function(JSONSourcePath) {
return loadJSONFile(JSONSourcePath)
},
_JSONSourcePath: function(fileName) {
return (FileSystem.documentDirectory + "/" + fileName + ".json");
},
_zipSourcePath: function(fileName) {
return (FileSystem.documentDirectory + "/library/" + fileName + ".zip");
},
textFromRefData: function(data) {
// Returns a dictionary of the form {en: "", he: "", sectionRef: ""} that includes a single string with
// Hebrew and English for `data.requestedRef` found in `data` as returned from Sefaria.data.
// sectionRef is so that we know which file / api call to make to open this text
// `data.requestedRef` may be either section or segment level or ranged ref.
if (data.isSectionLevel) {
let enText = "", heText = "";
for (let i = 0; i < data.content.length; i++) {
let item = data.content[i];
if (typeof item.text === "string") enText += item.text + " ";
if (typeof item.he === "string") heText += item.he + " ";
}
return new LinkContent(enText, heText, data.sectionRef);
} else {
let segmentNumber = data.requestedRef.slice(data.ref.length+1);
let toSegmentNumber = -1;
let dashIndex = segmentNumber.indexOf("-");
if (dashIndex !== -1) {
toSegmentNumber = parseInt(segmentNumber.slice(dashIndex+1));
segmentNumber = parseInt(segmentNumber.slice(0, dashIndex));
} else { segmentNumber = parseInt(segmentNumber); }
let enText = "";
let heText = "";
for (let i = 0; i < data.content.length; i++) {
let item = data.content[i];
const currSegNum = parseInt(item.segmentNumber);
if (currSegNum >= segmentNumber && (toSegmentNumber === -1 || currSegNum <= toSegmentNumber)) {
if (typeof item.text === "string") enText += item.text + " ";
if (typeof item.he === "string") heText += item.he + " ";
if (toSegmentNumber === -1) {
break; //not a ranged ref
}
}
}
return new LinkContent(enText, heText, data.sectionRef);
}
},
isGettinToBePurimTime: function() {
const msInDay = 1000*60*60*24;
const purimsOfTheFuture = [[2020, 2, 10], [2021, 1, 26], [2022, 2, 17], [2023, 2, 7], [2024, 2, 24], [2025, 2, 14], [2026, 2, 4], [2027, 2, 24], [2028, 2, 12], [2029, 2, 2]];
const now = new Date();
for (let potentialPurim of purimsOfTheFuture) {
const daysLeft = ((new Date(...potentialPurim)) - now)/msInDay;
if (daysLeft < 7 && daysLeft > -3) {
return true;
}
}
return false;
},
links: {
_linkContentLoadingStack: [],
/* when you switch segments, delete stack and hashtable */
reset: function() {
Sefaria.links._linkContentLoadingStack = [];
},
relatedCacheKey(ref, online) {
return `${ref}|${online}`;
},
loadRelated: async function(ref, online) {
if (online) {
const data = await Sefaria.api.related(ref);
return data;
} else {
const cacheKey = Sefaria.links.relatedCacheKey(ref, online);
const cached = Sefaria.api._related[cacheKey];
if (!!cached) { return cached; }
const data = await Sefaria.loadOfflineFile(ref, false);
// mimic response of links API so that addLinksToText() will work independent of data source
const sectionData = Sefaria.getSectionFromJsonData(ref, data);
if (!sectionData) { throw ERRORS.CANT_GET_SECTION_FROM_DATA; }
const linkList = (sectionData.content.reduce((accum, segment, segNum) => accum.concat(
("links" in segment) ? segment.links.map(link => {
const index_title = Sefaria.textTitleForRef(link.sourceRef);
const collectiveTitle = Sefaria.collectiveTitlesDict[index_title];
return {
sourceRef: link.sourceRef,
sourceHeRef: link.sourceHeRef,
index_title,
collectiveTitle,
category: ("category" in link) ? link.category : Sefaria.primaryCategoryForTitle(index_title),
anchorRef: `${ref}:${segNum+1}`,
sourceHasEn: link.sourceHasEn,
}
}) : []
), []));
const offlineRelatedData = {links: linkList};
Sefaria.api._related[cacheKey] = offlineRelatedData;
return offlineRelatedData;
}
},
getSegmentIndexFromRef: function(ref) {
let index = parseInt(ref.substring(ref.lastIndexOf(':') + 1)) - 1;
if (!index && index !== 0) {
// try again. assume depth-1 text
index = parseInt(ref.substring(ref.lastIndexOf(' ') + 1).trim()) - 1;
}
return index;
},
organizeRelatedBySegment: function(related) {
let output = {};
//filter out books not in toc
Object.entries(related).map(([key, valueList]) => {
if (key == 'links') { valueList = valueList.filter(l=>!!Sefaria.booksDict[l.index_title]); }
output[key] = [];
for (let value of valueList) {
if (value.expandedRefs) {
delete value.expandedRefs;
}
const anchors = value.anchorRefExpanded || [value.anchorRef];
if (anchors.length === 0) { continue; }
for (let anchor of anchors) {
const refIndex = Sefaria.links.getSegmentIndexFromRef(anchor);
if (!output[key][refIndex]) { output[key][refIndex] = []; }
let outputValue = value;
if (key == 'links') {
outputValue = {
"category": value.category,
"sourceRef": value.sourceRef,
"sourceHeRef": value.sourceHeRef,
"textTitle": value.index_title,
"sourceHasEn": value.sourceHasEn,
"collectiveTitle": value.collectiveTitle ? value.collectiveTitle.en: null,
"heCollectiveTitle": value.collectiveTitle ? value.collectiveTitle.he : null,
};
}
output[key][refIndex].push(outputValue);
}
}
});
return output;
},
addRelatedToSheet: function(sheet, related, sourceRef) {
const related_obj = Sefaria.links.organizeRelatedBySegment(related);
const sheetSegIndexes = [];
for (let i = 0; i < sheet.length; i++) {
if (sheet[i].sourceRef === sourceRef) { sheetSegIndexes.push(i); }
}
Object.entries(related_obj).map(([key, valueList]) => {
const flattenedValues = valueList.reduce((accum, curr) => accum.concat(curr), []);
for (let i of sheetSegIndexes) {
if (key === 'links') {
sheet[i][key] = flattenedValues;
} else {
if (!sheet[i].relatedWOLinks) { sheet[i].relatedWOLinks = []; }
sheet[i].relatedWOLinks[key] = flattenedValues;
}
}
});
return sheet;
},
addRelatedToText: function(text, related) {
const related_obj = Sefaria.links.organizeRelatedBySegment(related);
return text.map((seg,i) => ({
...seg,
links: related_obj.links[i] || [],
relatedWOLinks: {
...Object.keys(related_obj).filter(x => x !== 'links').reduce((obj, x) => {
obj[x] = related_obj[x][i] || [];
return obj;
}, {}),
},
}));
},
loadLinkData: function(ref, pos, resolveClosure, rejectClosure, runNow) {
const parseData = async function(data) {
let result;
try {
result = data.fromAPI ? data.result : Sefaria.textFromRefData(data);
} catch (e) {
crashlytics().recordError(new Error(`loadLinkData failed to load ${data.requestedRef}`));
}
let prev = Sefaria.links._linkContentLoadingStack.shift();
//delete Sefaria.links._linkContentLoadingHash[prev.ref];
//console.log("Removing from queue:",prev.ref,"Length:",Sefaria.links._linkContentLoadingStack.length);
if (Sefaria.links._linkContentLoadingStack.length > 0) {
let next = Sefaria.links._linkContentLoadingStack[0]; //Sefaria.links._linkContentLoadingStack.length-1
Sefaria.links.loadLinkData(next.ref, next.pos, null, null, true)
.then(next.resolveClosure)
.catch(next.rejectClosure);
}
if (result) {
return result;
} else {
throw result;
}