-
Notifications
You must be signed in to change notification settings - Fork 4
/
eaterFeeds.pas
1461 lines (1321 loc) · 43.7 KB
/
eaterFeeds.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 eaterFeeds;
interface
uses Classes, DataLank, eaterReg;
type
TFeedEatResult=record
FeedCount,PostCount:integer;
end;
TFeedEater=class(TInterfacedObject, IFeedStore, IFeedHandler)
private
FDB,FDBStats:TDataConnection;
FReport:TStringList;
FPostID:string;
FPostURL:WideString;
FPostPubDate:TDateTime;
FPostTags:Variant;
FPostTagPrefix:string;
FFeed:record
id,group_id:integer;
URL,URL0,URLSkip,Name,Name0,LastMod,LastMod0,Result,Result0:string;
Regime,TotalCount:integer;
LoadStart,LoadLast:TDateTime;
NotModified:boolean;
end;
FPostsTotal,FPostsNew:integer;
FHasReplaces:boolean;
OldPostsCutOff:TDateTime;
function LoadExternal(const URL,FilePath,LastMod,Accept:string):WideString;
function ParseExternalHeader(var content:WideString):WideString;
function FeedSkipDisplay(d:TDateTime):string;
procedure PerformReplaces(var title,content:WideString);
procedure PerformGlobalReplaces(var data:WideString);
procedure FeedCombineURL(const url,lbl:string);
function FindFeedURL(const data:WideString):boolean;
//IFeedStore
function CheckLastLoadResultPrefix(const Prefix:string):boolean;
//IFeedHandler
function CheckNewPost(const PostID:string;const PostURL:WideString;
PostPubDate:TDateTime):boolean;
procedure UpdateFeedName(const NewName:string);
procedure PostTags(const TagPrefix:string;const Tags:Variant);
procedure RegisterPost(const PostTitle,PostContent:WideString);
procedure ReportSuccess(const Lbl:string);
procedure ReportFailure(const Msg:string);
public
ForceLoadAll,SaveData:boolean;
OnFeedURLUpdate:TNotifyEvent;
constructor Create;
destructor Destroy; override;
procedure DoCleanup;
procedure DoAutoUnread;
function DoUpdateFeeds(SpecificFeedID:integer;const FeedLike:string;
PubDateMargin:double):TFeedEatResult;
procedure RenderGraphs;
end;
const
Specific_NewFeeds=-111;
var
PGVersion:string;
BlackList:TStringList;
implementation
uses Windows, SysUtils, Variants, ComObj, eaterUtils, eaterSanitize, MSXML2_TLB,
jsonDoc, VBScript_RegExp_55_TLB, eaterGraphs, feedSoundCloud, eatGram_TLB;
const
FeederIniPath='..\..\feeder.ini';
EaterIniPath='..\..\feeder_eater.ini';
//TODO: from ini?
FeedLoadReport='..\Load.html';
AvgPostsDays=500;
OldPostsDays=3660;
regimesteps=8;
regimestep:array[0..regimesteps-1] of integer=(1,2,3,7,14,30,60,90);
YoutubePrefix1='https://www.youtube.com/channel/';
YoutubePrefix2='https://www.youtube.com/feeds/videos.xml?channel_id=';
var
EaterGram:IEaterGram;
function qrDate(qr:TQueryResult;const Idx:Variant):TDateTime;
var
v:Variant;
begin
v:=qr[Idx];
if VarIsNull(v) then
Result:=0
else
Result:=double(v);
end;
{ TFeedEater }
constructor TFeedEater.Create;
var
sl:TStringList;
constr:string;
qr:TQueryResult;
begin
inherited Create;
OutLn('Opening databases...');
sl:=TStringList.Create;
try
sl.LoadFromFile(FeederIniPath);
constr:=sl.Text;
finally
sl.Free;
end;
FDB:=TDataConnection.Create(constr);
FDBStats:=TDataConnection.Create(constr);
if PGVersion='' then //?
begin
qr:=TQueryResult.Create(FDB,'select version()',[]);
try
if qr.Read then PGVersion:=qr.GetStr(0);
finally
qr.Free;
end;
end;
FReport:=TStringList.Create;
FReport.DefaultEncoding:=TEncoding.UTF8;
OldPostsCutOff:=UtcNow-OldPostsDays;
ForceLoadAll:=false;//default
SaveData:=false;//default
OnFeedURLUpdate:=nil;
end;
destructor TFeedEater.Destroy;
begin
FDB.Free;
FDBStats.Free;
inherited;
end;
procedure TFeedEater.DoCleanup;
var
qr:TQueryResult;
i,j:integer;
begin
Out0('Clean-up old...');
qr:=TQueryResult.Create(FDBStats,'select id from "Post" where pubdate<$1',[double(OldPostsCutOff)]);
try
j:=0;
while qr.Read do
begin
i:=qr.GetInt('id');
FDB.BeginTrans;
try
FDB.Execute('delete from "UserPost" where post_id=$1',[i]);
FDB.Execute('delete from "Opinion" where post_id=$1',[i]);
FDB.Execute('delete from "Post" where id=$1',[i]);
FDB.CommitTrans;
except
FDB.RollbackTrans;
raise;
end;
inc(j);
end;
Writeln(' '+IntToStr(j)+' posts cleaned ');
finally
qr.Free;
end;
Out0('Clean-up unused...');
qr:=TQueryResult.Create(FDBStats,'select id from "Feed" where id>0'+
' and not exists (select S.id from "Subscription" S where S.feed_id="Feed".id)',[]);
try
j:=0;
while qr.Read do
begin
i:=qr.GetInt('id');
Write(#13'... #'+IntToStr(i)+' ');
FDB.BeginTrans;
try
FDB.Execute('delete from "UserPost" where post_id in (select P.id from "Post" P where P.feed_id=$1)',[i]);
FDB.Execute('delete from "Opinion" where post_id in (select P.id from "Post" P where P.feed_id=$1)',[i]);
FDB.Execute('delete from "Post" where feed_id=$1',[i]);
FDB.Execute('delete from "Feed" where id=$1',[i]);
FDB.CommitTrans;
except
FDB.RollbackTrans;
raise;
end;
inc(j);
end;
Writeln(' '+IntToStr(j)+' feeds cleaned ');
finally
qr.Free;
end;
end;
procedure TFeedEater.DoAutoUnread;
var
qr:TQueryResult;
i:integer;
begin
Out0('Auto-unread after...');
qr:=TQueryResult.Create(FDBStats,'select X.id from "UserPost" X'
+' inner join "Post" P on P.id=X.post_id'
+' inner join "Subscription" S on S.id=X.subscription_id'
+' where P.pubdate<$1-S.autounread/24.0 limit 1',[double(UtcNow)]);
try
if qr.EOF then i:=0 else i:=1;
finally
qr.Free;
end;
if i=0 then
Writeln(' none')
else
begin
FDB.BeginTrans;
try
i:=FDB.Execute('delete from "UserPost" where id in (select X.id'
+' from "UserPost" X'
+' inner join "Post" P on P.id=X.post_id'
+' inner join "Subscription" S on S.id=X.subscription_id'
+' where P.pubdate<$1-S.autounread/24.0)',[double(UtcNow)]);
FDB.CommitTrans;
except
FDB.RollbackTrans;
raise;
end;
Writeln(' '+IntToStr(i)+' items marked read');
end;
end;
function TFeedEater.DoUpdateFeeds(SpecificFeedID:integer;const FeedLike:string;
PubDateMargin:double):TFeedEatResult;
var
qr:TQueryResult;
ids:array of integer;
ids_i,ids_l:integer;
d,oldPostDate:TDateTime;
sql1,sql2,ss:string;
postlast,postavg,f:double;
newfeed,dofeed,doreq,loadext,xres:boolean;
r:ServerXMLHTTP60;
redirCount,i,j:integer;
handler_i:cardinal;
doc:DOMDocument60;
FeedData,FeedDataType:WideString;
begin
FReport.Clear;
//TODO: from embedded resource
FReport.Add('<style>');
FReport.Add('P{font-family:"PT Sans","Yu Gothic",Calibri,sans-serif;font-size:0.7em;}');
FReport.Add('TH{font-family:"PT Sans","Yu Gothic",Calibri,sans-serif;font-size:0.7em;white-space:nowrap;border:1px solid #333333;}');
FReport.Add('TD{font-family:"PT Sans","Yu Gothic",Calibri,sans-serif;font-size:0.7em;white-space:nowrap;border:1px solid #CCCCCC;}');
FReport.Add('TD.n{max-width:20em;overflow:hidden;text-overflow:ellipsis;}');
FReport.Add('TD.empty{background-color:#CCCCCC;}');
FReport.Add('DIV.flag{display:inline;padding:2pt;color:#FFCC00;border-radius:4pt;white-space:nowrap;}');
FReport.Add('</style>');
FReport.Add('<table cellspacing="0" cellpadding="4" border="1">');
FReport.Add('<tr>');
FReport.Add('<th> </th>');
FReport.Add('<th>name</th>');
FReport.Add('<th>created</th>');
FReport.Add('<th>#</th>');
FReport.Add('<th>post:last</th>');
FReport.Add('<th>post:avg</th>');
FReport.Add('<th>regime</th>');
FReport.Add('<th>load:last</th>');
FReport.Add('<th>:since</th>');
FReport.Add('<th>load:result</th>');
FReport.Add('<th>load:new</th>');
FReport.Add('<th>load:items</th>');
FReport.Add('<th>total</th>');
FReport.Add('</tr>');
try
OutLn('List feeds for loading...');
Result.FeedCount:=0;
Result.PostCount:=0;
if SpecificFeedID>0 then
begin
ids_l:=1;
SetLength(ids,1);
ids[0]:=SpecificFeedID;
end
else
begin
if SpecificFeedID=Specific_NewFeeds then
qr:=TQueryResult.Create(FDB,'select F.id from "Feed" F where F.id>0'+
' and F.created>$1 order by F.id',[UtcNow-1.0])
else if FeedLike<>'' then
qr:=TQueryResult.Create(FDB,'select F.id from "Feed" F where F.id>0'+
' and F.url like $1'+
' order by F.id',['%'+FeedLike+'%'])
else
qr:=TQueryResult.Create(FDB,'select F.id from "Feed" F where F.id>0'+
//' and url like ''%instagram%'''+
' order by F.id',[]);
try
ids_l:=0;
ids_i:=0;
while qr.Read do
begin
if ids_i=ids_l then
begin
inc(ids_l,$400);//grow step
SetLength(ids,ids_l);
end;
ids[ids_i]:=qr.GetInt('id');
inc(ids_i);
end;
ids_l:=ids_i;
finally
qr.Free;
end;
end;
oldPostDate:=UtcNow-AvgPostsDays;
ids_i:=0;
while ids_i<ids_l do
begin
FFeed.id:=ids[ids_i];
qr:=TQueryResult.Create(FDB,'select *'
+' ,(select count(*) from "Subscription" S where S.feed_id=F.id) as scount'
+' from "Feed" F where F.id=$1',[FFeed.id]);
try
if qr.EOF then raise Exception.Create('No feed found for this id.');
FFeed.group_id:=qr.GetInt('group_id');
FFeed.URL0:=qr.GetStr('url');
FFeed.URLSkip:=qr.GetStr('urlskip');
FFeed.Name0:=qr.GetStr('name');
FFeed.LastMod0:=qr.GetStr('lastmod');
FFeed.Result0:=qr.GetStr('result');
FFeed.Regime:=qr.GetInt('regime');
FFeed.TotalCount:=qr.GetInt('totalcount');
FFeed.LoadStart:=UtcNow;
FFeed.LoadLast:=qrDate(qr,'loadlast');
FFeed.URL:=FFeed.URL0;
FFeed.Name:=FFeed.Name0;
FFeed.LastMod:=FFeed.LastMod0;
FFeed.Result:='';
FFeed.NotModified:=false;
FPostsTotal:=qr.GetInt('itemcount');
FPostsNew:=qr.GetInt('loadcount');
newfeed:=qr.IsNull('itemcount');
Out0('#'+IntToStr(FFeed.id)+' '+DisplayShortURL(FFeed.URL));
//flags
//i:=qr0.GetInt('flags');
//feedglobal:=(i and 1)<>0;
//TODO: more?
FReport.Add('<tr>');
FReport.Add('<th>'+IntToStr(FFeed.id)+'</th>');
FReport.Add('<td class="n" title="'+FormatDateTime('yyyy-mm-dd hh:nn:ss',FFeed.LoadStart)+'">');
if FFeed.group_id<>0 then
FReport.Add('<div class="flag" style="background-color:red;">'+IntToStr(FFeed.group_id)+'</div> ');
FReport.Add('<a href="'+HTMLEncode(FFeed.URL)+'">'+HTMLEncode(FFeed.Name)+'</a></td>');
FReport.Add('<td>'+FormatDateTime('yyyy-mm-dd hh:nn',qrDate(qr,'created'))+'</td>');
FReport.Add('<td style="text-align:right;">'+VarToStr(qr['scount'])+'</td>');
finally
qr.Free;
end;
//check feed timing and regime
qr:=TQueryResult.Create(FDB,
'select id from "Post" where feed_id=$1 order by 1 desc limit 1 offset 200',[FFeed.id]);
try
if qr.EOF then
begin
sql1:='';
sql2:='';
end
else
begin
sql1:=' and P1.id>'+IntToStr(qr.GetInt('id'));
sql2:=' and P2.id>'+IntToStr(qr.GetInt('id'));
end;
finally
qr.Free;
end;
qr:=TQueryResult.Create(FDB,(//UTF8Encode(
'select max(X.pubdate) as postlast, avg(X.pd) as postavg'
+', min(X.pm) as postmedian'
+' from('
+' select'
+' P2.pubdate, min(P2.pubdate-P1.pubdate) as pd'
+' ,case when cume_dist()over(order by min(P2.pubdate-P1.pubdate))<0.5 then null else min(P2.pubdate-P1.pubdate) end as pm'
+' from "Post" P1'
+' inner join "Post" P2 on P2.feed_id=P1.feed_id'+sql2+' and P2.pubdate>P1.pubdate+1.0/1440.0'
+' where P1.feed_id=$1'+sql1+' and P1.pubdate>$2'
+' group by P2.pubdate'
+' ) X')
,[FFeed.id,double(oldPostDate)]);
try
if qr.EOF then
begin
postlast:=0.0;
postavg:=0.0;
end
else
begin
postlast:=qrDate(qr,'postlast');
postavg:=qrDate(qr,'postmedian');
if postavg=0.0 then postavg:=qrDate(qr,'postavg');
end;
finally
qr.Free;
end;
if postlast=0.0 then
begin
FReport.Add('<td class="empty" title="'+HTMLEncode(FFeed.LastMod0)+'"> </td>');
if FFeed.LoadLast=0.0 then
d:=FFeed.LoadStart-PubDateMargin
else
d:=FFeed.LoadLast+FFeed.Regime;
end
else
begin
FReport.Add('<td title="'+HTMLEncode(FFeed.LastMod0)+'">'+FormatDateTime('yyyy-mm-dd hh:nn',postlast)+'</td>');
d:=postlast+postavg-PubDateMargin;
if (FFeed.LoadLast<>0.0) and (d<FFeed.LoadLast) then
d:=FFeed.LoadLast+FFeed.Regime-PubDateMargin;
end;
dofeed:=(d<FFeed.LoadStart) or ForceLoadAll;
if postavg=0.0 then
FReport.Add('<td class="empty"> </td>')
else
if postavg>1.0 then
FReport.Add('<td style="text-align:right;background-color:#FFFFCC;">'+IntToStr(Round(postavg))+' days</td>')
else
FReport.Add('<td style="text-align:right;">'+IntToStr(Round(postavg*1440.0))+' mins</td>');
if FFeed.Regime=0 then
FReport.Add('<td class="empty"> </td>')
else
FReport.Add('<td style="text-align:right;">'+IntToStr(FFeed.Regime)+'</td>');
if FFeed.LoadLast=0.0 then
FReport.Add('<td class="empty"> </td><td class="empty"> </td>')
else
begin
FReport.Add('<td>'+FormatDateTime('yyyy-mm-dd hh:nn',FFeed.LoadLast)+'</td>');
f:=UtcNow-FFeed.LoadLast;
if f>1.0 then
FReport.Add('<td style="text-align:right;background-color:#FFFFCC;">'+IntToStr(Round(f))+' days</td>')
else
FReport.Add('<td style="text-align:right;">'+IntToStr(Round(f*1440.0))+' mins</td>');
end;
//proceed with this feed?
if dofeed then
begin
//load feed data
loadext:=FileExists('feeds\'+Format('%.4d',[FFeed.id])+'.txt');
try
//TODO: move these into specific feed handlers
if (FFeed.Result0<>'') and (FFeed.Result0[1]='[') then
FFeed.Result0:='';
if (FFeed.Result0='') and StartsWithX(FFeed.URL,YoutubePrefix1,ss) then
FFeed.URL:=YoutubePrefix2+ss;
if StartsWith(FFeed.URL,'https://www.instagram.com/') then
begin
{
i:=cardinal(GetTickCount-InstagramDelayMS);
j:=InstagramDelaySecs[InstagramHot];
if i<j*1000 then
begin
Writeln('');
while i<j*1000 do
begin
Write(#13'Instagram delay '+IntToStr(j-(i div 1000))+'s... ');
Sleep(10);
i:=cardinal(GetTickCount-InstagramDelayMS);
end;
Write(#13'[Instagram delay...]');
end;
}
if (FFeed.URL<>'') and (FFeed.URL[Length(FFeed.URL)]<>'/') then
FFeed.URL:=FFeed.URL+'/';
if EaterGram=nil then
EaterGram:=CoEaterGram.Create;
FeedData:=EaterGram.LoadData(FFeed.URL);
FeedDataType:='applicaton/json';
if SaveData then
SaveUTF16('xmls\'+Format('%.4d',[FFeed.ID])+'.json',FeedData);
end
else
if loadext then
begin
FeedData:=LoadExternal(FFeed.URL,
'xmls\'+Format('%.4d',[FFeed.id])+'.xml',
FFeed.LastMod,
'application/rss+xml, application/atom+xml, application/xml, application/json, text/xml');
FeedDataType:=ParseExternalHeader(FeedData);
end
else
begin
redirCount:=0;
doreq:=true;
while doreq do
begin
doreq:=false;
Write(':');
r:=CoServerXMLHTTP60.Create;
if StartsWith(FFeed.URL,'sparql://') then
begin
r.open('GET','https://'+Copy(FFeed.URL,10,Length(FFeed.URL)-9)+
'?default-graph-uri=&query=PREFIX+schema%3A+<http%3A%2F%2Fschema.org%2F>%0D%0A'+
'SELECT+*+WHERE+%7B+%3Fnews+a+schema%3ANewsArticle%0D%0A.+%3Fnews+schema%3Aurl+%3Furl%0D%0A'+
'.+%3Fnews+schema%3AdatePublished+%3FpubDate%0D%0A'+
'.+%3Fnews+schema%3Aheadline+%3Fheadline%0D%0A'+
'.+%3Fnews+schema%3Adescription+%3Fdescription%0D%0A'+
'.+%3Fnews+schema%3AarticleBody+%3Fbody%0D%0A'+
'%7D+ORDER+BY+DESC%28%3FpubDate%29+LIMIT+20'
,false,EmptyParam,EmptyParam);
r.setRequestHeader('Accept','application/sparql-results+xml, application/xml, text/xml')
end
else
if StartsWith(FFeed.URL,'https://soundcloud.com/') then
begin
r.open('GET','https://api-v2.soundcloud.com/resolve?url='+
string(URLEncode(FFeed.URL))+'&client_id='+SoundCloudClientID,
false,EmptyParam,EmptyParam);
r.setRequestHeader('Accept','application/json');
end
else
begin
r.open('GET',FFeed.URL,false,EmptyParam,EmptyParam);
if Pos('sparql',FFeed.URL)<>0 then
r.setRequestHeader('Accept','application/sparql-results+xml, application/xml, text/xml')
else
r.setRequestHeader('Accept','application/rss+xml, application/atom+xml, application/xml, application/json, text/xml');
end;
r.setRequestHeader('Cache-Control','no-cache, no-store, max-age=0');
if Pos('tumblr.com',FFeed.URL)<>0 then
begin
r.setRequestHeader('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x'+
'64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36');
r.setRequestHeader('Cookie','_ga=GA1.2.23714421.1433010142; rxx=1tcxhdz'+
'ww7.1lckhv27&v=1; tmgioct=5d2ce7032975560097163000; pfg=1fd4f3446c5c'+
'c43c229f7759a039c1f03c54916c6dbe1ad54d36c333d0cf0ed4%23%7B%22eu_resi'+
'dent%22%3A1%2C%22gdpr_is_acceptable_age%22%3A1%2C%22gdpr_consent_cor'+
'e%22%3A1%2C%22gdpr_consent_first_party_ads%22%3A1%2C%22gdpr_consent_'+
'third_party_ads%22%3A1%2C%22gdpr_consent_search_history%22%3A1%2C%22'+
'exp%22%3A1594760108%2C%22vc%22%3A%22granted_vendor_oids%3D%26oath_ve'+
'ndor_list_version%3D18%26vendor_list_version%3D154%22%7D%233273090316');
end
else
r.setRequestHeader('User-Agent','FeedEater/1.1');
if StartsWith(FFeed.URL,'https://www.washingtonpost.com') then
r.setRequestHeader('Cookie','wp_gdpr=1|1');
//TODO: ...'/wp/v2/posts' param 'after' last load time?
if (FFeed.LastMod<>'') and not(ForceLoadAll) then
r.setRequestHeader('If-Modified-Since',FFeed.LastMod);
r.send(EmptyParam);
if (r.status=301) or (r.status=302) or (r.status=308) then //moved permanently
begin
FFeed.URL:=r.getResponseHeader('Location');
doreq:=true;
inc(redirCount);
if redirCount=8 then
raise Exception.Create('Maximum number of redirects reached');
end;
end;
if r.status=200 then
begin
Write(':');
FeedData:=r.responseText;
//:=r.getAllResponseHeaders;
FeedDataType:=r.getResponseHeader('Content-Type');
FFeed.LastMod:=r.getResponseHeader('Last-Modified');
r:=nil;
if SaveData then
SaveUTF16('xmls\'+Format('%.4d',[FFeed.id])+'.xml',FeedData);
end
else
if r.status=304 then
FFeed.NotModified:=true
else
FFeed.Result:='[HTTP:'+IntToStr(r.status)+']'+r.statusText;
end;
except
on e:Exception do
begin
FFeed.Result:='['+e.ClassName+']'+e.Message;
if not(loadext) and (e is EOleException)
and ((e.Message='A security error occurred')
or (e.Message='A connection with the server could not be established'))
then //TODO: e.ErrorCode=?
SaveUTF16('feeds\'+Format('%.4d',[FFeed.id])+'.txt','');
end;
end;
//global replaces
if FileExists('feeds\'+Format('%.4d',[FFeed.id])+'g.json') then
PerformGlobalReplaces(FeedData);
//content type missing? (really simple) auto-detect
if (FeedDataType='') and (Length(FeedData)>8) then
begin
i:=1;
while (i<=Length(FeedData)) and (FeedData[i]<=' ') do inc(i);
if (FeedData<>'') and ((FeedData[i]='{') or (FeedData[i]='[')) then
FeedDataType:='application/json'
else
if StartsWith(FeedData,'<?xml ') then
FeedDataType:='application/xml' //parse? xmlns? application/atom+xml? application/rss+xml?
else
FeedDataType:='text/html';//enables search for <link>s below
end;
//any new data?
if FFeed.NotModified then
begin
FFeed.Result:=FFeed.Result+' [HTTP 304]';
if not loadext then Writeln(' HTTP 304');
end
else
begin
if (FFeed.Result='') and (FeedData='') then FFeed.Result:='[NoData]';
//process feed data
if FFeed.Result='' then
try
FPostsTotal:=0;//see CheckNewPost
FPostsNew:=0;//see RegisterPost
SanitizeContentType(FeedDataType);
SanitizeUnicode(FeedData);
//TODO: "Feed".flags?
if FileExists('feeds\'+Format('%.4d',[FFeed.id])+'ws.txt') then
begin
i:=1;
while (i<=Length(FeedData)) and (word(FeedData[i])<=32) do inc(i);
if i<>1 then FeedData:=Copy(FeedData,i,Length(FeedData)-i+1);
end;
FHasReplaces:=FileExists('feeds\'+Format('%.4d',[FFeed.id])+'r.json');
handler_i:=0;
while handler_i<FeedProcessorsIndex do
begin
if FeedProcessors[handler_i].Determine(
Self,FFeed.URL,FeedData,FeedDataType) then
begin
FeedProcessors[handler_i].ProcessFeed(Self,FeedData);
//assert FFeed.Result set by ReportSuccess or ReportFailure
handler_i:=FeedProcessorsIndex;
end
else
inc(handler_i);
end;
//nothing yet? process as XML
if FFeed.Result='' then
begin
doc:=CoDOMDocument60.Create;
doc.async:=false;
doc.validateOnParse:=false;
doc.resolveExternals:=false;
doc.preserveWhiteSpace:=true;
doc.setProperty('ProhibitDTD',false);
xres:=doc.loadXML(FeedData);
//fix Mashable (grr!)
if not(xres) then
xres:=FixUndeclNSPrefix(doc,FeedData);
//fix floating nbsp's
if not(xres) and (Pos('''nbsp''',string(doc.parseError.reason))<>0) then
FixNBSP(doc,FeedData);
if xres then
begin
handler_i:=0;
while handler_i<FeedProcessorsXMLIndex do
begin
if FeedProcessorsXML[handler_i].Determine(doc) then
begin
FeedProcessorsXML[handler_i].ProcessFeed(Self,doc);
//assert FFeed.Result set by ReportSuccess or ReportFailure
handler_i:=FeedProcessorsXMLIndex;
end
else
inc(handler_i);
end;
//still nothing?
if FFeed.Result='' then
if not((FeedDataType='text/html') and FindFeedURL(FeedData)) then
FFeed.Result:='Unkown "'+doc.documentElement.tagName+'" ('
+FeedDataType+')';
end
else
begin
if FeedData='' then
FFeed.Result:='[No Data]'
else
//XML parse failed
if not((FeedDataType='text/html') and FindFeedURL(FeedData)) then
FFeed.Result:='[XML'+IntToStr(doc.parseError.line)+':'+
IntToStr(doc.parseError.linepos)+']'+doc.parseError.Reason;
end;
//
end;
inc(Result.FeedCount);
inc(Result.PostCount,FPostsNew);
inc(FFeed.TotalCount,FPostsNew);
except
on e:Exception do
FFeed.Result:='['+e.ClassName+']'+e.Message;
end;
//update feed data if any changes
if (FFeed.Result<>'') and (FFeed.Result[1]='[') then
begin
ErrLn('!!! '+FFeed.Result);
end
else
begin
//stale? update regime
if (FPostsNew=0) and (FPostsTotal>FFeed.Regime*2+5) then
begin
i:=0;
if FFeed.Regime>=0 then
begin
while (i<regimesteps) and (FFeed.Regime>=regimestep[i]) do inc(i);
if (i<regimesteps) and ((postlast=0.0)
or (postlast+regimestep[i]*2<FFeed.LoadStart)) then
begin
FFeed.Result:=FFeed.Result+' (stale? r:'+IntToStr(FFeed.Regime)+
'->'+IntToStr(regimestep[i])+')';
FFeed.Regime:=regimestep[i];
end;
end;
end
else
begin
//not stale: update regime to apparent post average period
if FFeed.Regime<>0 then
begin
i:=regimesteps;
while (i<>0) and (postavg<regimestep[i-1]) do dec(i);
if i=0 then FFeed.Regime:=0 else FFeed.Regime:=regimestep[i-1];
end;
end;
Writeln(' '+FFeed.Result);
end;
FDB.BeginTrans;
try
if FFeed.Name='' then
begin
i:=5;
while (i<=Length(FFeed.URL)) and (FFeed.URL[i]<>':') do inc(i);
inc(i);
if (i<=Length(FFeed.URL)) and (FFeed.URL[i]='/') then inc(i);
if (i<=Length(FFeed.URL)) and (FFeed.URL[i]='/') then inc(i);
FFeed.Name:='['+Copy(FFeed.URL,i,Length(FFeed.URL)-i+1);
i:=2;
while (i<=Length(FFeed.Name)) and (FFeed.Name[i]<>'/') do inc(i);
SetLength(FFeed.Name,i);
FFeed.Name[i]:=']';
end;
if newfeed or
(FFeed.URL<>FFeed.URL0) or (FFeed.Name<>FFeed.Name0) then
begin
FDB.Update('Feed',
['id',FFeed.id
,'name',FFeed.Name
,'url',FFeed.URL
,'loadlast',double(FFeed.LoadStart)
,'result',FFeed.Result
,'loadcount',FPostsNew
,'itemcount',FPostsTotal
,'totalcount',FFeed.TotalCount
,'regime',FFeed.Regime
]);
if (@OnFeedURLUpdate<>nil) and (FFeed.URL<>FFeed.URL0) then
OnFeedURLUpdate(Self);
end
else
FDB.Update('Feed',
['id',FFeed.id
,'loadlast',double(FFeed.LoadStart)
,'result',FFeed.Result
,'loadcount',FPostsNew
,'itemcount',FPostsTotal
,'totalcount',FFeed.TotalCount
,'regime',FFeed.Regime
]);
if FFeed.LastMod<>FFeed.LastMod0 then
FDB.Update('Feed',
['id',FFeed.id
,'lastmod',FFeed.LastMod
]);
FDB.CommitTrans;
except
FDB.RollbackTrans;
raise;
end;
end;
end
else
begin
//feed not loaded now
Writeln(' Skip '+FeedSkipDisplay(d));
FFeed.Result:=FFeed.Result0;
//postsTotal,postsNew see above
FFeed.LoadStart:=FFeed.LoadLast;
end;
if (FFeed.Result<>'') and (FFeed.Result[1]='[') then
FReport.Add('<td style="color:#CC0000;">'+HTMLEncode(FFeed.Result)+'</td>')
else
FReport.Add('<td>'+HTMLEncode(FFeed.Result)+'</td>');
if FPostsTotal=0 then
FReport.Add('<td class="empty"> </td>')
else
FReport.Add('<td style="text-align:right;">'+IntToStr(FPostsTotal)+'</td>');
FReport.Add('<td style="text-align:right;" title="'+FormatDateTime('yyyy-mm-dd hh:nn:ss',FFeed.LoadStart)
+#13#10+HTMLEncode(FFeed.LastMod)+'">'+IntToStr(FPostsNew)+'</td>');
FReport.Add('<td style="text-align:right;">'+IntToStr(FFeed.TotalCount)+'</td>');
FReport.Add('</tr>');
inc(ids_i);
end;
OutLn(Format('Loaded: %d posts from %d feeds',
[Result.PostCount,Result.FeedCount]));
FReport.Add('</table>');
qr:=TQueryResult.Create(FDBStats,
'select ((select count(*) from "Post")+500)/1000||''K posts, '''
+'||((select count(*) from "UserPost")+500)/1000||''K unread, '''
+'||pg_database_size(''feeder'')/1024000||''MB, '''
+'||version()',[]);
try
while qr.Read do
FReport.Add('<p>'+HTMLEncode(qr.GetStr(0))+'</p>');
finally
qr.Free;
end;
FReport.SaveToFile(FeedLoadReport);
except
on e:Exception do
begin
ErrLn('['+e.ClassName+']'+e.Message);
ExitCode:=1;
end;
end;
end;
function TFeedEater.CheckLastLoadResultPrefix(const Prefix: string): boolean;
begin
Result:=(FFeed.Result0='') or StartsWith(FFeed.Result0,Prefix);
end;
function TFeedEater.CheckNewPost(const PostID: string; const PostURL: WideString;
PostPubDate: TDateTime): boolean;
var
qr:TQueryResult;
i:integer;
s:string;
begin
FPostID:=PostID;
FPostURL:=PostURL;
FPostPubDate:=PostPubDate;
FPostTags:=Null;
FPostTagPrefix:='';
if FPostURL='' then FPostURL:=FPostID;
if FPostID='' then FPostID:=FPostURL;
if StartsWithX(FPostID,'http://',s) then
FPostID:=s
else
if StartsWithX(FPostID,'https://',s) then
FPostID:=s;
SanitizePostID(FPostID);
if FFeed.URLSkip<>'' then
begin
i:=Pos(FFeed.URLSkip,FPostID);
if i<>0 then FPostID:=Copy(FPostID,1,i-1);
end;
//TODO: if feed_flag_trim in feed_flags?
FPostURL:=SanitizeTrim(FPostURL);
//relative url
if (FPostURL<>'') and not(StartsWith(FPostURL,'http')) then
if FPostURL[1]='/' then
begin
i:=5;
while (i<=Length(FFeed.URL)) and (FFeed.URL[i]<>':') do inc(i);
inc(i);
if (i<=Length(FFeed.URL)) and (FFeed.URL[i]='/') then inc(i);
if (i<=Length(FFeed.URL)) and (FFeed.URL[i]='/') then inc(i);
while (i<=Length(FFeed.URL)) and (FFeed.URL[i]<>'/') do inc(i);
FPostURL:=Copy(FFeed.URL,1,i-1)+FPostURL;
end
else
begin
i:=Length(FFeed.URL);
while (i<>0) and (FFeed.URL[i]<>'/') do dec(i);
FPostURL:=Copy(FFeed.URL,1,i)+FPostURL;
end;
//TODO: switch: allow future posts?
if FPostPubDate>FFeed.LoadStart+2.0/24.0 then
FPostPubDate:=FFeed.LoadStart;
inc(FPostsTotal);
//check age, blacklist, already listed
Result:=FPostPubDate>=OldPostsCutOff;
i:=0;
while Result and (i<BlackList.Count) do
if (BlackList[i]<>'') and (blacklist[i]=Copy(FPostURL,1,Length(BlackList[i]))) then
Result:=false
else
inc(i);
if Result then
begin
if FFeed.group_id<>0 then
qr:=TQueryResult.Create(FDB,
'select P.id from "Post" P'
+' inner join "Feed" F on F.id=P.feed_id'
+' and F.group_id=$1'
+' where P.guid=$2'
,[FFeed.group_id,FPostID])
else
qr:=TQueryResult.Create(FDB,
'select id from "Post" where feed_id=$1 and guid=$2'
,[FFeed.id,FPostID]);
try
Result:=qr.EOF;
//TODO: if FFeed.group_id<>0 and P.feed_id>FFeed.id then update?
finally
qr.Free;
end;
end;
end;
procedure TFeedEater.UpdateFeedName(const NewName:string);