-
Notifications
You must be signed in to change notification settings - Fork 5
/
libraryparser.pas
executable file
·2197 lines (1942 loc) · 71.8 KB
/
libraryparser.pas
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
unit libraryParser;
{$I videlibrilanguageconfig.inc}
interface
uses
Classes, SysUtils, simplehtmlparser, extendedhtmlparser, simplexmlparser, inifilessafe,internetaccess,regexpr,booklistreader,multipagetemplate,bbutils,simplehtmltreeparser,vlmaps,commoninterface;
type
TCustomAccountAccess=class;
TCustomAccountAccessClass=class of TCustomAccountAccess;
{ TLibrary }
TLibrary=class(TLibraryDetails)
protected
function readProperty(tagName: string; properties: TProperties):TParsingResult;
procedure addVariable(n, v: string);
public
template:TMultiPageTemplate;
canModifySingleBooks:boolean;
//function getPrettyNameShort():string;virtual;
deprecatedId: string;
maxRenewCount: integer;
procedure loadFromFile(fileName:string);
procedure loadFromString(data, fileName:string); //fileName is used for id
function getAccountObject():TCustomAccountAccess;virtual;
constructor create;
destructor destroy;override;
function location: string;
function state: string;
function country: string;
function prettyLocation: string;
function prettyState: string;
function prettyCountry: string;
function prettyCountryState: string;
function prettyNameWithComment: string; inline;
function homepageUrl: string;
function catalogUrl: string;
class function pretty(const l: string): string;
class function unpretty(const l: string): string;
end;
TLibraryManager = class;
TLibraryMetaDataEnumerator = object
private
i: integer;
manager: TLibraryManager;
public
prettyCountryState, prettyLocation: string;
newCountryState, newLocation: boolean;
libraryId: string;
function MoveNext: boolean;
end;
TLibraryIdStringList = class(TMapStringOwningObject)
function DoCompareText(const s1, s2: string): PtrInt; override;
end;
TLibraryManager=class
private
function getCount: integer;
function getLibraryFromIndex(i: integer): TLibrary;
function getLibraryIdFromIndex(i: integer): string;
protected
basePath: string;
flibraries: TList;
flibraryIds: TLibraryIdStringList;
function getAccountObject(libID: string):TCustomAccountAccess;
public
templates:TStringList;
constructor create();
destructor destroy();override;
procedure init(apath:string);
function getTemplate(templateName: string):TMultiPageTemplate;
function getCombinedTemplate(template: TMultiPageTemplate; templateName: string):TMultiPageTemplate;
function getAccount(libID,accountID: string):TCustomAccountAccess;overload; //+-encoded library name, verbatim user number
function getAccount(mixID: string):TCustomAccountAccess;overload; //mixId: +-Encoded library name # +2-encoded user number
function enumerateLibraryMetaData: TLibraryMetaDataEnumerator;
procedure enumerateFilesInDir(const dir: string; s: TStrings);
procedure enumerateBuiltInTemplates(s: TStrings);
procedure enumerateUserTemplates(s: TStrings);
function get(id: string): TLibrary;
function getUserLibraries(): TList;
function setUserLibrary(trueid, data: string): TLibrary;
function downloadAndInstallUserLibrary(url: string): TLibrary;
procedure deleteUserLibrary(trueid: string);
procedure reloadLibrary(trueid: string);
procedure reloadLibrary(lib: TLibrary; data: string);
procedure reloadTemplate(templateId: string);
procedure reloadPendingTemplates(); //only call this synchronized thrugh updateThreadConfig.threadManagementSection
property libraries[i: integer]: TLibrary read getLibraryFromIndex; default;
property libraryIds[i: integer]: string read getLibraryIdFromIndex;
property count: integer read getCount;
private
pendingReplacementsOld, pendingReplacementsNew: array of TMultiPageTemplate;
procedure replaceTemplate(old, new: TMultiPageTemplate);
end;
TVariables=array of record
name,value:string;
end;
TBookListType=(bltInOldData,bltInCurrentFile,bltInCurrentDataUpdate);
TBookOutputType=(botAll,botCurrent,botOld,botCurrentUpdate);
{ TBookList }
{ TBookLists }
TBookLists=class
private
ownerLib:TCustomAccountAccess;
bookLists:array[TBookListType] of TBookList;
bookListOldFileName,bookListCurFileName: string;
bookListOldLoaded: boolean;
keepHistory: boolean;
function getBooksCurrentFile: TBookList;//inline;
function getBooksCurrentUpdate: TBookList;//inline;
function getBooksOld: TBookList;
procedure remove;
procedure save;
procedure updateSharedDates();
procedure needOldBookList;
public
nextLimit,nextNotExtendableLimit:longint;
//Call always from the MainThread
constructor create(const AOwnerLib:TCustomAccountAccess; const oldFile,curFile: string);
destructor destroy;override;
procedure mergePersistentToCurrentUpdate;
procedure completeUpdate(); //replaces currentFile with currentupdate and moves old books to old
property currentUpdate: TBookList read getBooksCurrentUpdate;
property current: TBookList read getBooksCurrentFile;
property old: TBookList read getBooksOld;
end;
EVidelibriException = class(Exception) end;
ELibraryException=class(EVidelibriException)
details:string;
constructor create;
constructor create(s:string;more_details:string='');
end;
EImportException = class(EVidelibriException) end;
TExtendType=(etAlways,etAllDepends,etSingleDepends,etNever);
{ TCustomAccountAccess }
//first start info
TCustomAccountAccess=class(TCustomBookOwner)
strict private
config: TSafeIniFile;
private
FFileLock: TRTLCriticalSection;
FEnabled: boolean;
FlastHistoryBackup: integer;
FTimeout: qword;
function GetConnected: boolean;
function GetUpdated: boolean;
procedure SetAccountType(AValue: integer);
procedure setPassword(AValue: string);
procedure getAllBaseConfig(sl: TStringList);
procedure setBaseConfigValue(const name, value: string);
protected
fbooks: TBookLists;
lib: TLibrary;
internet: TInternetAccess;
path,user,pass:string;
FExtendType: TExtendType;
FExtendDays,FLastCheckDate:integer;
FAccountType: integer;
FKeepHistory, FConnected, FUpdated: boolean;
FConnectingTime, FUpdateTime: qword;
FCharges:Currency;
procedure updateConnectingTimeout;
function getCharges:currency;virtual;
function GetNeedSingleBookUpdate: boolean; virtual;
procedure initFromConfig;
public
// nextLimit,nextNotExtendableLimit:longint;
thread: TThread;
broken: longint; //Iff equal currentDate, disable auto checking (only accessed by thread/thread-creator)
lock: TRTLCriticalSection;
expiration: string;
constructor create(alib: TLibrary);virtual;
destructor destroy;override;
procedure init(apath,userID:string);virtual;
procedure saveConfig();
procedure saveBooks();
procedure remove(); //DELETE the account
//==============Access functions================
//At first connect must be called
procedure connect(AInternet:TInternetAccess); virtual;abstract;
procedure disconnect(); virtual;
procedure resetConnection;
procedure updateAll(); virtual;
procedure updateSingle(book: TBook);virtual;
procedure updateAllSingly; virtual;
procedure extendAll(); virtual;
procedure extendList(bookList:TBookList); virtual;
//procedure orderSingle(book: TBook); virtual;
//procedure orderList(booklist: TBookList); virtual;
procedure cancelSingle(book: TBook); virtual;
procedure cancelList(booklist: TBookList); virtual;
function shouldExtendBook(book: TBook):boolean;
function existsCertainBookToExtend: boolean;
function needChecking: boolean;
function getLibrary():TLibrary;
procedure changeUser(const s:string); virtual;
function getUser(): string;virtual;
function getPlusEncodedID():string; virtual;
property charges: currency read getCharges; //<0 means unknown
function getDebugStackTrace: TStringArray; virtual;
property books: TBookLists read fbooks;
property passWord: string read pass write setPassword;
property lastCheckDate: integer read FLastCheckDate;
property extendDays: integer read FExtendDays write FExtendDays;
property extendType: TExtendType read FExtendType write FExtendType;
property keepHistory: boolean read FKeepHistory write FKeepHistory;
property lastHistoryBackup: integer read FLastHistoryBackup write FLastHistoryBackup;
property enabled: boolean read FEnabled write FEnabled;
property connected: boolean read GetConnected;
property updated: boolean read GetUpdated;
property timeout: qword read FTimeout write FTimeout;
property accountType: integer read FAccountType write SetAccountType;
property needSingleBookUpdate: boolean read GetNeedSingleBookUpdate;
end;
{ TTemplateAccountAccess }
TTemplateAccountAccess = class(TCustomAccountAccess)
protected
reader:TBookListReader;
function GetNeedSingleBookUpdate: boolean; override;
procedure parserVariableRead(variable: string; value: String);
//procedure selectBook(variable,value: string); not needed
procedure setVariables();
public
procedure setVariables(parser: THtmlTemplateParser);
constructor create(alib: TLibrary);override;
procedure resetlib();
procedure init(apath,userID:string);override;
destructor destroy;override;
procedure changeUser(const s:string); override;
//==============Access functions================
procedure connect(AInternet:TInternetAccess); override;
procedure disconnect(); override;
procedure updateAll;override;
procedure updateSingle(book: TBook);override;
procedure updateAllSingly; override;
procedure extendAll;override;
procedure extendList(booksToExtend: TBookList);override;
// procedure orderList(booklist: TBookList); override;
procedure cancelList(booklist: TBookList); override;
function getDebugStackTrace: TStringArray; override;
end;
TImportExportFlags = set of TImportExportFlag;
TImportExportFlagsArray = array of TImportExportFlags;
procedure exportAccounts(const fn: string; accounts: array of TCustomAccountAccess; flags: array of TImportExportFlags );
procedure importAccountsPrepare(const fn: string; out parser: TTreeParser; out accounts: TStringArray; out flags: TImportExportFlagsArray);
//frees the parser
procedure importAccounts(parser: TTreeParser; impAccounts: TStringArray; flags: TImportExportFlagsArray);
type TPatternMatchExceptionAnonymizer = class
inIncludeOverrideElement: integer;
function nodeToString(node: TTreeNode): string;
end;
resourcestring
rsCustomLibrary = 'selbst definierte';
rsAllLibraries = 'alle';
rsInvalidImportFile = 'Die Import-Datei ist ungültig. Nur mit "Export" erstellte Dateien können zum Import geladen werden.';
implementation
uses applicationconfig,bbdebugtools,xquery, xquery.internals.common,androidutils,simpleinternet,mockinternetaccess,libraryAccess,strutils,math,xquery.internals.lclexcerpt,bbutilsbeta;
resourcestring
rsNoTemplateLinkFound = 'Der Link verweist auf kein VideLibri-Template (es gibt kein Element < link rel="videlibri.description" auf der Seite)';
function currencyStrToCurrency(s:string):Currency;
begin
s:=trim(s);
if s='' then exit(0);
if '.'<>DecimalSeparator then
s:=StringReplace(s,'.',DecimalSeparator,[]);
if ','<>DecimalSeparator then
s:=StringReplace(s,',',DecimalSeparator,[]);
result:=StrToCurr(s);
{ temp:=trim(Utf8ToAnsi(pcharToString(text,textLen)));
lastBookCharges:=strtoint(temp[length(temp-1])*10+temp[length(temp]))/100;
delete(temp,length(temp)-2,3);
lastBookCharges:=strtoint(lastBookCharges);}
end;
function decodeSafeFileName(s: string): string;
var
i: Integer;
begin
if pos('+', s) = 0 then exit(s);
result := '';
i := 1;
while i <= length(s) do begin
if (s[i] = '+') and (i + 2 <= length(s)) then begin
result += chr(strtoint('$'+copy(s,i+1,2)));
i += 2;
end else result += s[i];
i += 1;
end;
end;
function encodeToSafeFileName(s: string): string;
const OK_SET = ['a'..'z','A'..'Z','_','-','0'..'9'];
var
i: Integer;
ok: Boolean;
begin
ok := true;
for i := 1 to length(s) do
if not (s[i] in OK_SET) then begin
ok := false;
break;
end;
if ok then exit(s);
result := '';
for i := 1 to length(s) do
if s[i] in OK_SET then result += s[i]
else result += '+' + IntToHex(ord(s[i]), 2);
end;
procedure exportAccounts(const fn: string; accounts: array of TCustomAccountAccess; flags: array of TImportExportFlags);
var
f: TFileStream;
tempsl: TStringList;
i: Integer;
j: Integer;
procedure wln(const s: string);
var
le: String;
begin
if s = '' then exit;
f.WriteBuffer(s[1], length(s));
le := LineEnding;
f.WriteBuffer(le[1], length(le));
end;
procedure dumpBooks(const bookFile, mode: string);
var
books: RawByteString;
startpos: LongInt;
endpos: LongInt;
begin
EnterCriticalSection(updateThreadConfig.libraryAccessSection);
try
if FileExists(bookFile) then
books := strLoadFromFileUTF8(bookFile);
startpos := strIndexOf(books, '<books');
if startpos > 0 then begin
startpos := strIndexOf(books, '>', startpos) + 1;
endpos := strRpos('<', books); //exclusive
if endpos > startpos then begin
wln(' <books mode="'+xmlStrEscape(mode)+'">');
f.WriteBuffer(books[startpos], endpos - startpos);
wln(' </books>');
end;
end;
finally
LeaveCriticalSection(updateThreadConfig.libraryAccessSection);
end;
end;
begin
if ExtractFileDir(fn) <> '' then ForceDirectories(ExtractFileDir(fn));
f:=TFileStream.Create(fn,fmOpenWrite or fmCreate);
tempsl := TStringList.Create;
tempsl.DelimitedText := '=';
tempsl.StrictDelimiter := true;
try
wln('<?xml version="1.0" encoding="UTF-8"?>');
wln('<videlibri-dump>');
for i := 0 to high(accounts) do with accounts[i] do begin
wln(' <account name="'+xmlStrEscape(prettyName, true)+'" '+IfThen(eifConfig in flags[i],'id="'+xmlStrEscape(accounts[i].getPlusEncodedID(), true)+'"','')+'>');
if eifConfig in flags[i] then begin
wln(' <config><base>');
getAllBaseConfig(tempsl);
for j := 0 to tempsl.count - 1 do
if (eifPassword in flags[i]) or (tempsl.Names[j] <> 'pass') then
wln(' <v n="'+xmlStrEscape(tempsl.Names[j], true)+'">'+xmlStrEscape(tempsl.ValueFromIndex[j])+'</v>');
wln(' </base></config>');
end;
if eifCurrent in flags[i] then dumpBooks(books.bookListCurFileName + '.xml', 'current');
if eifHistory in flags[i] then dumpBooks(books.bookListOldFileName + '.xml', 'history');
wln(' </account>');
end;
wln('</videlibri-dump>');
finally
f.Free;
end;
end;
procedure importAccountsPrepare(const fn: string; out parser: TTreeParser; out accounts: TStringArray; out
flags: TImportExportFlagsArray);
var
xq: TXQueryEngine;
xv: IXQValue;
tempv: xquery.IXQValue;
i: Integer;
hasConfig: IXQuery;
hasPass: IXQuery;
hasCurrent: IXQuery;
hasHistory: IXQuery;
node: TTreeNode;
begin
parser := TTreeParser.Create;
try
parser.parseTreeFromFile(fn);
xq := TXQueryEngine.create;
try
tempv := xq.evaluateXPath('/videlibri-dump/account', parser.getLastTree);
hasConfig := xq.parseQuery('./config/base');
hasPass := xq.parseQuery('./config/base/v[@n="pass"]');
hasCurrent := xq.parseQuery('./books[@mode="current"]');
hasHistory := xq.parseQuery('./books[@mode="history"]');
accounts := nil;
SetLength(accounts, tempv.Count);
flags := nil;
SetLength(flags, tempv.Count);
for i := 0 to high(accounts) do begin
xv := tempv.get(i+1);
node := xv.toNode;
accounts[i] := node.getAttribute('name');
flags[i] := [];
if hasConfig.evaluate(node).toBooleanEffective then Include(flags[i], eifConfig);
if hasCurrent.evaluate(node).toBooleanEffective then Include(flags[i], eifCurrent);
if hasHistory.evaluate(node).toBooleanEffective then Include(flags[i], eifHistory);
if hasPass.evaluate(node).toBooleanEffective then Include(flags[i], eifPassword);
end;
finally
xq.free;
end;
except
on e: Exception do begin
parser.free;
parser := nil;
if e is ETreeParseException then e.Message := rsInvalidImportFile + ': '+LineEnding+e.Message;
raise;
end;
end;
end;
procedure importAccounts(parser: TTreeParser; impAccounts: TStringArray; flags: TImportExportFlagsArray);
var getHistory, getCurrent: IXQuery;
procedure importBooklist(parent: TTreeNode; list: TBookList; current: boolean);
var xbook: IXQValue;
book: TBook;
node: TTreeNode;
fbook: TBook;
data: xquery.IXQValue;
begin
if current then data := getCurrent.evaluate(parent)
else data := getHistory.evaluate(parent);
for xbook in data do begin
book := TBook.create;
node := xbook.toNode.getFirstChild();
while node <> nil do begin
if (node.typ = tetOpen) and (node.value = 'v') then
book.setProperty(node.getAttribute('n'), node.deepNodeText());
node := node.getNextSibling();
end;
fbook := list.findBook(book);
if fbook = nil then list.add(book)
else begin
fbook.assignIfNewer(book);
book.free;
end;
end;
end;
var realAccounts: array of TCustomAccountAccess = nil;
accountNodes: array of TTreeNode = nil;
i, j: Integer;
xq: TXQueryEngine;
getAccoutNode: IXQuery;
id: String;
getConfig: IXQuery;
config: TTreeNode;
xv: IXQValue;
name: String;
begin
xq := TXQueryEngine.create;
try
SetLength(realAccounts, length(impAccounts));
SetLength(accountNodes, length(impAccounts));
xq.VariableChangelog.Clear; xq.VariableChangelog.add('name', '');
getAccoutNode := xq.parseQuery('/videlibri-dump/account[@name=$name]');
getConfig := xq.parseQuery('./config/base/v');
getCurrent := xq.parseQuery('./books[@mode="current"]/book');
getHistory := xq.parseQuery('./books[@mode="history"]/book');
for i := 0 to high(impAccounts) do begin
if flags[i] = [] then continue;
xq.VariableChangelog.Clear; xq.VariableChangelog.add('name', impAccounts[i]);
accountNodes[i] := getAccoutNode.evaluate(parser.getLastTree).toNode;
if accountNodes[i] = nil then raise EImportException.Create('Could not find account: '+impAccounts[i]+' in import file');
id := accountNodes[i].getAttribute('id');
if id <> '' then
for j := 0 to accounts.Count - 1 do
if accounts[j].getPlusEncodedID() = id then begin
realAccounts[i] := accounts[j];
break;
end;
if realAccounts[i] = nil then
for j := 0 to accounts.Count - 1 do
if accounts[j].prettyName = impAccounts[i] then begin
realAccounts[i] := accounts[j];
break;
end;
if (realAccounts[i] <> nil) and (realAccounts[i].thread <> nil) then
raise EImportException.Create('Cannot import account ' + impAccounts[i] + ': It is busy talking with the library server.');
end;
for i := 0 to high(impAccounts) do begin
if flags[i] = [] then continue;
if (realAccounts[i] = nil) then
if (accountNodes[i].getAttribute('id') = '') then
raise EImportException.Create('Cannot import account: '+impAccounts[i]+LineEnding+'Account is currently not registered, and import files contains no configuration data.')
else if not (eifConfig in flags[i]) then
raise EImportException.Create('Cannot import account: '+impAccounts[i]+LineEnding+'Account is currently not registered, and you disabled configuration import.')
end;
for i := 0 to high(impAccounts) do
if (flags[i] <> []) and (realAccounts[i] = nil) then begin
realAccounts[i] := libraryManager.getAccount((accountNodes[i].getAttribute('id')));
realAccounts[i].prettyName := impAccounts[i];
accounts.add(realAccounts[i]);
end;
for i := 0 to high(impAccounts) do begin
if flags[i] = [] then continue;
if eifConfig in flags[i] then begin
for xv in getConfig.evaluate(accountNodes[i]) do begin
config := xv.toNode;
name := config.getAttribute('n');
if (name <> 'pass') or (eifPassword in flags[i]) then
realAccounts[i].setBaseConfigValue(name, config.deepNodeText());
end;
realAccounts[i].initFromConfig;
realAccounts[i].saveConfig();
end;
if eifHistory in flags[i] then importBookList(accountNodes[i], realAccounts[i].books.old, false);
if eifCurrent in flags[i] then begin
with realAccounts[i].books do begin
importBookList(accountNodes[i], currentUpdate, true);
//remove current books that are in old. Thus preventing duplicates in old when current is updated
//todo: better check the imported old than our old
current.removeAllFrom(currentUpdate);
for j := current.Count - 1 downto 0 do
if old.findBook(current[j]) <> nil then
current.delete(j);
current.addList(currentUpdate);
currentUpdate.clear;
end;
end;
realAccounts[i].books.updateSharedDates();
realAccounts[i].saveBooks();
end;
parser.free;
finally
xq.free;
end;
end;
function TLibraryIdStringList.DoCompareText(const s1, s2: string): PtrInt;
var
l1, l2: SizeInt;
cond1, cond2: Boolean;
p1, p2, e1, e2: PChar;
c1, c2: char;
begin
//try
cond1 := s1 = '';
cond2 := s2 = '';
if cond1 <> cond2 then begin
if cond1 then exit(-1);
if cond2 then exit(1);
end else if cond1 then exit(0);
p1 := pchar(pointer(s1));
p2 := pchar(pointer(s2));
l1 := length(s1);
l2 := length(s2);
e1 := p1 + l1;
e2 := p2 + l2;
cond1 := (p1^ = '-') or (p1^ = '_');
cond2 := (p2^ = '-') or (p2^ = '_');
if cond1 <> cond2 then begin
if cond1 then exit(-1);
if cond2 then exit(1);
end;
//sort current country before other countries
cond1 := strBeginsWith(s1, localeCountry);
cond2 := strBeginsWith(s2, localeCountry);
if cond1 <> cond2 then begin
if cond1 then exit(-1);
if cond2 then exit(1);
end;
while (p1 < e1) and (p2 < e2) do begin
c1 := p1^;
c2 := p2^;
if c1 <> c2 then begin
if (c1 = '+') and (p1+1 < e1) then begin
c1 := (p1+1)^;
inc(p1, 2);
end;
if (c2 = '+') and (p2+1 < e2) then begin
c2 := (p2+1)^;
inc(p2, 2);
end;
result := ord(upCase(c1)) - ord(upCase(c2));
if result <> 0 then exit;
end;
inc(p1);
inc(p2);
end;
result := l1 - l2;
{ finally
write(stderr, 'Compared ', s1);
if result < 0 then write(' < ')
else if result > 0 then write(' > ')
else write(' = ');
writeln(s2, ': ', result);
end;}
end;
function TLibraryMetaDataEnumerator.MoveNext: boolean;
var
exploded: TStringArray;
newPrettyCountryState, newPrettyLocation: String;
begin
i += 1;
if i >= manager.count then exit(false);
libraryId := manager.flibraryIds[i];
exploded := strSplit(libraryId, '_');
newPrettyCountryState := TLibrary.pretty(exploded[0]) + ' - ' + TLibrary.pretty(exploded[1]);
newPrettyLocation := TLibrary.pretty(exploded[2]);
newCountryState := (i = 0) or (newPrettyCountryState <> prettyCountryState);
newLocation := (i = 0) or (newPrettyLocation <> prettyLocation);
if newCountryState then prettyCountryState := newPrettyCountryState;
if newLocation then prettyLocation := newPrettyLocation;
result := true;
end;
function TLibrary.readProperty(tagName: string; properties: TProperties):TParsingResult;
var value:string;
function parseTesting: TLibraryTestingInfo;
begin
case value of
'yes': result := tiYes;
'no': result := tiNo;
//'unknown': result := tiYes;
'broken': result := tiBroken;
else result := tiUnknown;
end;
end;
begin
tagName:=LowerCase(tagName);
value:=getProperty('value',properties);
if tagName='homepage' then fhomepageUrl:=value
else if tagName='catalogue' then fcatalogueUrl:=value
else if tagName='longname' then prettyName:=value
else if tagName='shortname' then prettyNameShort:=value
else if tagName='template' then begin
template:=libraryManager.getCombinedTemplate(template, value);
if template <> nil then templateId := template.name;
end
else if tagName='variable' then addVariable(getProperty('name',properties), value)
else if tagName='maxrenewcount' then maxRenewCount:=StrToInt(value)
else if tagName='deprecatedname' then deprecatedId:=value
else if tagName='table-comment' then tableComment:=value
else if tagName='account-comment' then accountComment:=value
else if tagName='segregated-accounts' then segregatedAccounts:=StrToBool(value)
else if tagName='testing-search' then testingSearch:=parseTesting
else if tagName='testing-account' then testingAccount:=parseTesting
;
Result:=prContinue;
end;
procedure TLibrary.addVariable(n, v: string);
begin
SetLength(variables, length(variables) + 1);
variables[high(variables)] := TLibraryVariable.Create;
variables[high(variables)].name := n;
variables[high(variables)].value := v;
end;
procedure TLibrary.loadFromFile(fileName: string);
begin
loadFromString(strLoadFromFileUTF8(fileName), '');
end;
procedure TLibrary.loadFromString(data, fileName: string);
begin
id:=ChangeFileExt(ExtractFileName(fileName),'');
maxRenewCount:=-1;
testingAccount := tiUnknown;
testingSearch := tiUnknown;
parseXML(data,@readProperty,nil,nil,CP_UTF8);
if template<>nil then begin
canModifySingleBooks:=(template.findAction('renew-single')<>nil) or
(template.findAction('renew-list')<>nil) ;
end;
if prettyNameShort = '' then
prettyNameShort:=strCopyFrom(id, strRpos('_', id)+1) + ' '+ prettyLocation;
if id.StartsWith('_') or id.StartsWith('-_') then
exit; //do not show testing information for user-defined libraries. But here we do not know if it is a user-defined library. But the default id starts with -_-_-_
if (testingSearch = tiBroken) and (testingAccount = tiBroken) then begin
if tableComment = '' then tableComment := 'Da die Bibliothek ihren Webkatalog geändert hat, funktioniert es nicht mehr';
prettyName += ' (kaputt)';
end else if (testingSearch = tiYes) and (testingAccount in [tiBroken, tiNo]) then prettyName += ' (nur Suche)'
else if (testingSearch = tiYes) and (testingAccount = tiUnknown) then prettyName += ' (nur Suche getestet)'
else if (testingSearch in [tiBroken, tiNo]) and (testingAccount = tiYes) then prettyName += ' (nur Konto)'
else if (testingSearch = tiUnknown) and (testingAccount = tiUnknown) then prettyName += ' (nicht getestet)'
else if (testingSearch in [tiBroken, tiNo]) and (testingAccount = tiUnknown) then prettyName += ' (keine Suche, nicht getestet)'
end;
//==============================================================================
// TLibrary (+Manager)
//==============================================================================
function TLibrary.getAccountObject():TCustomAccountAccess;
begin
result:=TTemplateAccountAccess.create(self);
end;
constructor TLibrary.create;
begin
end;
destructor TLibrary.destroy;
begin
inherited destroy;
end;
type TInternetAccessNonSense = TMockInternetAccess;
function TLibrary.catalogUrl: string;
var
parser: TMultipageTemplateReader;
tempinternet: TInternetAccess;
vpair: TLibraryVariable;
begin
if (fcatalogueUrl = '') and (fcatalogueUrlFromTemplate = '') and (template.findAction('catalogue') <> nil) then begin
tempinternet := TInternetAccessNonSense.create(); //will crash if used
parser := TMultipageTemplateReader.create(template,tempinternet, nil);
parser.parser.KeepPreviousVariables:=kpvKeepValues; //used in book list reader. needed here, too?
for vpair in variables do
parser.parser.variableChangeLog.ValuesString[vpair.name]:=vpair.value;
parser.callAction('catalogue');
fcatalogueUrlFromTemplate:=parser.parser.variableChangeLog['url'].toString;
parser.free;
tempinternet.free;
end;
result := fcatalogueUrl;
if result = '' then result := fcatalogueUrlFromTemplate;
if result = '' then result := fhomepageUrl;
end;
function TLibrary.location: string;
begin
result := strSplit(id, '_')[2];
end;
function TLibrary.state: string;
begin
result := strSplit(id, '_')[1];
end;
function TLibrary.country: string;
begin
result := strSplit(id, '_')[0];
end;
function TLibrary.prettyLocation: string;
begin
Result := pretty(location);
end;
function TLibrary.prettyState: string;
begin
result := pretty(state);
end;
function TLibrary.prettyCountry: string;
begin
result := pretty(country);
end;
function TLibrary.prettyCountryState: string;
begin
result := prettycountry + ' - ' + prettyState;
end;
function TLibrary.prettyNameWithComment: string;
begin
if tableComment = '' then exit(prettyName);
result := prettyName + LineEnding + tableComment;
end;
function TLibrary.homepageUrl: string;
begin
result := fhomepageUrl;
if result = '' then result := catalogUrl;
end;
class function TLibrary.pretty(const l: string): string;
begin
Result := l;
if pos('+', result) = 0 then exit;
result := StringReplace(Result, '+ue', 'ü', [rfReplaceAll]);
result := StringReplace(Result, '+oe', 'ö', [rfReplaceAll]);
result := StringReplace(Result, '+ae', 'ä', [rfReplaceAll]);
result := StringReplace(Result, '+sz', 'ß', [rfReplaceAll]);
result := StringReplace(Result, '++', ' ', [rfReplaceAll]);
//also Bridge.LibraryDetails.decodeIdEscapes
end;
class function TLibrary.unpretty(const l: string): string;
begin
Result := l;
result := StringReplace(Result, 'ü', '+ue', [rfReplaceAll]);
result := StringReplace(Result, 'ö', '+oe', [rfReplaceAll]);
result := StringReplace(Result, 'ä', '+ae', [rfReplaceAll]);
result := StringReplace(Result, 'ß', '+sz', [rfReplaceAll]);
result := StringReplace(Result, ' ', '++', [rfReplaceAll]);
//also in maketable
end;
function TLibraryManager.getCount: integer;
begin
result := flibraryIds.Count;
end;
function TLibraryManager.getLibraryFromIndex(i: integer): TLibrary;
begin
if flibraryIds.Objects[i] <> nil then
exit(TLibrary(flibraryIds.Objects[i]));
result := get(flibraryIds[i]);
end;
function TLibraryManager.getLibraryIdFromIndex(i: integer): string;
begin
result := flibraryIds[i];
end;
function TLibraryManager.getAccountObject(libID: string):TCustomAccountAccess;
var lib: TLibrary;
begin
Result:=nil;
lib := get(libID);
if lib = nil then lib := libraries[0]; //exception will crash since nothing is initialized yet
result := lib.getAccountObject();
end;
constructor TLibraryManager.create();
begin
flibraries:=Tlist.create;
templates:=tStringList.Create;
flibraryIds := TLibraryIdStringList.Create;
flibraryIds.CaseSensitive := true;
flibraryIds.Sorted := true;
flibraryIds.Duplicates := dupIgnore;
end;
destructor TLibraryManager.destroy();
var i:integer;
begin
for i:=0 to flibraries.Count-1 do
libraries[i].free;
flibraries.free;
for i:=0 to templates.Count-1 do
TMultiPageTemplate(templates.Objects[i]).free;
templates.free;
flibraryIds.Free;
inherited;
end;
procedure TLibraryManager.init(apath: string);
var i:longint;
userlibs: TStringArray;
begin
basePath:=apath;
flibraryIds.Sorted := false;
flibraryIds.text := assetFileAsString('libraries/libraries.list');
for i:=flibraryIds.Count-1 downto 0 do
if flibraryIds[i] = '' then
flibraryIds.Delete(i);
flibraryIds.Sort;
if logging then
for i := 1 to flibraryIds.Count - 1 do
if flibraryIds.DoCompareText(flibraryIds[i-1], flibraryIds[i]) > 0 then
log('Unsorted libraries: '+flibraryIds[i-1] + ' > ' + flibraryIds[i]);
flibraryIds.Sorted := true;
userlibs := strSplit(userConfig.ReadString('base', 'user-libraries', ''), ',');
for i := 0 to high(userlibs) do begin
userlibs[i] := trim(userlibs[i]);
if userlibs[i] = '' then continue;
flibraryIds.Add(userlibs[i]);
end;
end;
function TLibraryManager.getTemplate(templateName: string): TMultiPageTemplate;
var i:longint;
begin
i:=templates.IndexOf(templateName);
if i>=0 then Result:=TMultiPageTemplate(templates.Objects[i])
else begin
Result:=TMultiPageTemplate.Create();
try
result.loadTemplateWithCallback(@assetFileAsString, 'libraries/templates'+DirectorySeparator+templateName+DirectorySeparator,templateName, localeLanguage);
except
result.free;
raise
end;
templates.AddObject(templateName,Result);
end;
end;
function TLibraryManager.getCombinedTemplate(template: TMultiPageTemplate; templateName: string): TMultiPageTemplate;
var i:longint;
child: TMultiPageTemplate;
begin
if template = nil then exit(getTemplate(templateName));
i:=templates.IndexOf(template.name + '|' + templateName);
if i>=0 then Result:=TMultiPageTemplate(templates.Objects[i])
else begin
result := template.clone;
Result.name:=Result.name+'|'+templateName;
child := getTemplate(templateName);
for i := 0 to high(child.baseActions.children) do begin
setlength(Result.baseActions.children, length(Result.baseActions.children) + 1);
Result.baseActions.children[high(Result.baseActions.children)] := child.baseActions.children[i].clone;
end;
templates.AddObject(result.name,Result);
end;
end;