-
Notifications
You must be signed in to change notification settings - Fork 5
/
librarysearcheraccess.pas
637 lines (548 loc) · 21.5 KB
/
librarysearcheraccess.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
unit librarySearcherAccess;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils , librarySearcher,libraryParser, booklistreader,bbutils,messagesystem,simplexmlparser,multipagetemplate;
type
TBookNotifyEvent=procedure (sender: TObject; book: TBook) of object;
TPageCompleteNotifyEvent=procedure (sender: TObject; firstPage, nextPageAvailable: boolean) of object;
TPendingMessageEvent=procedure (sender: TObject; book: TBook; pendingMessage: TPendingMessage) of object;
TLibrarySearcherAccess = class;
{ TLibrarySearcherAccess }
TSearcherMessageTyp=(smtNone, smtFreeSearcher, smtFreeSearcherAndAccess, smtConnect, smtSearch, smtSearchNext, smtDetails, smtOrder, smtCompletePendingMessage, smtDisconnect);
{ TSearcherMessage }
TSearcherMessage = class
typ: TSearcherMessageTyp;
book: tbook;
pendingMessage: TPendingMessage;
messageResult: integer;
constructor create(t:TSearcherMessageTyp; b:TBook=nil; apendingMessage: TPendingMessage = nil; mesresult: integer = 0);
end;
{ TSearcherThread }
TSearcherThread = class(TThread)
private
fbookAccessSection: TRTLCriticalSection;
access: TLibrarySearcherAccess;
messages: TMessageSystem;
Searcher: TLibrarySearcher;
notifyEvent: TNotifyEvent;
bookNotifyEvent: TBookNotifyEvent;
pageCompleteEvent: TPageCompleteNotifyEvent;
pendingMessageEvent: TPendingMessageEvent;
//connectedEvent: TNotifyEvent;
changedBook: tbook;
firstPageForSync, nextPageAvailableForSync: boolean;
pendingMessage: TPendingMessage;
performingAction: TSearcherMessageTyp;
procedure desktopSynchronized(t: TThreadMethod);
procedure callNotifyEventSynchronized;
procedure callBookEventSynchronized;
procedure callPageCompleteEventSynchronized;
procedure callPendingMessageEventSynchronized;
procedure callNotifyEvent(event: TNotifyEvent);
procedure callBookEvent(event: TBookNotifyEvent; book: tbook);
procedure callPageCompleteEvent(event: TPageCompleteNotifyEvent; firstPage, nextPageAvailable: boolean);
procedure callPendingMessageEvent(event: TPendingMessageEvent; book: TBook; pendingMes: TPendingMessage);
procedure processPendingMessage(book: TBook; isOrderingAction: boolean);
protected
procedure execute;override;
public
constructor create(template: TMultiPageTemplate; aaccess: TLibrarySearcherAccess);
destructor destroy;override;
end;
TLibrarySearcherAccess = class
private
FOnException: TNotifyEvent;
fthread: TSearcherThread;
ftemplate: TMultiPageTemplate;
FOnConnected, FOnPendingMessageCompleted: TNotifyEvent;
FOnDetailsComplete, FOnOrderComplete: TBookNotifyEvent;
FOnSearchPageComplete: TPageCompleteNotifyEvent;
FOnTakePendingMessage: TPendingMessageEvent;
procedure removeOldMessageOf(typ: TSearcherMessageTyp);
function GetSearcher: TLibrarySearcher;
procedure loadSearchCache;
public
function operationActive: boolean;
constructor create();
procedure beginBookReading; //to access any searched book
procedure endBookReading;
procedure beginResultReading; //before accessing searcher
procedure endResultReading;
procedure newSearch(template: TMultiPageTemplate); //ensures that all operations are finished
procedure prepareNewSearchWithoutDisconnect; //ensures that all operations are finished, without changing the connection state
procedure connectAsync;
procedure searchAsync;
procedure searchNextAsync;
procedure detailsAsyncSave(book: TBook); //save means they make sure the
procedure orderAsync(account: TCustomAccountAccess; book: TBook);
procedure completePendingMessage(book: TBook; pm: TPendingMessage; result: integer);
procedure disconnectAsync;
procedure freeAsync;
property OnException: TNotifyEvent read FOnException write FOnException;
property OnConnected: TNotifyEvent read FOnConnected write FOnConnected;
property OnSearchPageComplete: TPageCompleteNotifyEvent read FOnSearchPageComplete write FOnSearchPageComplete;
property OnDetailsComplete: TBookNotifyEvent read FOnDetailsComplete write FOnDetailsComplete;
//holding order events:
//after calling orderAsync,
// --if there is a message---> OnTakePendingMessage --\
// --if there is no message--> OnOrderComplete |
// |
// /--------------------------------------------------------+
// \|/ |
//after calling completePendingMessage |
// --if there is a message---> OnTakePendingMessage ----/
// --if there is no message
// -----if status=ordered-----> OnOrderComplete
// -----if status<>ordered----> OnPendingMessageCompleted
property OnOrderComplete: TBookNotifyEvent read FOnOrderComplete write FOnOrderComplete;
property OnTakePendingMessage: TPendingMessageEvent read FOnTakePendingMessage write FOnTakePendingMessage;
property OnPendingMessageCompleted: TNotifyEvent read FOnPendingMessageCompleted write FOnPendingMessageCompleted;
property searcher: TLibrarySearcher read GetSearcher;
end;
type
{ TSearchTarget }
TSearchTarget = class
id: string;
name: string;
lib: TLibrary; //might be nil
template: TMultiPageTemplate;
constructor create(aname: string; alib: TLibrary; atemplate: TMultiPageTemplate);
constructor create(aid: string);
end;
{ TSearchableLocations }
TSearchableLocations = record
regions: TStringList; //string -> tstringlist
locations: TStringList; //string->stringlist of TSearchTarget
//searchTemplates: TStringList;
end;
function getSearchableLocations: TSearchableLocations;
implementation
uses applicationconfig, bbdebugtools, internetaccess, androidutils {$ifdef android}, bbjniutils{$else},forms{$endif}, commoninterface, xquery, jsonscannerhelper;
resourcestring
rsSearchAllRegions = 'alle Regionen';
function getSearchableLocations: TSearchableLocations;
function nestedList(base: TStringList; name: string): TStringList;
var
i: Integer;
begin
i := base.IndexOf(name);
if i < 0 then begin
result := TStringList.Create;
result.OwnsObjects := true;
i := base.AddObject(name, result);
end;
result := TStringList(base.Objects[i]);
end;
var
temp: TStringList;
loc: String;
libraryMetaData: TLibraryMetaDataEnumerator;
begin
with result do begin
regions := TStringList.Create;
regions.OwnsObjects := true;
locations := TStringList.Create;
locations.OwnsObjects := true;
libraryMetaData := libraryManager.enumerateLibraryMetaData;
while libraryMetaData.MoveNext do begin
loc := libraryMetaData.prettyLocation;
temp := nestedList(regions, libraryMetaData.prettyCountryState);
if temp.IndexOf(loc) < 0 then temp.Add(loc);
temp := nestedList(locations, loc);
temp.AddObject(libraryMetaData.libraryId, TSearchTarget.create(libraryMetaData.libraryId));
end;
locations.Sort;
nestedList(regions, rsSearchAllRegions).Text := locations.Text;
regions.Sort;
end;
end;
{ TSearchTarget }
constructor TSearchTarget.create(aname: string; alib: TLibrary; atemplate: TMultiPageTemplate);
begin
name := aname;
lib := alib;
template := atemplate;
end;
constructor TSearchTarget.create(aid: string);
begin
id := aid
end;
{ TLibrarySearcherAccess }
function TLibrarySearcherAccess.GetSearcher: TLibrarySearcher;
begin
if not assigned(fthread) then exit(nil);
Result:=fthread.Searcher;
end;
constructor TLibrarySearcherAccess.create();
begin
end;
procedure TLibrarySearcherAccess.freeAsync;
begin
if self = nil then exit;
if assigned(fthread) then fthread.messages.storeMessage(TSearcherMessage.Create(smtFreeSearcherAndAccess))
else free;
end;
procedure TLibrarySearcherAccess.beginBookReading;
begin
if not assigned(fthread) then exit;
EnterCriticalsection(fthread. fbookAccessSection);
end;
procedure TLibrarySearcherAccess.endBookReading;
begin
if not assigned(fthread) then exit;
LeaveCriticalsection(fthread.fbookAccessSection);
end;
procedure TLibrarySearcherAccess.beginResultReading;
begin
beginBookReading;
end;
procedure TLibrarySearcherAccess.endResultReading;
begin
endBookReading;
end;
function TLibrarySearcherAccess.operationActive: boolean;
begin
ReadBarrier;
result:=assigned(fthread) and (fthread.messages.existsMessage or (fthread.performingAction <> smtNone));
end;
procedure TLibrarySearcherAccess.removeOldMessageOf(typ: TSearcherMessageTyp);
var list: TFPList;
i:longint;
begin
if not assigned(fthread) then exit;
list:=fthread.messages.openDirectMessageAccess;
for i:=list.Count-1 downto 0 do
if TSearcherMessage(list[i]).typ=typ then begin
tobject(list[i]).free;
list.Delete(i);
end;
fthread.messages.closeDirectMessageAccess(list);
end;
procedure TLibrarySearcherAccess.newSearch(template: TMultiPageTemplate);
begin
if (operationActive) or not Assigned(fthread) or (ftemplate <> template) then begin
if assigned(fthread) then fthread.messages.storeMessage(TSearcherMessage.Create(smtFreeSearcher));
ftemplate := template;
fthread:=TSearcherThread.Create(ftemplate,self);
ReadWriteBarrier;
while fthread.Searcher = nil do begin sleep(25); ReadBarrier; end; //wait for thread start
ReadBarrier;
end;
end;
procedure TLibrarySearcherAccess.prepareNewSearchWithoutDisconnect;
const ALLOWED_ACTIONS = [smtNone, smtFreeSearcher, smtFreeSearcherAndAccess, smtConnect, smtDisconnect];
var
list: TFPList;
i: Integer;
begin
list:=fthread.messages.openDirectMessageAccess;
for i:=list.Count-1 downto 0 do
if not (TSearcherMessage(list[i]).typ in ALLOWED_ACTIONS) then begin
tobject(list[i]).free;
list.Delete(i);
end;
fthread.messages.closeDirectMessageAccess(list);
while assigned(fthread) and not (fthread.performingAction in ALLOWED_ACTIONS) do begin
ReadWriteBarrier; //i do not understand what this does
sleep(50);
{$ifndef android}application.ProcessMessages;{$endif}
end;
end;
procedure TLibrarySearcherAccess.loadSearchCache;
var
cache: String;
json, temp: IXQValue;
begin
cache := strLoadFromFile(searcher.getCacheFile);
if cache = '' then exit;
try
json := commoninterface.parseJSON(cache);
temp := json.getProperty('search-params');
if temp.kind = pvkObject then
searcher.SearchParams := TFormParams.fromJSON(temp);
except
on e: Exception do
storeException(e,nil,searcher.getLibraryIds,'-', nil);
end;
end;
procedure TLibrarySearcherAccess.connectAsync;
begin
if not assigned(fthread) then exit;
removeOldMessageOf(smtConnect);
if FileExists(searcher.getCacheFile) then loadSearchCache;
fthread.messages.storeMessage(TSearcherMessage.Create(smtConnect));
end;
procedure TLibrarySearcherAccess.searchAsync;
begin
if not assigned(fthread) then exit;
removeOldMessageOf(smtSearch);
fthread.messages.storeMessage(TSearcherMessage.Create(smtSearch));
end;
procedure TLibrarySearcherAccess.searchNextAsync;
begin
if not assigned(fthread) then exit;
removeOldMessageOf(smtSearchNext);
fthread.messages.storeMessage(TSearcherMessage.Create(smtSearchNext));
end;
procedure TLibrarySearcherAccess.detailsAsyncSave(book: TBook);
begin
if not assigned(fthread) then exit;
removeOldMessageOf(smtDetails);
fthread.messages.storeMessage(TSearcherMessage.Create(smtDetails,book));
end;
procedure TLibrarySearcherAccess.orderAsync(account: TCustomAccountAccess; book: TBook);
begin
if not assigned(fthread) then exit;
book.owningAccount := account;
fthread.messages.storeMessage(TSearcherMessage.Create(smtOrder,book));
end;
procedure TLibrarySearcherAccess.completePendingMessage(book: TBook; pm: TPendingMessage; result: integer);
begin
if not assigned(fthread) then exit;
if pm.callback = '' then exit;
fthread.messages.storeMessage(TSearcherMessage.Create(smtCompletePendingMessage,book, pm, result));
end;
procedure TLibrarySearcherAccess.disconnectAsync;
begin
if not assigned(fthread) then exit;
removeOldMessageOf(smtDisconnect);
fthread.messages.storeMessage(TSearcherMessage.Create(smtDisconnect));
end;
{ TSearcherThread }
procedure TSearcherThread.desktopSynchronized(t: TThreadMethod);
begin
{$ifndef android}
Synchronize(t);
{$else}
t();
{$endif}
end;
procedure TSearcherThread.callNotifyEventSynchronized;
begin
if self<>access.fthread then exit;
try
notifyEvent(access);
finally
notifyEvent:=nil;
end;
end;
procedure TSearcherThread.callBookEventSynchronized;
begin
if self<>access.fthread then exit;
try
bookNotifyEvent(access,changedBook);
finally
changedBook := nil;
end;
end;
procedure TSearcherThread.callPageCompleteEventSynchronized;
begin
if self<>access.fthread then exit;
if pageCompleteEvent = nil then exit;
try
pageCompleteEvent(access, firstPageForSync, nextPageAvailableForSync);
finally
pageCompleteEvent:=nil;
end;
end;
procedure TSearcherThread.callPendingMessageEventSynchronized;
begin
if self<>access.fthread then exit;
try
pendingMessageEvent(access,changedBook,pendingMessage);
finally
changedBook := nil;
pendingMessage := nil;
end;
end;
procedure TSearcherThread.callNotifyEvent(event: TNotifyEvent);
begin
if event=nil then exit;
while notifyEvent<>nil do sleep(5);
notifyEvent:=event;
desktopSynchronized(@callNotifyEventSynchronized);
end;
procedure TSearcherThread.callBookEvent(event: TBookNotifyEvent; book: tbook);
begin
if event=nil then exit;
if logging then log('Changed book: '+strFromPtr(changedBook));
while changedBook<>nil do sleep(5);
if logging then log('wait complete');
bookNotifyEvent:=event;
changedBook:=book;
desktopSynchronized(@callBookEventSynchronized);
end;
procedure TSearcherThread.callPageCompleteEvent(event: TPageCompleteNotifyEvent; firstPage, nextPageAvailable: boolean);
begin
if event = nil then exit;
while pageCompleteEvent <> nil do sleep(5);
pageCompleteEvent:=event;
firstPageForSync:=firstPage;
nextPageAvailableForSync:=nextPageAvailable;
desktopSynchronized(@callPageCompleteEventSynchronized);
end;
procedure TSearcherThread.callPendingMessageEvent(event: TPendingMessageEvent; book: TBook; pendingMes: TPendingMessage);
begin
if event=nil then exit;
if logging then log('Pending message: '+strFromPtr(changedBook)+' '+pendingMes.caption);
while changedBook<>nil do sleep(5);
if logging then log('wait complete');
pendingMessageEvent:=event;
changedBook:=book;
pendingMessage:=pendingMes;
desktopSynchronized(@callPendingMessageEventSynchronized);
end;
procedure TSearcherThread.processPendingMessage(book: TBook; isOrderingAction: boolean);
var
tmpPendingMessage: TPendingMessage;
hasCallback: Boolean;
begin
tmpPendingMessage := Searcher.bookListReader.pendingMessage;
if tmpPendingMessage <> nil then begin
hasCallback := tmpPendingMessage.callback <> '';
callPendingMessageEvent(access.FOnTakePendingMessage, book, tmpPendingMessage);
Searcher.bookListReader.pendingMessage := nil;
if hasCallback then exit; //the callback should be called by complete message, and handle it from there
end;
if isOrderingAction then begin
callBookEvent(access.FOnOrderComplete, book);
end else callNotifyEvent(access.FOnPendingMessageCompleted);
end;
procedure TSearcherThread.execute;
var mes: TSearcherMessage;
book: tbook;
debugLastSearchQuery: String;
newsearcher: TLibrarySearcher;
begin
newsearcher := TLibrarySearcher.create(access.ftemplate);
newsearcher.bookListReader.bookAccessSection:=@fbookAccessSection;
ReadWriteBarrier;
Searcher := newsearcher;
while true do begin
try
performingAction:=smtNone;
if logging then log('Searcher thread: wait for message');
mes:=TSearcherMessage(messages.waitForMessage);
if logging then log('Searcher thread: got message'+strFromPtr(mes));
if mes=nil then continue;
if mes.typ in [smtFreeSearcher, smtFreeSearcherAndAccess] then begin
if logging then log('Searcher thread: message typ smtFree');
if mes.typ = smtFreeSearcherAndAccess then access.Free;
mes.free;
break;
end;
performingAction:=mes.typ;
book:=mes.book;
if logging then
if mes.book = nil then log('Message book: nil')
else begin
log('Message book: '+strFromPtr(book) +' ' +book.title+' from '+book.author);
//for i:=0 to high(book.additional) do log('Book properties: '+book.additional[i].name+' = '+book.additional[i].value);
end;
case mes.typ of
smtNone: ;
smtConnect: begin
if logging then log('Searcher thread: message typ smtConnect');
searcher.connect;
callNotifyEvent(access.FOnConnected);
end;
smtSearch: begin
if logging then log('Searcher thread: message typ smtSearch');
if not searcher.Connected then begin //handles timeouts
if logging then log('Searcher thread: timeout reconnect');
searcher.connect;
callNotifyEvent(access.FOnConnected);
end;
access.beginResultReading; Searcher.SearchResult.clear; access.endResultReading;
if Searcher.SearchOptions <> nil then
debugLastSearchQuery := Searcher.SearchOptions.title + '/'+Searcher.SearchOptions.author+'/'+
Searcher.SearchOptions.getPropertyAdditional('keywords') + '/' + Searcher.SearchOptions.isbn + '/' +
Searcher.SearchOptions.year;// + '@' + inttostr(Searcher.SearchBranch)+':'+inttostr(searcher.HomeBranch);
searcher.search;
callPageCompleteEvent(access.FOnSearchPageComplete, true, searcher.SearchNextPageAvailable);
end;
smtSearchNext: begin
if logging then log('Searcher thread: message typ smtSearchNext');
access.beginResultReading; Searcher.SearchResult.clear; access.endResultReading;
Searcher.searchNext;
callPageCompleteEvent(access.FOnSearchPageComplete, false, searcher.SearchNextPageAvailable);
end;
smtDetails: begin
if logging then log('Searcher thread: message typ smtDetails');
if getproperty('details-searched',book.additional)<>'true' then begin
if logging then log('Searcher thread: search details for '+book.title+' from '+book.author);
Searcher.details(book);
access.beginBookReading;
addProperty('details-searched','true',book.additional);
access.endBookReading;
callBookEvent(access.FOnDetailsComplete,book);
end;
end;
smtOrder: begin
if logging then log('Searcher thread: message smtOrder: '+book.toSimpleString());
if (book = nil) or (book.owningAccount = nil) then log('Invalid book')
else begin
Searcher.orderSingle(book);
processPendingMessage(book.owningBook, true);
end;
if logging then log('end order');
end;
smtCompletePendingMessage: begin
if logging then log('Searcher thread: message smtCompletePendingMessage: '+book.toSimpleString());
if book <> nil then Searcher.bookListReader.selectBook(book);
Searcher.completePendingMessage(mes.pendingMessage, mes.messageResult);
processPendingMessage(book, (book <> nil) and (book.status in BOOK_CANCELABLE)); //BOOK_CANCELABLE does not mean cancelable, it refers to all ordered books. The idea is that the template will only set the status if the ordering succeeded
if logging then log('end order');
end
else if logging then log('Searcher thread: unknown type');
end;
FreeAndNil(mes);
except
on e: Exception do begin
storeException(e,nil,searcher.getLibraryIds,debugLastSearchQuery,searcher.bookListReader.actionTrace.toSharedArray);
FreeAndNil(mes);
messages.removeAndFreeAll;
callNotifyEvent(access.fOnException);
end;
end;
end;
performingAction:=smtNone;
FreeAndNil(Searcher);
end;
constructor TSearcherThread.create(template: TMultiPageTemplate; aaccess: TLibrarySearcherAccess);
begin
InitCriticalSection(fbookAccessSection);
self.access:=aaccess;
messages:=TMessageSystem.create;
performingAction := smtNone;
changedBook:=nil;
FreeOnTerminate:=true;
inherited create(false);
end;
destructor TSearcherThread.destroy;
begin
if logging then log('TSearcherThread.destroy started');
try
while messages.existsMessage do messages.retrieveLatestMessageOrNil.free;
messages.free;
DoneCriticalsection(fbookAccessSection);
{$ifdef android}
jvmref^^.DetachCurrentThread(jvmref);
{$endif}
except
on e: Exception do
if logging then log('exception: ' + e.Message);
end;
if logging then log('TSearcherThread.destroy ended');
inherited destroy;
end;
{ TSearcherMessage }
constructor TSearcherMessage.create(t: TSearcherMessageTyp; b: TBook; apendingMessage: TPendingMessage = nil; mesresult: integer = 0 );
begin
typ:=t;
book:=b;
self.pendingMessage := apendingMessage;
messageResult := mesresult;
end;
end.