forked from SelfControlApp/selfcontrol
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AppController.m
executable file
·513 lines (429 loc) · 21.1 KB
/
AppController.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
//
// AppController.m
// SelfControl
//
// Created by Charlie Stigler on 1/29/09.
// Copyright 2009 Eyebeam.
// This file is part of SelfControl.
//
// SelfControl is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#import "AppController.h"
NSString* const kSelfControlLockFilePath = @"/etc/SelfControl.lock";
@implementation AppController
- (AppController*) init {
[super init];
defaults_ = [NSUserDefaults standardUserDefaults];
NSDictionary* appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: 0], @"BlockDuration",
[NSDate distantFuture], @"BlockStartedDate",
[NSArray array], @"HostBlacklist",
[NSNumber numberWithBool: YES], @"EvaluateCommonSubdomains",
[NSNumber numberWithBool: YES], @"HighlightInvalidHosts",
[NSNumber numberWithBool: YES], @"VerifyInternetConnection",
[NSNumber numberWithBool: NO], @"TimerWindowFloats",
[NSNumber numberWithBool: NO], @"BlockSoundShouldPlay",
[NSNumber numberWithInt: 5], @"BlockSound",
nil];
[defaults_ registerDefaults:appDefaults];
return self;
}
- (NSString*)selfControlHelperToolPath {
static NSString* path;
// Cache the path so it doesn't have to be searched for again.
if(!path) {
NSBundle* thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForAuxiliaryExecutable: @"org.eyebeam.SelfControl"];
}
return path;
}
- (char*)selfControlHelperToolPathUTF8String {
static char* path;
// Cache the converted path so it doesn't have to be converted again
if(!path) {
path = malloc(512);
[[self selfControlHelperToolPath] getCString: path
maxLength: 512
encoding: NSUTF8StringEncoding];
}
return path;
}
- (IBAction)updateTimeSliderDisplay:(id)sender {
int numMinutes = [blockDurationSlider_ intValue];
NSString* timeString;
if (numMinutes == 0) {
timeString = [NSString stringWithString:@"Disabled"];
[submitButton_ setEnabled: NO];
}
else if (numMinutes < 60) {
timeString = [NSString stringWithFormat:@"%d minutes", numMinutes];
if([[defaults_ arrayForKey:@"HostBlacklist"] count] != 0)
[submitButton_ setEnabled: YES];
}
else if (numMinutes % 60 == 0) {
timeString = [NSString stringWithFormat:@"%d hours", numMinutes / 60];
if([[defaults_ arrayForKey:@"HostBlacklist"] count] != 0)
[submitButton_ setEnabled: YES];
}
else {
timeString = [NSString stringWithFormat:@"%d hours, %d minutes",
numMinutes / 60,
numMinutes % 60];
if([[defaults_ arrayForKey:@"HostBlacklist"] count] != 0)
[submitButton_ setEnabled: YES];
}
[blockSliderTimeDisplayLabel_ setStringValue:timeString];
}
- (IBAction)addBlock:(id)sender{
[defaults_ synchronize];
if(([[defaults_ objectForKey:@"BlockStartedDate"] timeIntervalSinceNow] < 0)) {
// This method shouldn't be getting called, a block is on (block started date
// is in the past, not distantFuture) so the Start button should be disabled.
// Maybe the UI didn't get properly refreshed, so try refreshing it again
// before we return.
[self refreshUserInterface];
return;
}
if([[defaults_ arrayForKey:@"HostBlacklist"] count] == 0)
// Since the Start button should be disabled when the blacklist has no entries,
// this should definitely not be happening. Exit.
return;
if([defaults_ boolForKey: @"VerifyInternetConnection"] && ![self networkConnectionIsAvailable]) {
NSAlert* networkUnavailableAlert = [[[NSAlert alloc] init] autorelease];
[networkUnavailableAlert setMessageText: @"No network connection detected"];
[networkUnavailableAlert setInformativeText:@"A block cannot be started without a working network connection. You can override this setting in Preferences."];
[networkUnavailableAlert addButtonWithTitle: @"Cancel"];
[networkUnavailableAlert addButtonWithTitle: @"Network Diagnostics..."];
if([networkUnavailableAlert runModal] == NSAlertFirstButtonReturn)
return;
// If the user selected Network Diagnostics launch an assisant to help them.
// apple.com is an arbitrary host chosen to pass to Network Diagnostics.
CFURLRef url = CFURLCreateWithString(NULL, CFSTR("http://apple.com"), NULL);
CFNetDiagnosticRef diagRef = CFNetDiagnosticCreateWithURL(NULL, url);
CFNetDiagnosticDiagnoseProblemInteractively(diagRef);
return;
}
AuthorizationRef authorizationRef;
char* helperToolPath = [self selfControlHelperToolPathUTF8String];
int helperToolPathSize = strlen(helperToolPath);
AuthorizationItem right = {
kAuthorizationRightExecute,
helperToolPathSize,
helperToolPath,
0
};
AuthorizationRights authRights = {
1,
&right
};
AuthorizationFlags myFlags = kAuthorizationFlagDefaults |
kAuthorizationFlagExtendRights |
kAuthorizationFlagInteractionAllowed;
OSStatus status;
status = AuthorizationCreate (&authRights,
kAuthorizationEmptyEnvironment,
myFlags,
&authorizationRef);
if(status) {
NSLog(@"ERROR: Failed to authorize block start.");
return;
}
// We need to pass our UID to the helper tool. It needs to know whose defaults
// it should reading in order to properly load the blacklist.
char uidString[10];
snprintf(uidString, sizeof(uidString), "%d", getuid());
char* args[] = { uidString, "--install", NULL };
status = AuthorizationExecuteWithPrivileges(authorizationRef,
helperToolPath,
kAuthorizationFlagDefaults,
args,
NULL);
if(status) {
NSLog(@"WARNING: Authorized execution of helper tool returned failure status code %d", status);
}
}
- (void)refreshUserInterface {
if([self selfControlLaunchDaemonIsLoaded]) {
[self showAndReloadTimerWindow];
[initialWindow_ close];
[self closeDomainList];
} else {
[self updateTimeSliderDisplay: blockDurationSlider_];
[defaults_ synchronize];
if([blockDurationSlider_ intValue] != 0 && [[defaults_ objectForKey: @"HostBlacklist"] count] != 0)
[submitButton_ setEnabled: YES];
else
[submitButton_ setEnabled: NO];
NSWindow* mainWindow = [NSApp mainWindow];
// We don't necessarily want the initial window to be key and front,
// but no other message seems to show it properly.
[initialWindow_ makeKeyAndOrderFront: self];
// So we work around it and make key and front whatever was the main window
[mainWindow makeKeyAndOrderFront: self];
[self closeTimerWindow];
}
}
- (void)showAndReloadTimerWindow {
if(timerWindowController_ == nil) {
timerWindowController_ = [[TimerWindowController alloc] init];
}
[[timerWindowController_ window] center];
[timerWindowController_ showWindow: self];
[timerWindowController_ reloadTimer];
}
- (void)closeTimerWindow {
[timerWindowController_ close];
}
/* - (void)removeBlock {
// Remember not to use this method, it defeats the point of SelfControl!
[defaults_ synchronize];
AuthorizationRef authorizationRef;
char* helperToolPath = [self selfControlHelperToolPathUTF8String];
int helperToolPathSize = strlen(helperToolPath);
AuthorizationItem right = {
kAuthorizationRightExecute,
helperToolPathSize,
helperToolPath,
0
};
AuthorizationRights authRights = {
1,
&right
};
AuthorizationFlags myFlags = kAuthorizationFlagDefaults |
kAuthorizationFlagExtendRights |
kAuthorizationFlagInteractionAllowed;
OSStatus status;
status = AuthorizationCreate (&authRights, kAuthorizationEmptyEnvironment, myFlags, &authorizationRef);
if(status) {
NSLog(@"ERROR: Failed to authorize block removal.");
return;
}
char uidString[10];
snprintf(uidString, sizeof(uidString), "%d", getuid());
char* args[] = { uidString, "--remove", NULL };
status = AuthorizationExecuteWithPrivileges(authorizationRef,
[self selfControlHelperToolPathUTF8String],
kAuthorizationFlagDefaults, args,
NULL);
if(status) {
NSLog(@"WARNING: Helper tool returned failure status code %d.");
return;
}
} */
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[NSApp setDelegate: self];
// Register observers on both distributed and normal notification centers
// to receive notifications from the helper tool and the other parts of the
// main SelfControl app. Note that they are divided thusly because distributed
// notifications are very expensive and should be minimized.
[[NSDistributedNotificationCenter defaultCenter] addObserver: self
selector: @selector(refreshUserInterface)
name: @"SCConfigurationChangedNotification"
object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(refreshUserInterface)
name: @"SCConfigurationChangedNotification"
object: nil];
[initialWindow_ center];
[self refreshUserInterface];
}
- (BOOL)selfControlLaunchDaemonIsLoaded {
[defaults_ synchronize];
// NSDate* blockStartedDate = [defaults_ objectForKey:@"BlockStartedDate"];
/*BOOL cur = (![blockStartedDate isEqualToDate: [NSDate distantFuture]]);
BOOL next = [[NSFileManager defaultManager] fileExistsAtPath: kSelfControlLockFilePath];
if(cur != next)
NSLog(@"cur isn't next!");
return next; */
return [[NSFileManager defaultManager] fileExistsAtPath: kSelfControlLockFilePath];
/* return (![blockStartedDate isEqualToDate: [NSDate distantFuture]]);
return [[NSFileManager defaultManager] fileExistsAtPath: kSelfControlLockFilePath]; */
}
- (IBAction)showDomainList:(id)sender {
if([self selfControlLaunchDaemonIsLoaded]) {
NSAlert* blockInProgressAlert = [[[NSAlert alloc] init] autorelease];
[blockInProgressAlert setMessageText: @"Block in progress"];
[blockInProgressAlert setInformativeText:@"The blacklist cannot be edited while a block is in progress."];
[blockInProgressAlert addButtonWithTitle: @"OK"];
[blockInProgressAlert runModal];
return;
}
if(domainListWindowController_ == nil) {
domainListWindowController_ = [[DomainListWindowController alloc] init];
}
[domainListWindowController_ showWindow: self];
}
- (void)closeDomainList {
[domainListWindowController_ close];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSApplication*) theApplication {
// Hack to make the application terminate after the last window is closed, but
// INCLUDE the HUD-style timer window.
if([[timerWindowController_ window] isVisible])
return NO;
return YES;
}
- (BOOL)networkConnectionIsAvailable {
SCNetworkConnectionFlags status;
// This method goes haywire if Google ever goes down...
BOOL reachable = SCNetworkCheckReachabilityByName ("google.com", &status);
return reachable && (status & kSCNetworkFlagsReachable) && !(status & kSCNetworkFlagsConnectionRequired);
}
- (IBAction)soundSelectionChanged:(id)sender {
// Map the tags used in interface builder to the sound
NSArray* systemSoundNames = [NSArray arrayWithObjects:
@"Basso",
@"Blow",
@"Bottle",
@"Frog",
@"Funk",
@"Glass",
@"Hero",
@"Morse",
@"Ping",
@"Pop",
@"Purr",
@"Sosumi",
@"Submarine",
@"Tink",
nil
];
NSSound* alertSound = [NSSound soundNamed: [systemSoundNames objectAtIndex: [defaults_ integerForKey: @"BlockSound"]]];
if(!alertSound)
NSLog(@"WARNING: Alert sound not found.");
else
[alertSound play];
}
- (void)addToBlockList:(NSString*)host {
if(host == nil)
return;
host = [[host stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] lowercaseString];
// Remove "http://" if a user tried to put that in
NSArray* splitString = [host componentsSeparatedByString: @"http://"];
for(int i = 0; i < [splitString count]; i++) {
if(![[splitString objectAtIndex: i] isEqual: @""]) {
host = [splitString objectAtIndex: i];
break;
}
}
// Delete anything after a "/" in case a user tried to copy-paste a web address.
host = [[host componentsSeparatedByString: @"/"] objectAtIndex: 0];
if([host isEqualToString: @""])
return;
NSMutableArray* list = [[defaults_ arrayForKey: @"HostBlacklist"] mutableCopy];
[list addObject: host];
[defaults_ setObject: list forKey: @"HostBlacklist"];
[defaults_ synchronize];
if(([[defaults_ objectForKey:@"BlockStartedDate"] isEqualToDate: [NSDate distantFuture]])) {
// This method shouldn't be getting called, a block is not on (block started
// is in the distantFuture) so the Start button should be disabled.
// Maybe the UI didn't get properly refreshed, so try refreshing it again
// before we return.
[self refreshUserInterface];
// Reverse the blacklist change made before we fail
NSMutableArray* list = [[defaults_ arrayForKey: @"HostBlacklist"] mutableCopy];
[list removeLastObject];
[defaults_ setObject: list forKey: @"HostBlacklist"];
return;
}
if([defaults_ boolForKey: @"VerifyInternetConnection"] && ![self networkConnectionIsAvailable]) {
NSAlert* networkUnavailableAlert = [[[NSAlert alloc] init] autorelease];
[networkUnavailableAlert setMessageText: @"No network connection detected"];
[networkUnavailableAlert setInformativeText:@"A block cannot be started without a working network connection. You can override this setting in Preferences."];
[networkUnavailableAlert addButtonWithTitle: @"Cancel"];
[networkUnavailableAlert addButtonWithTitle: @"Network Diagnostics..."];
if([networkUnavailableAlert runModal] == NSAlertFirstButtonReturn) {
// User clicked cancel
// Reverse the blacklist change made before we fail
NSMutableArray* list = [[defaults_ arrayForKey: @"HostBlacklist"] mutableCopy];
[list removeLastObject];
[defaults_ setObject: list forKey: @"HostBlacklist"];
return;
}
// If the user selected Network Diagnostics, launch an assisant to help them.
// apple.com is an arbitrary host chosen to pass to Network Diagnostics.
CFURLRef url = CFURLCreateWithString(NULL, CFSTR("http://apple.com"), NULL);
CFNetDiagnosticRef diagRef = CFNetDiagnosticCreateWithURL(NULL, url);
CFNetDiagnosticDiagnoseProblemInteractively(diagRef);
// Reverse the blacklist change made before we fail
NSMutableArray* list = [[defaults_ arrayForKey: @"HostBlacklist"] mutableCopy];
[list removeLastObject];
[defaults_ setObject: list forKey: @"HostBlacklist"];
return;
}
AuthorizationRef authorizationRef;
char* helperToolPath = [self selfControlHelperToolPathUTF8String];
int helperToolPathSize = strlen(helperToolPath);
AuthorizationItem right = {
kAuthorizationRightExecute,
helperToolPathSize,
helperToolPath,
0
};
AuthorizationRights authRights = {
1,
&right
};
AuthorizationFlags myFlags = kAuthorizationFlagDefaults |
kAuthorizationFlagExtendRights |
kAuthorizationFlagInteractionAllowed;
OSStatus status;
status = AuthorizationCreate (&authRights,
kAuthorizationEmptyEnvironment,
myFlags,
&authorizationRef);
if(status) {
NSLog(@"ERROR: Failed to authorize block refresh.");
// Reverse the blacklist change made before we fail
NSMutableArray* list = [[defaults_ arrayForKey: @"HostBlacklist"] mutableCopy];
[list removeLastObject];
[defaults_ setObject: list forKey: @"HostBlacklist"];
return;
}
// We need to pass our UID to the helper tool. It needs to know whose defaults
// it should read in order to properly load the blacklist.
char uidString[10];
snprintf(uidString, sizeof(uidString), "%d", getuid());
char* args[] = { uidString, "--refresh", NULL };
status = AuthorizationExecuteWithPrivileges(authorizationRef,
helperToolPath,
kAuthorizationFlagDefaults,
args,
NULL);
if(status) {
NSLog(@"WARNING: Authorized execution of helper tool returned failure status code %d", status);
}
}
- (void)dealloc {
[domainListWindowController_ release];
[timerWindowController_ release];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: @"SCConfigurationChangedNotification"
object: nil];
[[NSDistributedNotificationCenter defaultCenter] removeObserver: self
name: @"SCConfigurationChangedNotification"
object: nil];
[super dealloc];
}
// @synthesize initialWindow = initialWindow_;
- (id)initialWindow {
return initialWindow_;
}
- (id)domainListWindowController {
return domainListWindowController_;
}
- (void)setDomainListWindowController:(id)newController {
[newController retain];
[domainListWindowController_ release];
domainListWindowController_ = newController;
}
@end