-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathCTCScheduler.m
262 lines (206 loc) · 9.48 KB
/
CTCScheduler.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
#import "CTCScheduler.h"
#import "CTCFeedChecker.h"
#import "CTCDefaults.h"
#import "CTCFileUtils.h"
#import "NSDate+TimeOfDayMath.h"
NSString * const kCTCSchedulerStatusNotificationName = @"com.giorgiocalderolla.Catch.scheduler-status-update";
NSString * const kCTCSchedulerLastUpdateStatusNotificationName = @"com.giorgiocalderolla.Catch.scheduler-last-update-status-update";
@interface CTCScheduler ()
@property (strong, nonatomic) NSTimer *repeatingTimer;
@property (strong, nonatomic) NSXPCConnection *feedCheckerConnection;
@property (strong, nonatomic) id<NSObject> activityToken;
@property (assign, nonatomic, getter = isPolling) BOOL polling;
@property (assign, nonatomic, getter = isChecking) BOOL checking;
@end
@implementation CTCScheduler
+ (instancetype)sharedScheduler {
static CTCScheduler *sharedScheduler = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedScheduler = CTCScheduler.new;
});
return sharedScheduler;
}
- (id)init {
self = [super init];
if (!self) {
return nil;
}
self.polling = YES;
self.checking = NO;
// Create and start single connection to the feed helper
// Messages will be delivered serially
self.feedCheckerConnection = [[NSXPCConnection alloc] initWithServiceName:@"com.giorgiocalderolla.Catch.CatchFeedHelper"];
self.feedCheckerConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(CTCFeedCheck)];
__weak typeof(self) weakSelf = self;
self.feedCheckerConnection.interruptionHandler = ^{
[weakSelf handleFeedCheckCompletion:NO];
};
[self.feedCheckerConnection resume];
// Create a timer to check periodically
self.repeatingTimer = [NSTimer scheduledTimerWithTimeInterval:kCTCDefaultsFeedUpdateInterval
target:self
selector:@selector(tick:)
userInfo:nil
repeats:YES];
// Check now as well
[self fireTimerNow];
[self preventAppNap];
return self;
}
- (void)preventAppNap {
// Make sure we can keep running in the background if the system supports App Nap
if ([NSProcessInfo.processInfo respondsToSelector:@selector(beginActivityWithOptions:reason:)]) {
self.activityToken = [NSProcessInfo.processInfo
beginActivityWithOptions:NSActivityIdleSystemSleepDisabled|NSActivitySuddenTerminationDisabled
reason:@"Background checking is the whole point of the app"];
}
}
- (void)setChecking:(BOOL)checking {
_checking = checking;
[self reportStatus];
}
- (void)setPolling:(BOOL)polling {
_polling = polling;
[self reportStatus];
}
- (void)checkFeed {
// Don't check twice simultaneously
if (self.isChecking) return;
// Only work with valid preferences
if (!CTCDefaults.isConfigurationValid) {
NSLog(@"Refusing to check feed - invalid preferences");
return;
}
self.checking = YES;
// Check the feed
__weak typeof(self) weakSelf = self;
[self callFeedCheckerWithReplyHandler:^(NSArray *downloadedFeedFiles,
NSError *error){
// Deal with new files
[weakSelf handleDownloadedFeedFiles:downloadedFeedFiles];
[weakSelf handleFeedCheckCompletion:error == nil];
}];
}
- (NSData *)downloadFolderBookmark {
NSError *error;
NSURL *url = [NSURL fileURLWithPath:CTCDefaults.torrentsSavePath];
NSData *bookmark = [CTCFileUtils bookmarkForURL:url error:&error];
if (!bookmark) {
// Not really handling this at all
[NSException raise:@"Couldn't create bookmark for downloads folder"
format:@"Error: %@", error];
}
return bookmark;
}
- (void)callFeedCheckerWithReplyHandler:(CTCFeedCheckCompletionHandler)replyHandler {
// Read configuration
NSURL *feedURL = [NSURL URLWithString:CTCDefaults.feedURL];
NSArray *history = CTCDefaults.downloadHistory;
// Extract URLs from history
NSArray *previouslyDownloadedURLs = [history valueForKey:@"url"];
// Call feed checker service
CTCFeedChecker *feedChecker = [self.feedCheckerConnection remoteObjectProxy];
[feedChecker checkShowRSSFeed:feedURL
downloadingToBookmark:[self downloadFolderBookmark]
organizingByFolder:CTCDefaults.shouldOrganizeTorrentsInFolders
skippingURLs:previouslyDownloadedURLs
withReply:^(NSArray *downloadedFeedFiles, NSError *error) {
if (error) {
NSLog(@"Feed Checker error (checking feed): %@", error);
}
dispatch_async(dispatch_get_main_queue(), ^{
replyHandler(downloadedFeedFiles, error);
});
}];
}
- (void)handleFeedCheckCompletion:(BOOL)wasSuccessful {
self.checking = NO;
[NSNotificationCenter.defaultCenter postNotificationName:kCTCSchedulerLastUpdateStatusNotificationName
object:self
userInfo:@{@"successful": @(wasSuccessful),
@"time": NSDate.date}];
}
- (void)reportStatus {
NSLog(@"Scheduler status updated (polling = %d, checking = %d)", self.isPolling, self.isChecking);
// Report status to application delegate
[NSNotificationCenter.defaultCenter postNotificationName:kCTCSchedulerStatusNotificationName
object:self
userInfo:nil];
}
- (void)togglePause {
self.polling = !self.isPolling;
// If we have just been set to polling, poll immediately
if (self.isPolling) [self fireTimerNow];
}
- (void)forceCheck {
NSLog(@"Forcing feed check");
// Check feed right now ignoring time restrictions and "paused" mode
[self checkFeed];
}
- (void)downloadFile:(NSDictionary *)file
completion:(void (^)(NSDictionary *downloadedFile, NSError *error))completion {
// Call feed checker service
CTCFeedChecker *feedChecker = [self.feedCheckerConnection remoteObjectProxy];
[feedChecker downloadFile:file
toBookmark:[self downloadFolderBookmark]
organizingByFolder:CTCDefaults.shouldOrganizeTorrentsInFolders
withReply:^(NSDictionary *downloadedFile, NSError *error) {
if (error) {
NSLog(@"Feed Checker error (downloading file): %@", error);
}
dispatch_async(dispatch_get_main_queue(), ^{
completion(downloadedFile, error);
});
}];
}
- (void)fireTimerNow {
[self.repeatingTimer setFireDate:NSDate.distantPast];
}
- (void)tick:(NSTimer*)timer {
NSLog(@"Scheduler tick");
if (!self.isPolling) {
NSLog(@"Scheduler tick skipped (paused)");
return;
}
// Don't check if current time is outside user-defined range
if (![self shouldCheckNow]) {
NSLog(@"Scheduler tick skipped (outside of user-defined time range)");
return;
}
[self checkFeed];
}
- (void)handleDownloadedFeedFiles:(NSArray *)downloadedFeedFiles {
BOOL shouldOpenTorrentsAutomatically = CTCDefaults.shouldOpenTorrentsAutomatically;
for (NSDictionary *feedFile in downloadedFeedFiles.reverseObjectEnumerator) {
BOOL isMagnetLink = [feedFile[@"isMagnetLink"] boolValue];
// Open magnet link
if (isMagnetLink) {
[NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:feedFile[@"url"]]];
}
// Open normal torrent in torrent client, if requested
if (!isMagnetLink && shouldOpenTorrentsAutomatically) {
[NSWorkspace.sharedWorkspace openFile:feedFile[@"torrentFilePath"]];
}
// Post to Notification Center
NSUserNotification *notification = NSUserNotification.new;
notification.title = NSLocalizedString(@"newtorrent", @"New torrent notification");
notification.informativeText = [NSString stringWithFormat:NSLocalizedString(@"newtorrentdesc", @"New torrent notification"), feedFile[@"title"]];
notification.soundName = NSUserNotificationDefaultSoundName;
[NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:notification];
// Add url to history
NSArray *history = CTCDefaults.downloadHistory;
NSDictionary *newHistoryEntry = @{@"title": feedFile[@"title"],
@"url": feedFile[@"url"],
@"isMagnetLink": feedFile[@"isMagnetLink"],
@"date": NSDate.date};
NSArray *newHistory = [@[newHistoryEntry] arrayByAddingObjectsFromArray:history];
CTCDefaults.downloadHistory = newHistory;
}
}
- (BOOL)shouldCheckNow {
if (!CTCDefaults.areTimeRestrictionsEnabled) return YES;
return [NSDate.date isTimeOfDayBetweenDate:CTCDefaults.fromDateForTimeRestrictions
andDate:CTCDefaults.toDateForTimeRestrictions];
}
@end