-
Notifications
You must be signed in to change notification settings - Fork 5
/
booklistreader.pas
executable file
·1602 lines (1423 loc) · 54.2 KB
/
booklistreader.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 booklistreader;
{$I videlibrilanguageconfig.inc}
interface
uses
Classes, SysUtils,bbutils,extendedhtmlparser,simplehtmltreeparser,simplexmlparser, xquery, internetaccess, multipagetemplate, xquery__regex, commoninterface;
type
TBookList = class;
trilean = (tUnknown, tFalse, tTrue);
{ TBook }
TSerializeStringProperty = procedure (const name: string; const value: string) of object;
TSerializeDateProperty = procedure (const name: string; date: integer) of object;
TCustomBookOwner = class
//todo: move TCustomAccountAccess in the same unit as TBook (probably move both in a new unit)
//till moved, use this class as place holder type
protected
FPrettyName: string;
public
property prettyName: string read FPrettyName write FPrettyName;
end;
TBook=class
private
function GetOwningAccount: TCustomBookOwner;
procedure SetOwningAccount(AValue: TCustomBookOwner);
protected
_referenceCount: longint;
owner: TObject; //account
public
procedure decReference;
procedure incReference;
public
//protected
//persistent
id,author,title,year:string; //schlüssel
libraryBranch, libraryLocation: string; //branch of the library ("Filiale")
isbn: string;
category,statusStr{,otherInfo}: string;
issueDate,dueDate:longint;
status: TBookStatus;
cancelable: trilean;
lend: boolean;
renewCount: integer;
//*how to add a new property: define it, update: assignNoReplace, clear, serialize, setProperty
// public
lastExistsDate,firstExistsDate:longint;
// list: TBookList;
//temporary
holdings: TBookList;
charges: currency;
additional: TProperties;
function owningBook: TBook;
property owningAccount: TCustomBookOwner read GetOwningAccount write SetOwningAccount;
constructor create;
function equalToKey(compareTo: TBook): boolean;overload;
function equalToKey(aid,aauthor,atitle,ayear:string):boolean;overload;
procedure serialize(str: TSerializeStringProperty; date: TSerializeDateProperty);
procedure clear;
destructor Destroy; override;
procedure assign(book: TBook); //assigns everything except key fields
procedure assignAll(book: TBook); //assigns everything
procedure assignIfNewer(book: TBook); //assigns from the newer book, also take min of issue/exist date
procedure mergePersistentFields(book: TBook);
function clone: TBook;
function getNormalizedISBN(const removeSeps: boolean; conversion: integer): string;
class function getNormalizedISBN(const aisbn: string; const removeSeps: boolean; conversion: integer): string;
class function getCoverURLs(const aisbn: string; maxWidth, maxHeight: integer): TStringArray;
function toSimpleString():string;
function toLimitString():string;
//procedure assignOverride(book: TBook); //every value set in book will be replace the one of self
procedure setProperty(const name, value: string);
function getProperty(const name: string; const def: string = ''): string;
function getPropertyAdditional(const name: string; const def: string = ''): string; inline;
end;
{ TBookList }
TBookList = class(TFPList)
private
flendList: boolean;
function getBook(i:longint):TBook; //inline;
procedure setLendList(const AValue: boolean);
public
owner: TObject;
constructor create(aowner: TObject=nil);
destructor Destroy; override;
procedure delete(i:longint);
function remove(book: tbook):longint; //pointer comparison, not key comparison
procedure clear;
procedure add(book: TBook);
function add(id,title,author,year: string):TBook;
procedure assign(alist: TBookList);
procedure addList(alist: TBookList);
procedure mergePersistentFields(const old: TBookList);
//procedure overrideOldInformation(const old: TBookList);
procedure removeAllFrom(booksToRemove: TBookList); //key comparison, not pointer
procedure removeAllExcept(booksToKeep: TBookList); //key comparison, not pointer
function removeBook(book: TBook):longint; //key comparison
function findBook(book:TBook):TBook; //key comparison (use indexOf for pointer comparison)
function findBookIndex(book:TBook):longint; //key comparison (use indexOf for pointer comparison)
function findBook(id,author,title,year:string):TBook;
procedure load(fileName: string);
procedure save(fileName: string);
function toXQuery: IXQValue;
function lastCheck: longint;
function nextLimitDate(const extendable: boolean = true): longint;
property books[i:longint]: TBook read getBook; default;
property lendList: boolean read flendList write setLendList;
end;
TPendingMessageKind = (pmkAlert, pmkConfirm, pmkChoose);
TPendingMessage = class
kind: TPendingMessageKind;
callback, caption: string;
options, optionValues: TStringArray;
end;
{ TBookListReader }
TBookListReader = class(TMultipageTemplateReader)
private
currentBook,defaultBook: TBook;
class procedure setAllBookProperties(book:TBook; const value:IXQValue); static;
class procedure setBookProperty(book:TBook;variable: string; const value:IXQValue); static;
procedure parserVariableRead(variable: string; book: IXQValue);
procedure logall(sender: TMultipageTemplateReader; logged: string; debugLevel: integer=0);
procedure TraceEvent(sender: TXQueryEngine; value, info: IXQValue);
protected
procedure applyPattern(pattern, name: string); override;
function evaluateQuery(const query: IXQuery): IXQValue; override;
procedure setVariable(name: string; value: IXQValue; namespace: string=''); override;
public
bookAccessSection: ^TRTLCriticalSection;
books: TBookList;
bookListHasBeenClearedAndMightNeedSingleUpdate: boolean;
pendingMessage: TPendingMessage;
cache: TXQBoxedStringMap;
accountExpiration: string;
constructor create(atemplate:TMultiPageTemplate);
destructor destroy();override;
class function bookToPXP(book:TBook): TXQBoxedStringMap; static;
procedure selectBook(book:TBook);
end;
{ TXQVideLibriStaticContext }
TXQVideLibriStaticContext = class(TXQStaticContext)
private
bookListReader: TBookListReader;
public
constructor Create(abookListReader: TBookListReader);
function clone: TXQStaticContext; override;
end;
const BOOK_NOT_EXTENDABLE=[bsProblematic];
BOOK_EXTENDABLE=[bsNormal];
BOOK_CANCELABLE=[bsOrdered, bsReserved, bsProvided];
BOOK_NOT_LEND=BOOK_CANCELABLE;
function BookStatusToStr(book: TBook;verbose:boolean=false): string; //returns utf8
implementation
uses math, bbdebugtools, simplehtmlparser, applicationconfig, xquery_json//<- enable JSON
, xquery.namespaces, xquery.internals.common
;
resourcestring
rsBookStatusInvalid = 'Ungültiger Bücherstatus: %s';
rsBookStatusAvailable = 'verfügbar';
rsBookStatusLend = 'ausgeliehen';
rsBookStatusVirtual = 'E-Book/sonstiges';
rsBookStatusPresentation = 'Präsenzbestand';
rsBookStatusInterloan = 'fernleihbar';
const XMLNamespaceURL_VideLibri = 'http://www.videlibri.de';
var XMlNamespaceVideLibri, XMlNamespaceVideLibri_VL: TNamespace;
type TVideLibriHtmlPatternMatcher = class(THtmlTemplateParser)
protected
procedure raiseMatchingException(message: string); override;
end;
function BookStatusToStr(book: TBook;verbose:boolean=false): string;
begin
if book.lend then begin
case book.Status of
bsUnknown: if verbose then exit(rsBookStatusNormalRenewable) else exit('');
// bsUnknown: exit('Ausleihstatus unbekannt');
// bsIsSearchedDONTUSETHIS: exit('Ausleihstatus wird ermittelt... (sollte nicht vorkommen, bitte melden!)');
// bsEarMarked:exit('vorgemerkt');
// bsMaxLimitReached: exit('maximale Ausleihfrist erreicht');
// bsAccountExpired: exit('Büchereikarte ist abgelaufen');
bsNormal: if verbose then exit(rsRenewable + ': '+book.statusStr) else exit(book.statusStr);
bsProblematic: if verbose then exit(rsBookStatusNonRenewable + ': '+book.statusStr) else exit(book.statusStr);
bsOrdered: if book.statusStr <> '' then exit(book.statusStr) else exit(rsBookStatusOrdered);
bsProvided: if book.statusStr <> '' then exit(book.statusStr) else exit(rsBookStatusProvided);
bsReserved: if book.statusStr <> '' then exit(book.statusStr) else exit(rsBookStatusReserved);
bsAvailable, bsLend, bsVirtual, bsPresentation, bsInterLoan: exit(rsBookStatusNotLend)
else exit(format(rsBookStatusInvalid, [inttostr(ord(book.status))]));
end;
if verbose then exit(rsBookStatusNotLend) else exit('');
end else
case book.Status of
bsNormal, bsUnknown: exit(book.statusStr);
bsAvailable: exit(rsBookStatusAvailable);
bsLend: exit(rsBookStatusLend);
bsVirtual: exit(rsBookStatusVirtual);
bsPresentation: exit(rsBookStatusPresentation);
bsInterLoan: exit(rsBookStatusInterloan);
else exit('???????');
end;
end;
function BookStatusToSerializationStr(status: TBookStatus): string;
begin
case status of
bsNormal: exit('normal');
bsUnknown: exit('unknown');
bsProblematic: exit('critical');
bsOrdered: exit('ordered');
bsProvided: exit('provided');
bsReserved: exit('reserved');
bsAvailable: exit('available');
bsLend: exit('lend');
bsVirtual: exit('virtual');
bsPresentation: exit('presentation');
bsInterLoan: exit('interloan');
else exit('--invalid--'+inttostr(integer(status)));
end;
end;
procedure TVideLibriHtmlPatternMatcher.raiseMatchingException(message: string);
begin
raise EVideLibriHTMLMatchingException.create(message, self);
end;
{ TXQVideLibriStaticContext }
constructor TXQVideLibriStaticContext.Create(abookListReader: TBookListReader);
begin
bookListReader := abookListReader;
end;
function TXQVideLibriStaticContext.clone: TXQStaticContext;
begin
Result:=TXQVideLibriStaticContext.Create(bookListReader);
result.assign(self);
end;
{ TBook }
function TBook.GetOwningAccount: TCustomBookOwner;
var
b: TBook;
begin
b := owningBook;
if assigned(b.owner) and b.owner.InheritsFrom(TCustomBookOwner) then result := TCustomBookOwner(b.owner)
else result := nil;
end;
procedure TBook.SetOwningAccount(AValue: TCustomBookOwner);
var
b: TBook;
begin
b := owningBook;
if b.owner=AValue then Exit;
b.owner:=AValue;
end;
procedure TBook.decReference;
begin
_referenceCount-=1;
if _referenceCount<=0 then free;
end;
procedure TBook.incReference;
begin
_referenceCount+=1;
end;
function TBook.owningBook: TBook;
begin
result := self;
while (result.owner <> nil) and (result.owner.InheritsFrom(TBook)) do result := tbook(result.owner);
end;
constructor TBook.create;
begin
_referenceCount:=1;
status:=bsUnknown;
cancelable:=tUnknown;
renewCount := -1;
end;
function TBook.equalToKey(compareTo: TBook): boolean;
begin
result:=(id=compareTo.id) and (title=compareTo.title) and
(author=compareTo.author) and (year=compareTo.year);
end;
function TBook.equalToKey(aid, aauthor, atitle, ayear: string): boolean;
begin
result:=(id=aid) and (title=atitle) and
(author=aauthor) and (year=ayear);
end;
procedure TBook.serialize(str: TSerializeStringProperty; date: TSerializeDateProperty);
begin
if Assigned(str) then begin
str('id', id);
str('author', author);
str('title', title);
str('isbn', isbn);
str('year', year);
str('libraryBranch', libraryBranch);
str('libraryLocation', libraryLocation);
str('category', category);
str('status', statusStr);
//str('otherInfo', otherInfo);
str('statusId', BookStatusToSerializationStr(status));
if renewCount > 0 then str('renewCount', inttostr(renewCount));
case cancelable of
tUnknown: str('cancelable', '?');
tTrue: str('cancelable', 'true');
tFalse: str('cancelable', 'false');
end;
end;
if assigned(date) then begin
date('issueDate', issueDate);
date('dueDate', dueDate);
date('_lastExistsDate', lastExistsDate);
date('_firstExistsDate', firstExistsDate);
end;
//check with bookToJBook
end;
procedure TBook.clear;
begin
Id:='';
category:='';
Title:='';
Author:='';
year:='';
StatusStr:='';
libraryBranch := '';
libraryLocation := '';
isbn := '';
Status:=bsUnknown;
cancelable:=tUnknown;
dueDate:=0;
issueDate:=0;
renewCount:=0;
//lastExistsDate, firstExistsDate?
SetLength(Additional,0);
FreeAndNil(holdings);
end;
destructor TBook.Destroy;
var
i: Integer;
begin
if holdings <> nil then begin
//safety check
for i := 0 to holdings.Count - 1 do
if holdings[i].owner = self then holdings[i].owner := owner;
holdings.Free;
end;
inherited Destroy;
end;
procedure TBook.assign(book: TBook);
var
temp: TBook;
i: Integer;
begin
if (book=nil) or (book = self) then exit;
category:=book.category;
libraryBranch:=book.libraryBranch;
libraryLocation:=book.libraryLocation;
isbn:=book.isbn;
statusStr:=book.statusStr;
issueDate:=book.issueDate;
dueDate:=book.dueDate;
status:=book.status;
charges:=book.charges;
lastExistsDate:=book.lastExistsDate;
if (firstExistsDate=0) or ((book.firstExistsDate<>0) and (book.firstExistsDate<firstExistsDate)) then
firstExistsDate:=book.firstExistsDate;
cancelable:=book.cancelable;
renewCount := book.renewCount;
additional := book.additional;
SetLength(additional, length(additional));
if book.holdings <> nil then begin
if holdings = nil then holdings := TBookList.create(self);
holdings.clear;
holdings.Capacity:=book.holdings.Count;
for i := 0 to book.holdings.Count - 1 do begin
temp := book.holdings[i].clone;
holdings.add(temp);
temp.decReference;
end;
end;
end;
procedure TBook.assignAll(book: TBook);
begin
if (book=nil) or (book = self) or (self = nil) then exit;
assign(book);
author:=book.author;
title:=book.title;
year:=book.year;
id:=book.id;
end;
procedure TBook.assignIfNewer(book: TBook);
begin
if (book=nil) or (book = self) or (self = nil) then exit;
if (issueDate <> 0) and (book.issueDate <> 0) then issueDate:=min(issueDate, book.issueDate);
if (firstExistsDate <> 0) and (book.firstExistsDate <> 0) then firstExistsDate:=min(firstExistsDate, book.firstExistsDate);
if book.lastExistsDate > lastExistsDate then assign(book)
else if book.lastExistsDate = lastExistsDate then begin
dueDate:=max(dueDate, book.dueDate);
end;
end;
procedure TBook.mergePersistentFields(book: TBook);
begin
if (book=nil) or (book = self) or (self = nil) then exit;
if (firstExistsDate <> 0) and (book.firstExistsDate <> 0) then firstExistsDate:=min(firstExistsDate, book.firstExistsDate);
end;
function TBook.clone: TBook;
begin
result := TBook.create;
result.assignAll(self);
end;
function TBook.getNormalizedISBN(const removeSeps: boolean; conversion: integer): string;
begin
result := getNormalizedISBN(isbn, removeSeps, conversion);
end;
function extractISBN(const input: string; out digitCount: integer; out hasDashes: boolean): string;
var
i, len: Integer;
begin
result := trim(input);
for i := 1 to length(result) do
if result[i] in ['0'..'9'] then begin
delete(result, 1, i - 1);
break;
end;
digitCount := 0;
hasDashes := false;
len := 0;
for i := 1 to length(result) do begin
case result[i] of
'0'..'9','X': inc(digitCount);
'-': hasDashes := true;
' ': if hasDashes or (digitCount in [10,13]) then break;
else break;
end;
inc(len);
end;
delete(result, len + 1, length(result));
while (result <> '') and (result[length(result)] = '-') do delete(result, length(result), 1);
end;
class function TBook.getNormalizedISBN(const aisbn: string; const removeSeps: boolean; conversion: integer): string;
var
check: Integer;
multiplier: Integer;
i, pos, digitCount: Integer;
hasDashes: boolean;
begin
result := extractISBN(aisbn, digitCount, hasDashes);
if length(result) < 5 then exit;
if (digitCount <> 10) and (digitCount <> 13) then //try some recovery from invalid inputs.
if result[2] = '-' then digitCount := 10 //e.g. isbn10: 3-680-08783-7
else if result[4] in ['-', ' '] then digitCount := 13; //isbn13: 978-3-7657-2781-8
if digitCount <> conversion then begin //only calculate checkcode when converting the ISBN to prevent it from breaking valid ISBNs
//see https://en.wikipedia.org/wiki/List_of_ISBN_identifier_groups
//X can mean 0
if conversion = 13 then begin
if strBeginsWith(result, '1') and ( strBeginsWith(result, '10-') or strBeginsWith(result, '11-') or strBeginsWith(result, '12-') ) then
result := '979-' + result
else
result := '978-' + result;
check := 0;
multiplier := 1;
for i := 1 to length(result) - 1 do
if result[i] in ['0'..'9'] then begin
check += multiplier * (ord(result[i]) - ord('0'));
multiplier := (multiplier + 2) and 3;
end;
result[length(result)] := chr(ord('0') + (10 - check mod 10) mod 10);
end;
if conversion = 10 then begin
if result[4] = '-' then delete(result, 1, 4)
else delete(result, 1, 3);
i := 1;
check := 0;
for pos := 1 to length(result) do
if result[pos] in ['0'..'9'] then begin
if i = 10 then begin
check := check mod 11;
if check = 10 then result[pos] := 'X'
else result[pos] := chr(check + ord('0'));
break;
end;
check += (ord(result[pos]) - ord('0')) * i;
inc(i);
end;
end;
end;
if removeSeps then
Result := StringReplace(StringReplace(result, '-', '', [rfReplaceAll]), ' ', '', [rfReplaceAll]);
//no code to insert dashes since that needs complicated tables
end;
class function TBook.getCoverURLS(const aisbn: string; maxWidth, maxHeight: integer): TStringArray;
var
isbn10, isbn13: String;
size: Char;
begin
result := nil;
isbn10 := getNormalizedISBN(aisbn, true, 10);
//if logging then log('isbn10: '+isbn10);
isbn13 := getNormalizedISBN(aisbn, true, 13);
//if logging then log('isbn13: '+isbn13);
SetLength(result, 3);
if maxHeight > 150 then size := 'L' else size := 'M';
result[0] := 'https://images-eu.ssl-images-amazon.com/images/P/'+isbn10+'.03.'+size+'.jpg';
// result[1] := 'http://images-eu.amazon.com/images/P/'+isbn10+'.03.'+size+'.jpg';
if maxWidth > 180 then size := 'L' else size := 'M';
result[1] := 'http://covers.openlibrary.org/b/isbn/'+isbn10+'-'+size+'.jpg?default=false';
if maxWidth > 200 then size := 'l' else size := 'm';
result[2] := 'https://www.buchhandel.de/cover/'+isbn13+'/'+isbn13+'-cover-'+size+'.jpg';
//arrayAdd(images, 'http://vlb.de/GetBlob.aspx?strIsbn='+book.getNormalizedISBN(true, 13)+'&size=M');
end;
function TBook.toSimpleString():string;
begin
result:=id+' - '+author+' * '+ title;
end;
function TBook.toLimitString(): string;
begin
result:=toSimpleString() + ' => '+DateToPrettyStr(dueDate);
end;
procedure TBook.setProperty(const name, value: string);
begin
case lowercase(name) of
'category': Category:=value;
'id': Id:=value;
'author': Author:=value;
'title': Title:=value;
'year': Year:=value;
'librarybranch': libraryBranch := value;
'librarylocation': libraryLocation := value;
'isbn': isbn:=value;
'statusid':
case value of
'curious': status:=bsNormal;
'critical': status:=bsProblematic;
'ordered': status:=bsOrdered;
'provided': status:=bsProvided;
'reserved', 'requested': status:=bsReserved;
'normal': status:=bsNormal;
'unknown': status:=bsUnknown;
'available': status:=bsAvailable;
'lend': status:=bsLend;
'virtual': status:=bsVirtual;
'presentation': status:=bsPresentation;
'interloan': status:=bsInterLoan;
'history', '': status := bsUnknown; //these are invalid statuses (not occuring during serialization, however history is used by xquery offline search )
else begin
status := bsProblematic;
statusStr := Format(rsBookStatusInvalid, [value]);
end;
end;
'cancelable': if (value <> '') and (value <> '0') and not striEqual(value, 'false') and (value <> '?') then cancelable:=tTrue
else if value = '?' then cancelable:=tUnknown
else cancelable:=tFalse;
'status': statusStr := value;
'issuedate': issueDate:=bbutils.dateParse(value, 'yyyy-mm-dd');
'duedate': dueDate:=bbutils.dateParse(value, 'yyyy-mm-dd');
'_firstexistsdate': firstExistsDate:=bbutils.dateParse(value, 'yyyy-mm-dd');
'_lastexistsdate': lastExistsDate:=bbutils.dateParse(value, 'yyyy-mm-dd');
'renewcount': renewCount := StrToIntDef(value, -1);
else simplexmlparser.setProperty(name,value,additional);
end;
end;
function TBook.getProperty(const name: string; const def: string): string;
begin
case lowercase(name) of
'category': result:=Category;
'id': result:=Id;
'author': result:=Author;
'title': result:=Title;
'year': result:=Year;
'librarybranch': result:=libraryBranch;
'librarylocation': result:=libraryLocation;
'isbn': result:=isbn;
'statusid': result := BookStatusToSerializationStr(status);
'cancelable': case cancelable of
tUnknown: result := '?';
tFalse: result := 'false';
tTrue: result := 'true';
end;
'status': result := statusStr;
'issuedate': result := bbutils.dateTimeFormat('yyyy-mm-dd', issueDate);
'duedate': result := bbutils.dateTimeFormat('yyyy-mm-dd', dueDate);
'_firstexistsdate': result := bbutils.dateTimeFormat('yyyy-mm-dd', firstExistsDate);
'_lastexistsdate': result := bbutils.dateTimeFormat('yyyy-mm-dd', lastExistsDate);
'renewcount': result := inttostr(max(renewCount, 0));
else result := getPropertyAdditional(name, def);
end;
end;
function TBook.getPropertyAdditional(const name: string; const def: string): string;
begin
result := simplexmlparser.getProperty(name, additional, def);
end;
{
procedure TBook.assignOverride(book: TBook);
var i:longint;
begin
if book=nil then exit;
if book.category<>'' then category:=book.category;
if book.statusStr<>'' then statusStr:=book.statusStr;
if book.otherInfo<>'' then otherInfo:=book.otherInfo;
if book.issueDate<>0 then issueDate:=book.issueDate;
if book.dueDate<>0 then dueDate:=book.dueDate;
if book.status<>bsUnknown then status:=book.status;
if book.charges<>0 then charges:=book.charges;
if book.lastExistsDate<>0 then lastExistsDate:=book.lastExistsDate;
if (firstExistsDate=0) or ((book.firstExistsDate<>0) and (book.firstExistsDate<firstExistsDate)) then
firstExistsDate:=book.firstExistsDate;
for i:=0 to high(book.additional) do
setProperty(book.additional[i].name,book.additional[i].value,additional);
end;
}
{ TBookList }
function TBookList.getBook(i: longint): TBook; inline;
begin
result:=TBook(Items[i]);
end;
procedure TBookList.setLendList(const AValue: boolean);
var i:longint;
begin
flendList:=AValue;
for i:=0 to Count-1 do
books[i].lend:=AValue;
end;
constructor TBookList.create(aowner: TObject);
begin
owner:=aowner;
end;
destructor TBookList.Destroy;
begin
clear;
inherited Destroy;
end;
procedure TBookList.delete(i: longint);
begin
books[i].decReference;
inherited delete(i);
end;
function TBookList.remove(book: tbook):longint;
begin
Result := IndexOf(book);
If Result <> -1 then
Self.Delete(Result);
end;
procedure TBookList.clear;
var i:longint;
begin
for i:=0 to Count-1 do
books[i].decReference;
inherited clear;
end;
procedure TBookList.add(book: TBook);
begin
if book.owner=nil then begin
book.owner:=owner;
book.lend:=lendList;
end;
book.incReference;
inherited add(book);
end;
function TBookList.add(id, title, author, year: string): TBook;
begin
result:=TBook.Create;
result.id:=id;
result.title:=title;
Result.author:=author;
Result.year:=year;
Result.owner:=owner;
result.lend:=lendList;
inherited Add(Result);
end;
procedure TBookList.assign(alist: TBookList);
begin
clear;
AddList(alist);
end;
procedure TBookList.addList(alist: TBookList);
var i:longint;
begin
inherited AddList(alist);
for i:=0 to alist.count-1 do
alist[i].incReference;
end;
procedure TBookList.mergePersistentFields(const old: TBookList);
var i:longint;
begin
//TODO: Optimize to O(n log n)
for i:=0 to count-1 do
books[i].mergePersistentFields(old.findBook(books[i]));
end;
{procedure TBookList.overrideOldInformation(const old: TBookList);
var i:longint;
begin
//TODO: Optimize to O(n log n)
for i:=0 to count-1 do
books[i].assignOverride(old.findBook(books[i]));
end;}
procedure TBookList.removeAllFrom(booksToRemove: TBookList);
var i:longint;
begin
for i:=0 to booksToRemove.count-1 do
removeBook(booksToRemove[i]);
end;
procedure TBookList.removeAllExcept(booksToKeep: TBookList);
var i:longint;
begin
//TODO: Optimize to O(n log n)
for i:=count-1 downto 0 do
if booksToKeep.findBook(books[i]) = nil then
delete(i);
end;
function TBookList.removeBook(book: TBook):longint;
begin
Result:=findBookIndex(book);
if Result<>-1 then delete(Result);
end;
function TBookList.findBook(book: TBook): TBook;
var i:longint;
begin
for i:=0 to count-1 do
if books[i].equalToKey(book) then
exit(books[i]);
Result:=nil;
end;
function TBookList.findBookIndex(book: TBook): longint;
var i:longint;
begin
for i:=0 to count-1 do
if books[i].equalToKey(book) then
exit(i);
Result:=-1;
end;
function TBookList.findBook(id, author, title, year: string): TBook;
var i:longint;
begin
for i:=0 to count-1 do
if books[i].equalToKey(id,author,title,year) then
exit(books[i]);
Result:=nil;
end;
type
{ TBookListXMLReader }
TBookListXMLReader = class
list: TBookList;
constructor Create(alist: TBookList);
procedure parse(data: string);
private
currentBook: TBook;
currentPropertyName, currentPropertyValue: string;
function enterTag(tagName: string; properties: TProperties): TParsingResult;
function leaveTag(tagName: string): TParsingResult;
function textRead(text: string): TParsingResult;
end;
constructor TBookListXMLReader.Create(alist: TBookList);
begin
list := alist;
end;
function TBookListXMLReader.leaveTag(tagName: string): TParsingResult;
begin
result := prContinue;
case tagName of
'books': result := prStop;
'book': begin
list.add(currentBook);
currentBook.decReference; //HUH? That is not the same as the old loading (now ref count = 1 in list, previously was ref count = 2)
currentBook := nil;
end;
'v': if (currentPropertyName = '') or (currentBook = nil) then raise EBookListReader.create('Korrupte Bücherdatei')
else begin
currentBook.setProperty(currentPropertyName, currentPropertyValue);
currentPropertyName := '';
currentPropertyValue := '';
end;
else raise EBookListReader.create('Korrupte Bücherdatei (ungültiger geschlossener Tag)');
end;
end;
procedure TBookListXMLReader.parse(data: string);
begin
simplexmlparser.parseXML(data, @enterTag, @leaveTag, @textRead, CP_UTF8);
end;
function TBookListXMLReader.enterTag(tagName: string; properties: TProperties): TParsingResult;
begin
case LowerCase(tagName) of
'books': ; //
'book': currentBook := TBook.create;
'v': begin
currentPropertyName := simplexmlparser.getProperty('n', properties);
currentPropertyValue := '';
end;
'?xml': ;
else raise EBookListReader.create('Korrupte Bücherdatei (ungültiger geöffneter Tag)');
end;
result := prContinue;
end;
function TBookListXMLReader.textRead(text: string): TParsingResult;
begin
if currentPropertyName <> '' then currentPropertyValue += text;
result := prContinue;
end;
procedure TBookList.load(fileName: string);
function truncNull(var source: string):string;
var p:integer;
begin
p:=pos(#0,source);
result:=copy(source,1,p-1);
system.delete(source,1,p);
end;
function truncNullDef(var source: string;def:string):string;
var p:integer;
begin
p:=pos(#0,source);
if p<=0 then exit(def);
result:=copy(source,1,p-1);
system.delete(source,1,p);
end;
var sl:TStringList;
line:string;
i:integer;
book:TBook;
xmlReader: TBookListXMLReader;
begin
if logging then
log('TBookList.load('+fileName+') started');
clear;
if FileExists(fileName+'.xml') then begin
xmlReader := TBookListXMLReader.Create(self);
xmlReader.parse(strLoadFromFileUTF8(fileName+'.xml'));
xmlReader.free;
end else if FileExists(fileName) then begin
log('Import old file format');
sl:=TStringList.create;
sl.LoadFromFile(fileName);
Capacity:=sl.count;
for i:=0 to sl.count-1 do begin
book:=TBook.Create;
with book do begin
line:=sl[i];
id:=truncNull(line);
category:=truncNull(line);
author:=truncNull(line);
title:=truncNull(line);
statusStr:=truncNull(line);
{otherInfo:=}truncNull(line);
issueDate:=StrToInt(truncNull(line));
dueDate:=StrToInt(truncNull(line));
lastExistsDate:=StrToInt(truncNull(line));
status:=TBookStatus(StrToInt(truncNull(line)));
year:=truncNullDef(line,'');
firstExistsDate:=StrToInt(truncNullDef(line,'0'));
isbn:=truncNullDef(line,'');
lend:=self.lendList;
owner:=self.owner;
//list:=self;
end;
inherited add(book);
end;
sl.free;
end;
if logging then
log('TBookList.load('+fileName+') ended')
end;
type
{ TBookListSerializer }
TBookListSerializer = object
stream: tstream;
procedure writeProp(const n,v:string);
procedure writeDateProp(const n: string; d: integer);
procedure writeString(const s: string);
procedure writeLn(const s: string);
end;
procedure TBookListSerializer.writeProp(const n, v: string);
begin
writeLn(#9'<v n="'+xmlStrEscape(n,true)+'">'+xmlStrEscape(v)+'</v>');
end;
procedure TBookListSerializer.writeDateProp(const n: string; d: integer);
begin
writeProp(n, dateTimeFormat('yyyy-mm-dd', d));
end;
procedure TBookListSerializer.writeString(const s: string);
begin
if length(s) = 0 then exit;
stream.WriteBuffer(s[1], length(s));
end;
procedure TBookListSerializer.writeLn(const s: string);
begin
writeString(s + LineEnding);
end;
procedure booklistSave(stream: TStream; data: pointer);
var temp: TBookListSerializer;
i: Integer;
begin
with TBookList(data) do begin
temp.stream := stream;
temp.writeLn('<?xml version="1.0" encoding="UTF-8"?>');
temp.writeLn('<books>');
for i := 0 to count-1 do begin
temp.writeLn('<book>');
books[i].serialize(@temp.writeProp, @temp.writeDateProp);
temp.writeLn('</book>');
end;