Repository navigation
Expand file tree
/
Copy pathmain.m
More file actions
397 lines (367 loc) · 14.5 KB
/
Copy pathmain.m
File metadata and controls
397 lines (367 loc) · 14.5 KB
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
//
// main.m
// google-wave-notifier
//
// Created by hiroshi on 09/10/16.
// Copyright yakitara.com 2009. All rights reserved.
//
#import <Foundation/NSDictionary.h>
#import <Cocoa/Cocoa.h>
#import <SystemConfiguration/SCDynamicStoreCopySpecific.h> // for getting web proxy settings
#import <Growl/Growl.h>
#import <Growl/GrowlApplicationBridge.h>
#define SERVICE_NAME "Unofficial Google Wave Notifier" // FIXME: get from app
enum {
MenuItemTagUnreadInsert = 1,
MenuItemTagUnread = 2,
MenuItemTagCheckNow = 3,
};
//TODO: yes, I should separate class implementation from main.m...
@interface AppDelegate : NSObject <GrowlApplicationBridgeDelegate>
{
IBOutlet id menu;
IBOutlet id preferencesWindow;
NSStatusItem *statusItem;
NSDate *checkedDate;
NSMutableDictionary *growlNotified;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification;
- (IBAction)checkNotificationAsync:(id)sender;
- (void)checkNotification:(NSTimer*)theTimer;
- (void)updateSinceChecked:(NSTimer*)theTimer;
- (void)updateStatusItemWithCount:(int)count;
- (NSString *)password;
- (void)setPassword:(NSString *)value;
- (NSString *)webProxy;
- (IBAction)openPreferences:(id)sender;
- (IBAction)goToInbox:(id)sender;
- (IBAction)goToWave:(id)sender;
- (IBAction)resetAdvancedPreferencesToDefaults:(id)sender;
- (void) growlNotificationWasClicked:(id)clickContext;
@end
@implementation AppDelegate
- (void)growlNotificationWasClicked:(id)clickContext
{
[[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: clickContext]];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[GrowlApplicationBridge setGrowlDelegate:self];
// defaults
NSDictionary *defaultsDict = [NSDictionary dictionaryWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]];
[[NSUserDefaults standardUserDefaults] registerDefaults: defaultsDict];
[[NSUserDefaultsController sharedUserDefaultsController] setInitialValues: defaultsDict];
//NSLog(@"appliesImmediately: %d\n", [[NSUserDefaultsController sharedUserDefaultsController] appliesImmediately]);
growlNotified = [NSMutableDictionary dictionaryWithCapacity:10];
// menubar item
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength: NSVariableStatusItemLength];
[statusItem setImage: [NSImage imageNamed: @"color.png"]];
[statusItem setHighlightMode: YES];
[statusItem setMenu: menu];
// check once first
[self checkNotificationAsync: self];
// schedule updateSinceChecked
[NSTimer scheduledTimerWithTimeInterval: 60
target: self
selector: @selector(updateSinceChecked:)
userInfo: nil
repeats: YES];
// schedule checkNotification
[NSTimer scheduledTimerWithTimeInterval: 5.0 * 60 // TODO: preferences
target: self
selector: @selector(checkNotification:)
userInfo: nil
repeats: YES];
}
- (void)checkNotificationAsync:(id)sender
{
// NOTE: Clicking button and performeClose will not end editing the first responder text field. So, force to end editing it.
[preferencesWindow endEditingFor: [preferencesWindow firstResponder]];
[preferencesWindow performClose: sender];
[NSTimer scheduledTimerWithTimeInterval: 1.0
target: self
selector: @selector(checkNotification:)
userInfo: nil
repeats: NO];
}
- (void)checkNotification:(NSTimer*)theTimer
{
checkedDate = [NSDate dateWithTimeIntervalSinceNow: -2.0]; // ensure that first call of scheduled updateSinceChecked is called a minutes later
[self updateSinceChecked: NULL];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// first of all, check keychain for password
NSString *email = [defaults objectForKey: @"Email"];
if (!email)
{
[self updateStatusItemWithCount: -1];
return;
}
NSString *password = [self password];
if (!password)
{
[self updateStatusItemWithCount: -1];
return;
}
//NSLog(@"e: %@, p: %@\n", email, password);
NSString *pathToRuby = [defaults objectForKey: @"PathToRuby"];
NSLog(@"checkNotification: start. (pathToRuby: %@)\n", pathToRuby);
NSTask *task = [[NSTask alloc] init];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *handle = [pipe fileHandleForReading];
[task setLaunchPath: pathToRuby];
NSString *rbPath = [[NSBundle mainBundle] pathForResource: @"google-wave-notifier" ofType: @"rb"];
NSString *proxy = [self webProxy];
if (proxy)
{
[task setArguments: [NSArray arrayWithObjects: rbPath, email, password, @"-p", proxy, nil]];
}
else
{
[task setArguments: [NSArray arrayWithObjects: rbPath, email, password, nil]];
}
[task setStandardOutput: pipe];
@try {
[task launch];
}
//NOTE: will catch NSInvalidArgumentException when launchPath not accesible
@catch (NSException *e) {
NSLog(@"launch failed: %@: %@", [e name], [e reason]);
[self updateStatusItemWithCount: -1];
return;
}
NSData *data = [handle readDataToEndOfFile];
//NSLog([[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]);
//NSLog(@"\n");
[task waitUntilExit];
if ([task terminationStatus] != 0)
{
[self updateStatusItemWithCount: -1];
return;
}
NSString *errorString = nil;
NSPropertyListFormat format;
id plist = [NSPropertyListSerialization propertyListFromData: data
mutabilityOption: NSPropertyListImmutable
format: &format
errorDescription: &errorString];
if (errorString)
{
NSLog(@"checkNotification: failed. error: %@\n", *errorString);
}
else
{
//id count = [[[plist objectForKey: @"Items"] objectAtIndex: 0] objectForKey: @"Unread Count"];
// First, remove previous unreads
NSMenuItem *menuItem = nil;
while (menuItem = [menu itemWithTag: MenuItemTagUnread])
{
[menu removeItem: menuItem];
}
// remove or replace total unread count as menubar title
int totalCount = [[plist objectForKey: @"Total Unread Count"] intValue];
[self updateStatusItemWithCount: totalCount];
if (totalCount > 0)
{
[self updateStatusItemWithCount: totalCount];
// Add new unreads
NSInteger insertIndex = [menu indexOfItemWithTag: MenuItemTagUnreadInsert] + 1;
// separator
NSMenuItem *separator = [NSMenuItem separatorItem];
[separator setTag: MenuItemTagUnread];
[menu insertItem: separator atIndex: insertIndex];
// unread waves
NSEnumerator *enumerator = [[plist objectForKey: @"Items"] objectEnumerator];
NSDictionary *item = nil;
NSMutableDictionary *foundWaves = [NSMutableDictionary dictionaryWithCapacity:0];
while (item = [enumerator nextObject])
{
NSString *waveName= [item objectForKey: @"Title"];
NSNumber *unreadCount = [item objectForKey:@"Unread Count"];
[foundWaves setObject:unreadCount forKey: waveName];
NSString *url = [item objectForKey:@"URL"];
NSString *title = [NSString stringWithFormat: @"%@ (%@)", waveName , unreadCount];
NSMenuItem *menuItem = [menu insertItemWithTitle: title action: @selector(goToWave:) keyEquivalent: @"" atIndex: insertIndex];
[menuItem setRepresentedObject: url];
[menuItem setTag: MenuItemTagUnread];
if([growlNotified objectForKey:waveName] == nil ||
unreadCount != nil && [[growlNotified objectForKey:waveName] compare:unreadCount] != NSOrderedSame)
{
[GrowlApplicationBridge
notifyWithTitle:[NSString stringWithFormat: @"New Wave for %@",waveName]
description:[NSString stringWithFormat:@"%@ new Waves have been received",[NSNumber numberWithInt:[unreadCount intValue]-[[growlNotified objectForKey:waveName] intValue]]]
notificationName:@"NewWave"
iconData: [NSData data]
priority: (signed int)0
isSticky: FALSE
clickContext: url];
[growlNotified setObject:unreadCount forKey:waveName];
}
}
NSArray* keys = [growlNotified allKeys];
for(id key in keys) {
if([foundWaves objectForKey:key] == nil) {
[growlNotified removeObjectForKey:key];
}
}
}
else {
[growlNotified removeAllObjects];
}
NSLog(@"checkNotification: done. (total count: %d)\n", totalCount);
}
}
- (void)updateSinceChecked:(NSTimer*)theTimer
{
NSFont *font = [NSFont menuBarFontOfSize: 0];
NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObject: font forKey: NSFontAttributeName];
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString: @"Check Now" attributes: attrs];
[attrs setObject: [NSColor grayColor] forKey: NSForegroundColorAttributeName];
[attrs setObject: [NSFont menuBarFontOfSize: [font pointSize] - 2] forKey: NSFontAttributeName];
NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate: checkedDate];
NSLog(@"updateSinceChecked: seconds: %f", seconds);
NSString *appendTitle = NULL;
if (seconds < 60)
{
appendTitle = @" - Checked less than 1 min ago";
}
else if (seconds < 60 * 60)
{
appendTitle = [NSString stringWithFormat: @" - Checked %d min ago", (int)(seconds / 60)];
}
else // more than an hour
{
appendTitle = [NSString stringWithFormat: @" - Checked %d h ago", (int)(seconds / (60 * 60))];
}
[title appendAttributedString: [[NSAttributedString alloc] initWithString: appendTitle attributes: attrs]];
[[menu itemWithTag: MenuItemTagCheckNow] setAttributedTitle: title];
}
// count < 0 means failure
- (void)updateStatusItemWithCount:(int)count
{
if (count > 0)
{
[statusItem setImage: [NSImage imageNamed: @"color.png"]];
[statusItem setTitle: [NSString stringWithFormat: @"%d", count]];
}
else if(count == 0)
{
[statusItem setImage: [NSImage imageNamed: @"gray.png"]];
[statusItem setTitle: @""];
}
else
{
[statusItem setImage: [NSImage imageNamed: @"gray.png"]];
[statusItem setTitle: @"x"];
}
}
- (NSString *)password
{
NSString *email = [[NSUserDefaults standardUserDefaults] objectForKey: @"Email"];
if (email)
{
void *passwordData;
UInt32 passwordLength;
OSStatus status = SecKeychainFindGenericPassword(
NULL, // default keychain
strlen(SERVICE_NAME), // length of service name
SERVICE_NAME, // service name
[email lengthOfBytesUsingEncoding: NSUTF8StringEncoding], // length of account name
[email UTF8String], // account name
&passwordLength, // length of password
&passwordData, // pointer to password data
NULL // the item reference
);
if (status != noErr)
{
NSLog(@"SecKeychainFindGenericPassword: failed. (OSStatus: %d)\n", status); // FIXME: handle the errror
return nil;//@"";
}
//NSString *passwd = [NSString stringWithUTF8String: passwordData];
NSString *passwd = [[NSString alloc] initWithBytes: passwordData length: passwordLength encoding: NSUTF8StringEncoding];
status = SecKeychainItemFreeContent(NULL, passwordData);
if (status != noErr)
{
NSLog(@"SeSecKeychainItemFreeContent: failed. (OSStatus: %d)\n", status); // FIXME: handle the errror
}
return passwd;
}
else
{
return nil; //@"";
}
}
- (void)setPassword:(NSString *)value
{
NSString *email = [[NSUserDefaults standardUserDefaults] objectForKey: @"Email"];
if (email)
{
OSStatus status = SecKeychainAddGenericPassword (
NULL, // default keychain
strlen(SERVICE_NAME), // length of service name
SERVICE_NAME, // service name
[email lengthOfBytesUsingEncoding: NSUTF8StringEncoding], // length of account name
[email UTF8String], // account name
[value lengthOfBytesUsingEncoding: NSUTF8StringEncoding], // length of password
[value UTF8String], // password
NULL
);
if (status != noErr)
{
NSLog(@"SecKeychainAddGenericPassword: failed. (OSStatus: %d)\n", status); // FIXME: handle the errror
}
}
}
- (NSString*)webProxy
{
CFDictionaryRef proxySettings = SCDynamicStoreCopyProxies((SCDynamicStoreRef)NULL);
//NSLog(@"proxySettings: %@", proxySettings);
NSURL *url = [NSURL URLWithString: @"https://wave.google.com/wave/"];
NSArray *proxies = (NSArray*)CFNetworkCopyProxiesForURL((CFURLRef)url, proxySettings);
//NSLog(@"proxies: %@", proxies);
for (NSDictionary *dict in proxies)
{
if ([[dict objectForKey: @"kCFProxyTypeKey"] isEqualToString: @"kCFProxyTypeHTTPS"])
{
NSString *proxy = [NSString stringWithFormat: @"%@:%@",
[dict objectForKey: @"kCFProxyHostNameKey"],
[dict objectForKey: @"kCFProxyPortNumberKey"]];
NSLog(@"use proxy: %@\n", proxy);
return proxy;
}
}
return nil;
}
- (IBAction)openPreferences:(id)sender
{
[preferencesWindow makeKeyAndOrderFront: sender];
[preferencesWindow setLevel: NSTornOffMenuWindowLevel];
}
- (IBAction)goToInbox:(id)sender
{
[[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: @"https://wave.google.com/wave/"]];
}
- (IBAction)goToWave:(id)sender
{
NSString *url = [sender representedObject];
[[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: url]];
}
- (IBAction)resetAdvancedPreferencesToDefaults:(id)sender
{
// NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// NSUserDefaultsController *defaultsController = [NSUserDefaultsController sharedUserDefaultsController];
//[[defaultsController values] removeObjectForKey: @"PathToRuby"];
//[[defaultsController values] setNilValueForKey: @"PathToRuby"];
//[[defaultsController values] setValue: @"" forKey: @"PathToRuby"];
// [[defaultsController defaults] removeObjectForKey: @"PathToRuby"];
}
// for Cocoa binding key path
// NOTE: Key of Info.plist is not as is. (e.g. "Bundle version" => "CFBundleVersion")
- (NSDictionary *)infoDictionary
{
return [[NSBundle mainBundle] infoDictionary];
}
@end
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}