-
Notifications
You must be signed in to change notification settings - Fork 227
/
RefreshManager.m
1269 lines (1139 loc) · 55.6 KB
/
RefreshManager.m
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
//
// RefreshManager.m
// Vienna
//
// Created by Steve on 7/19/05.
// Copyright (c) 2004-2018 Steve Palmer and Vienna contributors (see menu item 'About Vienna' for list of contributors). All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "RefreshManager.h"
@import os.log;
#import "FeedCredentials.h"
#import "ActivityItem.h"
#import "ActivityLog.h"
#import "StringExtensions.h"
#import "Preferences.h"
#import "Constants.h"
#import "OpenReader.h"
#import "NSNotificationAdditions.h"
#import "Article.h"
#import "Folder.h"
#import "Database.h"
#import "TRVSURLSessionOperation.h"
#import "URLRequestExtensions.h"
#import "Vienna-Swift.h"
#import "XMLFeed.h"
#import "XMLFeedParser.h"
typedef NS_ENUM (NSInteger, Redirect301Status) {
HTTP301Unknown = 0,
HTTP301Pending,
HTTP301Unsafe,
HTTP301Safe
};
#define VNA_LOG os_log_create("--", "RefreshManager")
@interface RefreshManager ()
@property (readwrite, copy) NSString * statusMessage;
@property (nonatomic) NSTimer * unsafe301RedirectionTimer;
@property (copy) NSString * riskyIPAddress;
@property (nonatomic) Redirect301Status redirect301Status;
@property (nonatomic) NSMutableArray * redirect301WaitQueue;
@property (nonatomic, readonly) NSURLSession * urlSession;
-(BOOL)isRefreshingFolder:(Folder *)folder ofType:(RefreshTypes)type;
-(void)getCredentialsForFolder;
-(void)setFolderErrorFlag:(Folder *)folder flag:(BOOL)theFlag;
-(void)setFolderUpdatingFlag:(Folder *)folder flag:(BOOL)theFlag;
-(void)pumpSubscriptionRefresh:(Folder *)folder shouldForceRefresh:(BOOL)force;
-(void)pumpFolderIconRefresh:(Folder *)folder;
-(void)refreshFeed:(Folder *)folder fromURL:(NSURL *)url withLog:(ActivityItem *)aItem shouldForceRefresh:(BOOL)force;
-(NSString *)getRedirectURL:(NSData *)data;
-(void)syncFinishedForFolder:(Folder *)folder;
@end
@implementation RefreshManager {
NSUInteger countOfNewArticles;
NSMutableArray *authQueue;
FeedCredentials *credentialsController;
BOOL hasStarted;
NSString *statusMessageDuringRefresh;
NSOperationQueue *networkQueue;
dispatch_queue_t _queue;
}
+(void)initialize
{
}
/* init
* Initialise the class.
*/
-(instancetype)init
{
if ((self = [super init]) != nil) {
countOfNewArticles = 0;
authQueue = [[NSMutableArray alloc] init];
statusMessageDuringRefresh = nil;
networkQueue = [[NSOperationQueue alloc] init];
networkQueue.name = @"VNAHTTPSession queue";
networkQueue.maxConcurrentOperationCount = [[Preferences standardPreferences] integerForKey:MAPref_ConcurrentDownloads];
NSString * osVersion;
NSOperatingSystemVersion version = [NSProcessInfo processInfo].operatingSystemVersion;
osVersion = [NSString stringWithFormat:@"%ld_%ld_%ld", version.majorVersion, version.minorVersion, version.patchVersion];
Preferences * prefs = [Preferences standardPreferences];
NSString *name = prefs.userAgentName;
NSString * userAgent = [NSString stringWithFormat:MA_DefaultUserAgentString, name, [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"], osVersion];
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.timeoutIntervalForResource = 300;
config.HTTPAdditionalHeaders = @{@"User-Agent": userAgent};
config.HTTPMaximumConnectionsPerHost = 6;
config.HTTPShouldUsePipelining = YES;
_urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(handleGotAuthenticationForFolder:) name:MA_Notify_GotAuthenticationForFolder object:nil];
[nc addObserver:self selector:@selector(handleCancelAuthenticationForFolder:) name:MA_Notify_CancelAuthenticationForFolder
object:nil];
[nc addObserver:self selector:@selector(handleWillDeleteFolder:) name:VNADatabaseWillDeleteFolderNotification object:nil];
[nc addObserver:self selector:@selector(handleChangeConcurrentDownloads:) name:MA_Notify_ConcurrentDownloadsChange object:nil];
// be notified on system wake up after sleep
[[NSWorkspace sharedWorkspace].notificationCenter addObserver:self selector:@selector(handleDidWake:)
name:@"NSWorkspaceDidWakeNotification" object:nil];
_queue = dispatch_queue_create("uk.co.opencommunity.vienna2.refresh", NULL);
_redirect301WaitQueue = [[NSMutableArray alloc] init];
hasStarted = NO;
}
return self;
} // init
/* sharedManager
* Returns the single instance of the refresh manager.
*/
+(RefreshManager *)sharedManager
{
// Singleton
static RefreshManager * _refreshManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_refreshManager = [[RefreshManager alloc] init];
});
return _refreshManager;
}
-(void)handleChangeConcurrentDownloads:(NSNotification *)nc
{
NSLog(@"Handling new downloads count");
networkQueue.maxConcurrentOperationCount = [[Preferences standardPreferences] integerForKey:MAPref_ConcurrentDownloads];
}
/* handleWillDeleteFolder
* Trap the notification that is broadcast just before a folder is being deleted.
* We use this to remove that folder from the refresh queue, if it is present, and
* interrupt a connection on that folder. Otherwise our retain on the folder will
* prevent it from being fully released until the end of the refresh by which time
* the folder list pane will probably have completed its post delete update.
*/
-(void)handleWillDeleteFolder:(NSNotification *)nc
{
Folder * folder = [[Database sharedManager] folderFromID:[nc.object integerValue]];
if (folder != nil) {
for (TRVSURLSessionOperation *theRequest in networkQueue.operations) {
NSMutableURLRequest *urlRequest = (NSMutableURLRequest *)(theRequest.task.originalRequest);
if (((NSDictionary *)[urlRequest vna_userInfo])[@"folder"] == folder) {
[theRequest.task cancel];
break;
}
}
}
}
-(void)handleDidWake:(NSNotification *)nc
{
NSString * currentAddress = [NSHost currentHost].address;
if (![currentAddress isEqualToString:self.riskyIPAddress]) {
// we might have moved to a new network
// so, at the next occurence we should test if we can safely handle
// 301 redirects
self.redirect301Status = HTTP301Unknown;
[self.unsafe301RedirectionTimer invalidate];
self.unsafe301RedirectionTimer = nil;
}
}
/* handleGotAuthenticationForFolder [delegate]
* Called when somewhere just provided us the needed authentication for the specified
* folder. Note that we don't know if the authentication is valid yet - just that a
* user name and password has been provided.
*/
-(void)handleGotAuthenticationForFolder:(NSNotification *)nc
{
Folder * folder = (Folder *)nc.object;
[[Database sharedManager] clearFlag:VNAFolderFlagNeedCredentials forFolder:folder.itemId];
[authQueue removeObject:folder];
[self refreshSubscriptions:@[folder] ignoringSubscriptionStatus:YES];
// Get the next one in the queue, if any
[self getCredentialsForFolder];
}
/* handleCancelAuthenticationForFolder
* Called when somewhere cancelled our request to authenticate the specified
* folder.
*/
-(void)handleCancelAuthenticationForFolder:(NSNotification *)nc
{
Folder * folder = (Folder *)nc.object;
[authQueue removeObject:folder];
// Get the next one in the queue, if any
[self getCredentialsForFolder];
}
-(void)forceRefreshSubscriptionForFolders:(NSArray *)foldersArray
{
statusMessageDuringRefresh = NSLocalizedString(@"Forcing Refresh subscriptions…", nil);
for (Folder * folder in foldersArray) {
if (folder.type == VNAFolderTypeGroup) {
[self forceRefreshSubscriptionForFolders:[[Database sharedManager] arrayOfFolders:folder.itemId]];
} else if (folder.type == VNAFolderTypeOpenReader) {
if (![self isRefreshingFolder:folder ofType:MA_Refresh_GoogleFeed] &&
![self isRefreshingFolder:folder ofType:MA_ForceRefresh_Google_Feed])
{
[self pumpSubscriptionRefresh:folder shouldForceRefresh:YES];
}
}
}
}
/* refreshSubscriptions
* Add the folders specified in the foldersArray to the refresh queue.
*/
-(void)refreshSubscriptions:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus
{
statusMessageDuringRefresh = NSLocalizedString(@"Refreshing subscriptions…", nil);
for (Folder * folder in foldersArray) {
if (folder.isGroupFolder) {
[self refreshSubscriptions:[[Database sharedManager] arrayOfFolders:folder.itemId] ignoringSubscriptionStatus:NO];
} else if (folder.isRSSFolder) {
if ((!folder.isUnsubscribed || ignoreSubStatus) && ![self isRefreshingFolder:folder ofType:MA_Refresh_Feed]) {
[self pumpSubscriptionRefresh:folder shouldForceRefresh:NO];
}
} else if (folder.isOpenReaderFolder) {
if ((!folder.isUnsubscribed || ignoreSubStatus) && ![self isRefreshingFolder:folder ofType:MA_Refresh_GoogleFeed] &&
![self isRefreshingFolder:folder ofType:MA_ForceRefresh_Google_Feed])
{
// we depend of pieces of info gathered by loadSubscriptions
NSOperation * op = [NSBlockOperation blockOperationWithBlock:^(void) {
if (folder.isSyncedOK) { // provide feedback that there is no need to fetch this feed
NSString * name = [folder.name hasPrefix:[Database untitledFeedFolderName]] ? folder.feedURL : folder.name;
ActivityItem * aItem = [[ActivityLog defaultLog] itemByName:name];
[aItem setStatus:NSLocalizedString(@"No new articles available", nil)];
[aItem clearDetails];
[self setFolderErrorFlag:folder flag:NO];
[folder clearNonPersistedFlag:VNAFolderFlagSyncedOK]; // get ready for next request
} else {
[self pumpSubscriptionRefresh:folder shouldForceRefresh:NO];
}
}];
NSOperation * unreadCountOperation = [OpenReader sharedManager].unreadCountOperation;
if (unreadCountOperation != nil && !unreadCountOperation.isFinished) {
[op addDependency:unreadCountOperation];
}
[[NSOperationQueue mainQueue] addOperation:op];
}
}
}
} // refreshSubscriptions
/* refreshFolderIconCacheForSubscriptions
* Add the folders specified in the foldersArray to the refresh queue.
*/
-(void)refreshFolderIconCacheForSubscriptions:(NSArray *)foldersArray
{
statusMessageDuringRefresh = NSLocalizedString(@"Refreshing folder images…", nil);
for (Folder * folder in foldersArray) {
if (folder.type == VNAFolderTypeGroup) {
[self refreshFolderIconCacheForSubscriptions:[[Database sharedManager] arrayOfFolders:folder.itemId]];
} else if (folder.type == VNAFolderTypeRSS || folder.type == VNAFolderTypeOpenReader) {
[self refreshFavIconForFolder:folder];
}
}
}
/* refreshFavIconForFolder
* Adds the specified folder to the refresh queue.
*/
/**
* Refreshes the favicon for the specified folder
*
* @param folder The folder object to refresh the favicon for
*/
-(void)refreshFavIconForFolder:(Folder *)folder
{
// Do nothing if there's no homepage associated with the feed
// or if the feed already has a favicon.
if ((folder.type == VNAFolderTypeRSS || folder.type == VNAFolderTypeOpenReader) &&
(folder.homePage == nil || folder.homePage.vna_isBlank || folder.hasCachedImage))
{
[[Database sharedManager] clearFlag:VNAFolderFlagCheckForImage forFolder:folder.itemId];
return;
}
if (![self isRefreshingFolder:folder ofType:MA_Refresh_FavIcon]) {
[self pumpFolderIconRefresh:folder];
}
}
/* isRefreshingFolder
* Returns whether refresh queue has a queue item for the specified folder
* and refresh type.
*/
-(BOOL)isRefreshingFolder:(Folder *)folder ofType:(RefreshTypes)type
{
for (TRVSURLSessionOperation *theRequest in networkQueue.operations) {
NSMutableURLRequest *urlRequest = (NSMutableURLRequest *)(theRequest.task.originalRequest);
if ((((NSDictionary *)[urlRequest vna_userInfo])[@"folder"] == folder) &&
([[((NSDictionary *)[urlRequest vna_userInfo]) valueForKey:@"type"] integerValue] == @(type).integerValue))
{
return YES;
}
}
return NO;
}
/* cancelAll
* Cancel all active refreshes.
*/
-(void)cancelAll
{
[networkQueue cancelAllOperations];
}
/* countOfNewArticles
*/
-(NSUInteger)countOfNewArticles
{
return countOfNewArticles;
}
/* getCredentialsForFolder
* Initiate the UI to request the credentials for the specified folder.
*/
-(void)getCredentialsForFolder
{
if (credentialsController == nil) {
credentialsController = [[FeedCredentials alloc] init];
}
// Pull next folder out of the queue. The UI will post a
// notification when it is done and we can move on to the
// next one.
if (authQueue.count > 0 && !credentialsController.window.visible) {
Folder * folder = authQueue[0];
[credentialsController requestCredentialsInWindow:NSApp.mainWindow forFolder:folder];
}
}
/* setFolderErrorFlag
* Sets or clears the folder error flag then broadcasts an update indicating that the folder
* has changed.
*/
-(void)setFolderErrorFlag:(Folder *)folder flag:(BOOL)theFlag
{
if (theFlag) {
[folder setNonPersistedFlag:VNAFolderFlagError];
} else {
[folder clearNonPersistedFlag:VNAFolderFlagError];
}
[[NSNotificationCenter defaultCenter] vna_postNotificationOnMainThreadWithName:MA_Notify_FoldersUpdated object:@(folder.itemId)];
}
/* setFolderUpdatingFlag
* Sets or clears the folder updating flag then broadcasts an update indicating that the folder
* has changed.
*/
-(void)setFolderUpdatingFlag:(Folder *)folder flag:(BOOL)theFlag
{
if (theFlag) {
[folder setNonPersistedFlag:VNAFolderFlagUpdating];
} else {
[folder clearNonPersistedFlag:VNAFolderFlagUpdating];
}
[[NSNotificationCenter defaultCenter] vna_postNotificationOnMainThreadWithName:MA_Notify_FoldersUpdated object:@(folder.itemId)];
}
/* pumpFolderIconRefresh
* Initiate a connect to refresh the icon for a folder.
*/
-(void)pumpFolderIconRefresh:(Folder *)folder
{
// The activity log name we use depends on whether or not this folder has a real name.
NSString * name = [folder.name hasPrefix:[Database untitledFeedFolderName]] ? folder.feedURL : folder.name;
ActivityItem *aItem = [[ActivityLog defaultLog] itemByName:name];
NSString * favIconPath;
if (folder.type == VNAFolderTypeRSS) {
[aItem appendDetail:NSLocalizedString(@"Retrieving folder image", nil)];
favIconPath = [NSString stringWithFormat:@"%@/favicon.ico", folder.homePage.vna_trimmed.vna_baseURL];
} else { // Open Reader feed
[aItem appendDetail:NSLocalizedString(@"Retrieving folder image for Open Reader Feed", nil)];
favIconPath = [NSString stringWithFormat:@"%@/favicon.ico", folder.homePage.vna_trimmed.vna_baseURL];
}
NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:favIconPath]];
__weak typeof(self)weakSelf = self;
[self addConnection:myRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
[aItem appendDetail:[NSString stringWithFormat:@"%@ %@",
NSLocalizedString(@"Error retrieving RSS Icon:", nil), error.localizedDescription ]];
[[Database sharedManager] clearFlag:VNAFolderFlagCheckForImage forFolder:folder.itemId];
} else {
[weakSelf setFolderUpdatingFlag:folder flag:NO];
if (((NSHTTPURLResponse *)response).statusCode == 404) {
[aItem appendDetail:NSLocalizedString(@"RSS Icon not found!", nil)];
} else if (((NSHTTPURLResponse *)response).statusCode == 200) {
NSImage *iconImage = [[NSImage alloc] initWithData:data];
if (iconImage != nil && iconImage.valid) {
iconImage.size = NSMakeSize(16, 16);
folder.image = iconImage;
// Broadcast a notification since the folder image has now changed
[[NSNotificationCenter defaultCenter] vna_postNotificationOnMainThreadWithName:MA_Notify_FoldersUpdated
object:@(folder.itemId)];
// Log additional details about this.
[aItem appendDetail:[NSString stringWithFormat:NSLocalizedString(@"Folder image retrieved from %@",
nil), myRequest.URL]];
NSString * byteCount = [NSByteCountFormatter stringFromByteCount:(long long)data.length
countStyle:NSByteCountFormatterCountStyleFile];
[aItem appendDetail:[NSString stringWithFormat:NSLocalizedString(@"%@ received",
@"Number of bytes received, e.g. 1 MB received"),
byteCount]];
} else {
[aItem appendDetail:NSLocalizedString(@"RSS Icon not found!", nil)];
}
} else {
[aItem appendDetail:[NSString stringWithFormat:NSLocalizedString(@"HTTP code %d reported from server",
nil), (int)((NSHTTPURLResponse *)response).statusCode]];
}
[[Database sharedManager] clearFlag:VNAFolderFlagCheckForImage forFolder:folder.itemId];
}
}];
} // pumpFolderIconRefresh
#pragma mark Core of feed refresh
/* pumpSubscriptionRefresh
* Pick the folder at the head of the refresh queue and spawn a connection to
* refresh that folder.
*/
-(void)pumpSubscriptionRefresh:(Folder *)folder shouldForceRefresh:(BOOL)force
{
// If this folder needs credentials, add the folder to the list requiring authentication
// and since we can't progress without it, skip this folder on the connection
if (folder.flags & VNAFolderFlagNeedCredentials) {
[authQueue addObject:folder];
[self getCredentialsForFolder];
return;
}
// The activity log name we use depends on whether or not this folder has a real name.
NSString * name = [folder.name hasPrefix:[Database untitledFeedFolderName]] ? folder.feedURL : folder.name;
ActivityItem * aItem = [[ActivityLog defaultLog] itemByName:name];
// Compute the URL for this connection
NSString * urlString = folder.feedURL;
NSURL * url = nil;
if ([urlString hasPrefix:@"file://"]) {
url = [NSURL fileURLWithPath:[urlString substringFromIndex:7].stringByExpandingTildeInPath];
} else if ([urlString hasPrefix:@"feed://"]) {
url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", [urlString substringFromIndex:7]]];
} else {
url = [NSURL URLWithString:urlString];
}
// Seed the activity log for this feed.
[aItem clearDetails];
[aItem setStatus:NSLocalizedString(@"Retrieving articles", nil)];
// Mark the folder as being refreshed. The updating status is not
// persistent so we set this directly on the folder rather than
// through the database.
[self setFolderUpdatingFlag:folder flag:YES];
// Additional detail for the log
if (folder.type == VNAFolderTypeOpenReader) {
[aItem appendDetail:[NSString stringWithFormat:NSLocalizedString(@"Connecting to Open Reader server to retrieve %@", nil),
urlString]];
} else {
[aItem appendDetail:[NSString stringWithFormat:NSLocalizedString(@"Connecting to %@", nil), urlString]];
}
// Kick off the connection
[self refreshFeed:folder fromURL:url withLog:aItem shouldForceRefresh:force];
} // pumpSubscriptionRefresh
/* refreshFeed
* Refresh a folder's newsfeed using the specified URL.
*/
-(void)refreshFeed:(Folder *)folder fromURL:(NSURL *)url withLog:(ActivityItem *)aItem shouldForceRefresh:(BOOL)force
{
NSMutableURLRequest *myRequest;
if (folder.type == VNAFolderTypeRSS) {
myRequest = [NSMutableURLRequest requestWithURL:url];
NSString * theLastUpdateString = folder.lastUpdateString;
if (![theLastUpdateString isEqualToString:@""]) {
[myRequest setValue:theLastUpdateString forHTTPHeaderField:@"If-Modified-Since"];
[myRequest setValue:@"feed" forHTTPHeaderField:@"A-IM"];
}
[myRequest vna_setUserInfo:@{ @"folder": folder, @"log": aItem, @"type": @(MA_Refresh_Feed) }];
[myRequest addValue:
@"application/rss+xml,application/rdf+xml,application/atom+xml,text/xml,application/xml,application/xhtml+xml,application/feed+json,application/json;q=0.9,text/html;q=0.8,*/*;q=0.5"
forHTTPHeaderField:@"Accept"];
// if authentication infos are present, try basic authentication first
if (![folder.username isEqualToString:@""]) {
NSString* usernameAndPassword = [NSString vna_toBase64String:[NSString stringWithFormat:@"%@:%@", folder.username, folder.password]];
[myRequest setValue:[NSString stringWithFormat:@"Basic %@", usernameAndPassword] forHTTPHeaderField:@"Authorization"];
}
__weak typeof(self)weakSelf = self;
[self addConnection:myRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
[weakSelf folderRefreshFailed:myRequest error:error];
} else {
[weakSelf folderRefreshCompleted:myRequest response:response data:data];
}
}];
} else { // Open Reader feed
[[OpenReader sharedManager] refreshFeed:folder withLog:(ActivityItem *)aItem shouldIgnoreArticleLimit:force];
}
if (!hasStarted) {
hasStarted = YES;
countOfNewArticles = 0;
[[OpenReader sharedManager] resetCountOfNewArticles];
[[NSNotificationCenter defaultCenter] postNotificationName:MA_Notify_RefreshStatus object:nil];
}
} // refreshFeed
// failure callback
-(void)folderRefreshFailed:(NSMutableURLRequest *)request error:(NSError *)error
{
os_log_debug(VNA_LOG, "Refresh of %@ failed. Reason: %{public}@", error.userInfo[NSURLErrorFailingURLStringErrorKey], error.localizedDescription);
Folder * folder = ((NSDictionary *)[request vna_userInfo])[@"folder"];
if (error.code == NSURLErrorCancelled) {
// Stopping the connection isn't an error, so clear any existing error flag.
[self setFolderErrorFlag:folder flag:NO];
// If this folder also requires an image refresh, add that
if ((folder.flags & VNAFolderFlagCheckForImage)) {
[self refreshFavIconForFolder:folder];
}
} else if (error.code == NSURLErrorUserAuthenticationRequired) { //Error caused by lack of authentication
if (![authQueue containsObject:folder]) {
[authQueue addObject:folder];
}
[self getCredentialsForFolder];
}
ActivityItem *aItem = (ActivityItem *)((NSDictionary *)[request vna_userInfo])[@"log"];
[self setFolderErrorFlag:folder flag:YES];
[aItem appendDetail:[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Error retrieving RSS feed:", nil),
error.localizedDescription ]];
[aItem setStatus:NSLocalizedString(@"Error", nil)];
[self syncFinishedForFolder:folder];
} // folderRefreshFailed
/* folderRefreshCompleted
* Called when a folder refresh completed.
*/
-(void)folderRefreshCompleted:(NSMutableURLRequest *)connector response:(NSURLResponse *)response data:(NSData *)receivedData
{
dispatch_async(_queue, ^() {
// TODO : refactor code to separate feed refresh code and UI
Folder * folder = (Folder *)((NSDictionary *)[connector vna_userInfo])[@"folder"];
ActivityItem *connectorItem = ((NSDictionary *)[connector vna_userInfo])[@"log"];
NSURL * url = connector.URL;
NSInteger folderId = folder.itemId;
Database *dbManager = [Database sharedManager];
NSInteger responseStatusCode;
NSString * lastModifiedString;
// hack for handling file:// URLs
if (url.fileURL) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString * filePath = [url.path stringByRemovingPercentEncoding];
BOOL isDirectory = NO;
if ([fileManager fileExistsAtPath:filePath isDirectory:&isDirectory] && !isDirectory) {
responseStatusCode = 200;
lastModifiedString = [[fileManager attributesOfItemAtPath:filePath error:nil] fileModificationDate].description;
} else {
responseStatusCode = 404;
}
} else {
responseStatusCode = ((NSHTTPURLResponse *)response).statusCode;
lastModifiedString = SafeString([((NSHTTPURLResponse *)response).allHeaderFields valueForKey:@"Last-Modified"]);
}
if (responseStatusCode == 304) {
// No modification from last check
[self setFolderErrorFlag:folder flag:NO];
[connectorItem appendDetail:NSLocalizedString(@"Got HTTP status 304 - No news from last check", nil)];
dispatch_async(dispatch_get_main_queue(), ^{
[connectorItem setStatus:NSLocalizedString(@"No new articles available", nil)];
[self syncFinishedForFolder:folder];
});
return;
} else if (responseStatusCode == 410) {
// We got HTTP 410 which means the feed has been intentionally removed so unsubscribe the feed.
[dbManager setFlag:VNAFolderFlagUnsubscribed forFolder:folderId];
} else if (responseStatusCode == 200 || responseStatusCode == 226) {
if (receivedData != nil) {
[self finalizeFolderRefresh:@{
@"folder": folder,
@"log": connectorItem,
@"url": url,
@"data": receivedData,
@"mimeType": SafeString(response.MIMEType),
@"lastModifiedString": lastModifiedString,
}];
}
} else { //other HTTP response codes like 404, 403...
[connectorItem appendDetail:[NSString stringWithFormat:NSLocalizedString(@"HTTP code %d reported from server", nil),
(int)responseStatusCode]];
[connectorItem appendDetail:[NSHTTPURLResponse localizedStringForStatusCode:responseStatusCode]];
dispatch_async(dispatch_get_main_queue(), ^{
[connectorItem setStatus:NSLocalizedString(@"Error", nil)];
});
[self setFolderErrorFlag:folder flag:YES];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self syncFinishedForFolder:folder];
});
}); //block for dispatch_async on _queue
} // folderRefreshCompleted
-(void)finalizeFolderRefresh:(NSDictionary *)parameters
{
if (!parameters) {
os_log_error(VNA_LOG, "%{public}s has no parameters", __PRETTY_FUNCTION__);
}
Folder * folder = (Folder *)parameters[@"folder"];
NSInteger folderId = folder.itemId;
Database * dbManager = [Database sharedManager];
ActivityItem *connectorItem = parameters[@"log"];
NSURL * url = parameters[@"url"];
NSData * receivedData = parameters[@"data"];
NSString * lastModifiedString = parameters[@"lastModifiedString"];
// Check whether this is an HTML redirect. If so, create a new connection using
// the redirect.
NSString * redirectURL = [self getRedirectURL:receivedData];
if (redirectURL != nil) {
if ([redirectURL isEqualToString:url.absoluteString]) {
// To prevent an infinite loop, don't redirect to the same URL.
[connectorItem appendDetail:[NSString stringWithFormat:NSLocalizedString(@"Improper infinitely looping URL redirect to %@",
nil), url.absoluteString]];
} else {
[self refreshFeed:folder fromURL:[NSURL URLWithString:redirectURL] withLog:connectorItem shouldForceRefresh:NO];
return;
}
}
// Empty data feed is OK if we got HTTP 200
__block NSUInteger newArticlesFromFeed = 0;
if (receivedData.length > 0) {
Preferences *standardPreferences = [Preferences standardPreferences];
if (standardPreferences.shouldSaveFeedSource) {
NSString * feedSourcePath = folder.feedSourceFilePath;
if ([standardPreferences boolForKey:MAPref_ShouldSaveFeedSourceBackup]) {
BOOL isDirectory = YES;
NSFileManager *defaultManager = [NSFileManager defaultManager];
if ([defaultManager fileExistsAtPath:feedSourcePath isDirectory:&isDirectory] && !isDirectory) {
NSString * backupPath = [feedSourcePath stringByAppendingPathExtension:@"bak"];
if (![defaultManager fileExistsAtPath:backupPath] || [defaultManager removeItemAtPath:backupPath error:NULL]) { // Remove any old backup first
[defaultManager moveItemAtPath:feedSourcePath toPath:backupPath error:NULL];
}
}
}
[receivedData writeToFile:feedSourcePath options:NSAtomicWrite error:NULL];
}
id<VNAFeed> newFeed;
NSError *error;
NSString *mimeType = parameters[@"mimeType"];
if ([mimeType containsString:@"application/feed+json"] ||
[mimeType containsString:@"application/json"]) {
VNAJSONFeedParser *parser = [[VNAJSONFeedParser alloc] init];
newFeed = [parser feedWithJSONData:receivedData error:&error];
} else {
VNAXMLFeedParser *parser = [[VNAXMLFeedParser alloc] init];
newFeed = [parser feedWithXMLData:receivedData error:&error];
}
if (!newFeed) {
NSString *errorDebugDescription = error.userInfo[NSDebugDescriptionErrorKey];
if (errorDebugDescription) {
os_log_error(VNA_LOG, "%@", errorDebugDescription);
}
// Mark the feed as failed
[self setFolderErrorFlag:folder flag:YES];
dispatch_async(dispatch_get_main_queue(), ^{
[connectorItem setStatus:NSLocalizedString(@"Error parsing data in feed", nil)];
});
return;
}
// Log number of bytes we received
NSString * byteCount = [NSByteCountFormatter stringFromByteCount:receivedData.length
countStyle:NSByteCountFormatterCountStyleFile];
[connectorItem appendDetail:[NSString stringWithFormat:NSLocalizedString(@"%@ received",
@"Number of bytes received, e.g. 1 MB received"),
byteCount]];
// Extract the latest title and description
NSString * feedTitle = newFeed.title;
NSString * feedDescription = newFeed.feedDescription;
NSString * feedLink = newFeed.homePageURL;
// Synthesize feed link if it is missing
if (feedLink == nil || feedLink.vna_isBlank) {
feedLink = folder.feedURL.vna_baseURL;
}
if (feedLink != nil && ![feedLink hasPrefix:@"http:"] && ![feedLink hasPrefix:@"https:"]) {
feedLink = [NSURL URLWithString:feedLink relativeToURL:url].absoluteString;
}
if (feedTitle != nil && !feedTitle.vna_isBlank && [folder.name hasPrefix:[Database untitledFeedFolderName]]) {
// If there's an existing feed with this title, make ours unique
// BUGBUG: This duplicates logic in database.m so consider moving it there.
NSString * oldFeedTitle = feedTitle;
NSString * newFeedTitle = feedTitle;
NSUInteger index = 1;
while (([dbManager folderFromName:newFeedTitle]) != nil) {
newFeedTitle = [NSString stringWithFormat:@"%@ (%lu)", oldFeedTitle, (unsigned long)index++];
}
connectorItem.name = newFeedTitle;
[dbManager setName:newFeedTitle forFolder:folderId];
}
if (feedDescription != nil) {
[dbManager setDescription:feedDescription forFolder:folderId];
}
if (feedLink != nil) {
[dbManager setHomePage:feedLink forFolder:folderId];
}
// Remember the last modified date
if (lastModifiedString != nil && lastModifiedString.length > 0) {
[dbManager setLastUpdateString:lastModifiedString forFolder:folderId];
}
if (newFeed.items.count == 0) {
// Mark the feed as empty
dispatch_async(dispatch_get_main_queue(), ^{
[connectorItem setStatus:NSLocalizedString(@"No articles in feed", nil)];
});
return;
}
// We'll be collecting articles into this array
NSMutableArray *articleArray = [NSMutableArray array];
NSMutableArray *articleGuidArray = [NSMutableArray array];
NSDate *itemAlternativeDate = newFeed.modificationDate;
if (itemAlternativeDate == nil) {
itemAlternativeDate = [NSDate date];
}
// Parse off items.
for (id<VNAFeedItem> newsItem in newFeed.items) {
NSDate * articleDate = newsItem.publicationDate;
NSDate * modificationDate = newsItem.modificationDate;
NSString * articleGuid = newsItem.guid;
// This routine attempts to synthesize a GUID from an incomplete item that lacks an
// ID field. Generally we'll have three things to work from: a link, a title and a
// description. The link alone is not sufficiently unique and I've seen feeds where
// the description is also not unique. The title field generally does vary but we need
// to be careful since separate articles with different descriptions may have the same
// title. The solution is to use the link and title and build a GUID from those.
// We add the folderId at the beginning to ensure that items in different feeds do not share a guid.
if ([articleGuid isEqualToString:@""]) {
articleGuid = [NSString stringWithFormat:@"%ld-%@-%@", (long)folderId, newsItem.url, newsItem.title];
}
// This is a horrible hack for horrible feeds that contain more than one item with the same guid.
// Bad feeds! I'm talking to you, kerbalstuff.com
NSUInteger articleIndex = [articleGuidArray indexOfObject:articleGuid];
if (articleIndex != NSNotFound) {
// We rebuild complex guids which should eliminate most duplicates
Article * firstFoundArticle = articleArray[articleIndex];
if (articleDate == nil) {
// first, hack the initial article (which is probably the first loaded / most recent one)
NSString * firstFoundArticleNewGuid =
[NSString stringWithFormat:@"%ld-%@-%@", (long)folderId, firstFoundArticle.link, firstFoundArticle.title];
firstFoundArticle.guid = firstFoundArticleNewGuid;
articleGuidArray[articleIndex] = firstFoundArticleNewGuid;
// then hack the guid for the item being processed
articleGuid = [NSString stringWithFormat:@"%ld-%@-%@", (long)folderId, newsItem.url, newsItem.title];
} else {
// first, hack the initial article (which is probably the first loaded / most recent one)
NSString * firstFoundArticleNewGuid =
[NSString stringWithFormat:@"%ld-%@-%@-%@", (long)folderId,
[NSString stringWithFormat:@"%1.3f", firstFoundArticle.lastUpdate.timeIntervalSince1970], firstFoundArticle.link,
firstFoundArticle.title];
firstFoundArticle.guid = firstFoundArticleNewGuid;
articleGuidArray[articleIndex] = firstFoundArticleNewGuid;
// then hack the guid for the item being processed
articleGuid =
[NSString stringWithFormat:@"%ld-%@-%@-%@", (long)folderId,
[NSString stringWithFormat:@"%1.3f", articleDate.timeIntervalSince1970], newsItem.url, newsItem.title];
}
}
[articleGuidArray addObject:articleGuid];
// set the article date if it is missing. We'll use the
// last modified date of the feed and set each article to be 1 second older than the
// previous one. So the array is effectively newest first.
if (articleDate == nil) {
articleDate = itemAlternativeDate;
itemAlternativeDate = [itemAlternativeDate dateByAddingTimeInterval:-1.0];
}
Article * article = [[Article alloc] initWithGuid:articleGuid];
article.folderId = folderId;
article.author = newsItem.authors;
article.body = newsItem.content;
if (!newsItem.title || newsItem.title.vna_isBlank) {
NSString *newTitle = newsItem.content.vna_titleTextFromHTML.vna_stringByUnescapingExtendedCharacters;
if (newTitle.vna_isBlank) {
article.title = NSLocalizedString(@"(No title)", @"Fallback for feed items without a title");
} else {
article.title = newTitle;
}
} else {
article.title = newsItem.title;
}
NSString * articleLink = newsItem.url;
if (![articleLink hasPrefix:@"http:"] && ![articleLink hasPrefix:@"https:"]) {
articleLink = [NSURL URLWithString:articleLink relativeToURL:url].absoluteString;
}
if (articleLink == nil) {
articleLink = feedLink;
}
article.link = articleLink;
article.publicationDate = articleDate;
article.lastUpdate = modificationDate;
NSString * enclosureLink = newsItem.enclosure;
if ([enclosureLink isNotEqualTo:@""] && ![enclosureLink hasPrefix:@"http:"] && ![enclosureLink hasPrefix:@"https:"]) {
enclosureLink = [NSURL URLWithString:enclosureLink relativeToURL:url].absoluteString;
}
article.enclosure = enclosureLink;
if ([enclosureLink isNotEqualTo:@""]) {
[article setHasEnclosure:YES];
}
[articleArray addObject:article];
}
// Here's where we add the articles to the database
if (articleArray.count > 0u) {
[folder resetArticleStatuses];
NSArray *guidHistory = [dbManager guidHistoryForFolderId:folderId];
for (Article * article in articleArray) {
if ([folder createArticle:article
guidHistory:guidHistory] && (article.status == ArticleStatusNew))
{
++newArticlesFromFeed;
}
}
}
if (newArticlesFromFeed > 0u) {
[dbManager setLastUpdate:[NSDate date] forFolder:folderId];
}
// Mark the feed as succeeded
[self setFolderErrorFlag:folder flag:NO];
[folder clearNonPersistedFlag:VNAFolderFlagBuggySync];
}
// Send status to the activity log
if (newArticlesFromFeed == 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[connectorItem setStatus:NSLocalizedString(@"No new articles available", nil)];
});
} else {
NSString * logText = [NSString stringWithFormat:NSLocalizedString(@"%d new articles retrieved", nil), (int)newArticlesFromFeed];
dispatch_async(dispatch_get_main_queue(), ^{
connectorItem.status = logText;
});
[[NSNotificationCenter defaultCenter] vna_postNotificationOnMainThreadWithName:MA_Notify_ArticleListContentChange object:@(folder.
itemId)];
}
// Done with this connection
// Add to count of new articles so far
countOfNewArticles += newArticlesFromFeed;
// If this folder also requires an image refresh, do that
if ((folder.flags & VNAFolderFlagCheckForImage)) {
dispatch_async(dispatch_get_main_queue(), ^{
[self refreshFavIconForFolder:folder];
});
}
}
/* getRedirectURL
* Scans the XML data and checks whether it is actually an HTML redirect. If so, returns the
* redirection URL. (Yes, I'm aware that some of this could be better implemented with calls to
* strnstr and its ilk but I have a deep rooted distrust of the standard C runtime stemming from
* a childhood trauma with buffer overflows so bear with me.)
*/
-(NSString *)getRedirectURL:(NSData *)data
{
const char *scanPtr = data.bytes;
const char *scanPtrEnd = scanPtr + data.length;
// Make sure this is HTML otherwise this is likely just valid
// XML and we can ignore everything else.
const char *htmlTagPtr = "<html>";
while (scanPtr < scanPtrEnd && *htmlTagPtr != '\0') {
if (*scanPtr != ' ') {
if (tolower(*scanPtr) != *htmlTagPtr) {
return nil;
}
++htmlTagPtr;
}
++scanPtr;
}
// Look for the meta attribute
const char *metaTag = "<meta ";
const char *headEndTag = "</head>";
const char *metaTagPtr = metaTag;
const char *headEndTagPtr = headEndTag;
while (scanPtr < scanPtrEnd) {
if (tolower(*scanPtr) == *metaTagPtr) {
++metaTagPtr;
} else {
metaTagPtr = metaTag;
if (tolower(*scanPtr) == *headEndTagPtr) {
++headEndTagPtr;
} else {
headEndTagPtr = headEndTag;
}
}
if (*headEndTagPtr == '\0') {
return nil;
}
if (*metaTagPtr == '\0') {
// Now see if this meta tag has http-equiv attribute
const char *httpEquivAttr = "http-equiv=\"refresh\"";
const char *httpEquivAttrPtr = httpEquivAttr;
while (scanPtr < scanPtrEnd && *scanPtr != '>') {
if (tolower(*scanPtr) == *httpEquivAttrPtr) {
++httpEquivAttrPtr;
} else if (*scanPtr != ' ') {
httpEquivAttrPtr = httpEquivAttr;
}
if (*httpEquivAttrPtr == '\0') {
// OK. This is our meta tag. Now look for the URL field
while (scanPtr < scanPtrEnd - 3 && *scanPtr != '>') {
if (tolower(*scanPtr) == 'u' && tolower(*(scanPtr + 1)) == 'r' && tolower(*(scanPtr + 2)) == 'l' &&
*(scanPtr + 3) == '=')
{
const char *urlStart = scanPtr + 4;
const char *urlEnd = urlStart;
// Finally, gather the URL for the redirect and return it as an
// auto-released string.
while (urlEnd < scanPtrEnd && *urlEnd != '"' && *urlEnd != ' ' && *urlEnd != '>') {
++urlEnd;
}
if (urlEnd == scanPtrEnd) {
return nil;
}
return [[NSString alloc] initWithBytes:urlStart length:(urlEnd - urlStart) encoding:NSASCIIStringEncoding];
}
++scanPtr;
}
}
++scanPtr;