-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainController.m
More file actions
2505 lines (1668 loc) · 85.6 KB
/
Copy pathMainController.m
File metadata and controls
2505 lines (1668 loc) · 85.6 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
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
//
// MainController.m
// Reader Notifier
//
//
#import "MainController.h"
#import "Keychain.h"
// changelog since 1.02
// - we have made it so that the lag of the count will be minor when marking something as read.
// 27 with special icons, 29 else
#define ourStatusItemWithLength 29
#define versionBuildNumber 110
#define indexOfPreviewFields 4
#define itemsExclPreviewFields 6
#define maxLettersInSummary 500
#define maxLettersInSource 20
#define runningDebug 0
// disregard
// #define itemsExclPreviewFields 7 // changed from 6, back before "open all in windows" feature
@interface Delegate : NSObject
{
}
@end
@implementation Delegate
- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) aBool
{
// [[NSApplication sharedApplication] terminate: nil];
}
@end
@implementation MainController
- (id)init
{
[super init];
[self setupEventHandlers];
NSMutableDictionary *defaultPrefs = [NSMutableDictionary dictionary];
[defaultPrefs setObject:@"20" forKey:@"maxItems"];
[defaultPrefs setObject:@"10" forKey:@"timeDelay"];
[defaultPrefs setObject:@"" forKey:@"Label"];
[defaultPrefs setObject:@"5" forKey:@"maxNotifications"];
[defaultPrefs setObject:@"NO" forKey:@"EnableTorrentCastMode"];
prefs = [[NSUserDefaults standardUserDefaults] retain];
[prefs registerDefaults:defaultPrefs];
// in earlier versions this was set to the actual user password, which we would want to override
[prefs setObject:@"NotForYourEyes" forKey:@"Password"];
normalAttrsDictionary = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects: [NSFont fontWithName:@"Lucida Grande" size:14.0], nil] forKeys:[NSArray arrayWithObjects: NSFontAttributeName, nil ]];
smallAttrsDictionary = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects: [NSFont fontWithName:@"Lucida Grande" size:12.0], [NSColor grayColor], nil] forKeys:[NSArray arrayWithObjects: NSFontAttributeName, NSForegroundColorAttributeName, nil ]];
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(notificationTest1)
name:@"PleaseUpdateMenu"
object:GRMenu];
// we need this to know when the computer wakes from sleep
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(notificationTest2) name:NSWorkspaceDidWakeNotification object:nil];
/* NSNotificationCenter * wc = [[NSWorkspace sharedWorkspace] notificationCenter];
[nc addObserver:self selector:@selector(notificationTest2)
name:@"PleaseUpdateMenu"
object:nil];
*/
return self;
}
- (void)notificationTest1
{
// if (runningDebug == 1) NSLog(@"Notification Center message to Update Menu");
[self performSelectorOnMainThread:@selector(updateMenu) withObject:nil waitUntilDone:NO];
/// [NSThread detachNewThreadSelector:@selector(updateMenu) toTarget:self withObject:nil];
}
- (void)notificationTest2
{
NSDate *sleepUntil = [NSDate dateWithTimeIntervalSinceNow:8.0];
[NSThread sleepUntilDate:sleepUntil];
[lastCheckTimer invalidate];
[self createLastCheckTimer];
[lastCheckTimer fire];
// [self checkNowWithDelayDetached:[NSNumber numberWithInt:5]];
}
- (void)windowWillClose:(NSNotification *)aNotification
{
// when window closes, we update the shit
// if (runningDebug == 1) NSLog([aNotification name]);
// we disable this, because the app crashes if you put in new usercreds and then exit the prefwin at the same time
// [self checkNow:nil];
}
- (void)awakeFromNib
{
[NSApp activateIgnoringOtherApps:YES];
// Get system version
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"];
NSString *versionString = [dict objectForKey:@"ProductVersion"];
NSArray *array = [versionString componentsSeparatedByString:@"."];
int count = [array count];
int major = (count >= 1) ? [[array objectAtIndex:0] intValue] : 0;
int minor = (count >= 2) ? [[array objectAtIndex:1] intValue] : 0;
if (major > 10 || major == 10 && minor >= 5) {
isLeopard = YES;
} else {
isLeopard = NO;
}
// Growl
[GrowlApplicationBridge setGrowlDelegate:self];
[prefs setObject:@"" forKey:@"storedSID"];
if ([[prefs valueForKey:@"useColoredNoUnreadItemsIcon"] intValue] == 1) {
nounreadItemsImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"nounreadalt" ofType:@"png"]];
} else {
// intValue == 0
nounreadItemsImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"nounread" ofType:@"png"]];
}
if ([[prefs valueForKey:@"useColoredNoUnreadItemsIcon"] intValue] == 2) {
unreadItemsImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"nounread" ofType:@"png"]];
errorImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bwerror" ofType:@"png"]];
} else {
unreadItemsImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"unread" ofType:@"png"]];
errorImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"png"]];
}
highlightedImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"highunread" ofType:@"png"]];
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:ourStatusItemWithLength] retain]; //NSVariableStatusItemLength] retain];
[statusItem setHighlightMode:YES];
[statusItem setTitle:@""];
[statusItem setMenu:GRMenu];
[statusItem setImage:nounreadItemsImage];
[statusItem setAlternateImage:highlightedImage];
[statusItem setEnabled:YES];
user = [[NSMutableArray alloc] init];
titles = [[NSMutableArray alloc] init];
links = [[NSMutableArray alloc] init];
results = [[NSMutableArray alloc] init];
lastIds = [[NSMutableArray alloc] init];
feeds = [[NSMutableArray alloc] init];
ids = [[NSMutableArray alloc] init];
sources = [[NSMutableArray alloc] init];
newItems = [[NSMutableArray alloc] init];
summaries = [[NSMutableArray alloc] init];
torrentcastlinks = [[NSMutableArray alloc] init];
lastCheckMinute = 0;
[[tempMenuSec insertItemWithTitle:NSLocalizedString(@"Go to Reader",nil) action:@selector(launchSite:) keyEquivalent:@"" atIndex:0] setTarget:self];
[[tempMenuSec insertItemWithTitle:NSLocalizedString(@"Subscribe to Feed",nil) action:@selector(openAddFeedWindow:) keyEquivalent:@"" atIndex:1] setTarget:self];
[[tempMenuSec insertItemWithTitle:NSLocalizedString(@"Check Now",nil) action:@selector(checkNow:) keyEquivalent:@"" atIndex:2] setTarget:self];
[[tempMenuSec itemAtIndex:2] setAttributedTitle:[self makeAttributedMenuString:NSLocalizedString(@"Check Now",nil):@""]];
[tempMenuSec insertItem:[NSMenuItem separatorItem] atIndex:3];
[[tempMenuSec insertItemWithTitle:NSLocalizedString(@"Preferences...",nil) action:@selector(openPrefs:) keyEquivalent:@"" atIndex:4] setTarget:self];
[[tempMenuSec itemAtIndex:2] setAttributedTitle:[self makeAttributedMenuString:NSLocalizedString(@"Check Now",nil):NSLocalizedString(@"Updating...",nil)]];
[[GRMenu insertItemWithTitle:NSLocalizedString(@"Go to Reader",nil) action:@selector(launchSite:) keyEquivalent:@"" atIndex:0] setTarget:self];
[[GRMenu insertItemWithTitle:NSLocalizedString(@"Subscribe to Feed",nil) action:@selector(openAddFeedWindow:) keyEquivalent:@"" atIndex:1] setTarget:self];
[[GRMenu insertItemWithTitle:NSLocalizedString(@"Check Now",nil) action:@selector(checkNow:) keyEquivalent:@"" atIndex:2] setTarget:self];
[[GRMenu itemAtIndex:2] setAttributedTitle:[self makeAttributedMenuString:NSLocalizedString(@"Check Now",nil):@""]];
[GRMenu insertItem:[NSMenuItem separatorItem] atIndex:3];
[[GRMenu insertItemWithTitle:NSLocalizedString(@"Preferences...",nil) action:@selector(openPrefs:) keyEquivalent:@"" atIndex:4] setTarget:self];
storedSID = [[NSString alloc] init];
storedSID = @"";
if ([prefs valueForKey:@"Username"] && [Keychain checkForExistanceOfKeychain] > 0) {
[self setTimeDelay:[[prefs valueForKey:@"timeDelay"] intValue]];
[mainTimer fire];
[self createLastCheckTimer];
[lastCheckTimer fire];
} else {
[self displayAlert:@"Please fill in your Google Account login in the preference pane":@"In order to connect to your feed you need to type in your username and password."];
[self displayMessage:@"please enter login details"];
}
// Get the info dictionary (Info.plist)
NSDictionary *infoDictionary;
infoDictionary = [[NSBundle mainBundle] infoDictionary];
if (runningDebug == 1) if (runningDebug == 1) NSLog(@"Hello. %@ Build %@", [infoDictionary objectForKey:@"CFBundleName"], [infoDictionary objectForKey:@"CFBundleVersion"]);
if ([prefs valueForKey:@"torrentCastFolderPath"] != NULL) {
[torrentCastFolderPath setStringValue:[prefs valueForKey:@"torrentCastFolderPath"]];
}
NSProcessInfo *procInfo = [NSProcessInfo processInfo];
if (runningDebug == 1) if (runningDebug == 1) NSLog(@"We're on %@", [procInfo operatingSystemVersionString]);
}
- (void)createLastCheckTimer
{
lastCheckMinute = 0;
lastCheckTimer = [[NSTimer scheduledTimerWithTimeInterval:(60) target:self selector:@selector(lastTimeCheckedTimer:) userInfo:nil repeats:YES] retain];
}
- (void)setTimeDelay:(int) x //creates a timer with a user-specified delay, fires the timer
{
//if (runningDebug == 1) if (runningDebug == 1) NSLog(@"creating timer with %d minute delay", [[prefs stringForKey:@"timeDelay"] intValue]);
mainTimer = [[NSTimer scheduledTimerWithTimeInterval:(60 * x) target:self selector:@selector(timer:) userInfo:nil repeats:YES] retain];
}
- (void)timer:(NSTimer *)timer
{
if (currentlyFetchingAndUpdating != YES) {
if (![[self loginToGoogle] isEqualToString:@""]) {
[self retrieveGoogleFeed];
}
}
}
- (void)lastTimeCheckedTimer:(NSTimer *)timer
{
if (lastCheckMinute > [[prefs valueForKey:@"timeDelay"] intValue]) {
if (runningDebug == 1) if (runningDebug == 1) NSLog(@"lastTimeChecked is more than it should be, so we run update");
if (currentlyFetchingAndUpdating != YES) {
[NSThread detachNewThreadSelector:@selector(checkNow:) toTarget:self withObject:nil];
}
} else {
if (runningDebug == 1) if (runningDebug == 1) NSLog(@"lastTimeCheckedTimer run %d", lastCheckMinute);
if (lastCheckMinute == 0) {
[self displayLastTimeMessage:[NSString stringWithString:NSLocalizedString(@"Checked less than 1 min ago",nil)]]; /* ok */
} else if (lastCheckMinute == 1) {
[self displayLastTimeMessage:[NSString stringWithString:NSLocalizedString(@"Checked 1 min ago",nil)]]; /* ok */
} else if (lastCheckMinute < 60) {
[self displayLastTimeMessage:[NSString stringWithFormat:NSLocalizedString(@"Checked %d min ago",nil), lastCheckMinute]];
} else if (59 < lastCheckMinute < 120) {
[self displayLastTimeMessage:[NSString stringWithString:NSLocalizedString(@"Checked 1 hour ago",nil)]]; /* ok */
} else if (119 < lastCheckMinute < 180) {
[self displayLastTimeMessage:[NSString stringWithString:NSLocalizedString(@"Checked 2 hours ago",nil)]]; /* ok */
} else if (179 < lastCheckMinute < 240) {
[self displayLastTimeMessage:[NSString stringWithString:NSLocalizedString(@"Checked 3 hours ago",nil)]]; /* ok */
} else if (239 < lastCheckMinute) {
[self displayLastTimeMessage:[NSString stringWithString:NSLocalizedString(@"Checked more than 4 hours ago",nil)]]; /* ok */
}
lastCheckMinute++;
}
}
- (NSString *)sendConnectionRequest:(NSString *)urlToConnectTo:(BOOL)handleCookies:(NSString *)cookieValue:(NSString *)theHTTPMethod:(NSString *)theHTTPBody
{
NSError *error = nil;
NSURLResponse *response;
NSData *dataReply;
NSString *stringReply;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:urlToConnectTo]];
[request setTimeoutInterval:5.0];
if (isLeopard) {
[request setHTTPShouldHandleCookies:NO];
} else {
[request setHTTPShouldHandleCookies:handleCookies];
}
[request setValue:cookieValue forHTTPHeaderField:@"Cookie"];
[request setHTTPMethod:theHTTPMethod]; // Changing the setHTTPMethod to "POST" sends the HTTPBody
[request setHTTPBody: [theHTTPBody dataUsingEncoding: NSUTF8StringEncoding]];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error==nil) {
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
return stringReply;
[stringReply release];
} else {
return @"";
}
}
- (int)getUnreadCount
{
if (runningDebug == 1) if (runningDebug == 1) NSLog(@"Total count (getUnreadCount) method initiated");
// since .99 this has provided a memory error (case of Moore).
// we've tried to fix it with releasing atomdoc2 and temparray5 (and not releasing dstring)
// http://www.google.com/reader/api/0/unread-count?all=true&autorefresh=true&output=json&ck=1165697710220&client=scroll
NSError *newError = nil;
NSURLResponse *newResponse;
NSData *newDataReply;
// NSString *newReply;
NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@://www.google.com/reader/api/0/unread-count?all=true&autorefresh=true&output=xml&client=scroll",[self getURLPrefix]]]];
// [request setHTTPMethod: @"PUT"]; // With the setHTTPMethod set to "PUT" the HTTPBody is not being sent
// we need to do this, otherwise we can risk get an old one :( - seriously, we did!
[newRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[newRequest setTimeoutInterval:5.0];
if (isLeopard) {
[newRequest setHTTPShouldHandleCookies:NO];
} else {
[newRequest setHTTPShouldHandleCookies:YES];
}
[newRequest setValue:[self loginToGoogle] forHTTPHeaderField:@"Cookie"];
[newRequest setHTTPMethod:@"GET"]; // Changing the setHTTPMethod to "POST" sends the HTTPBody
newDataReply = [NSURLConnection sendSynchronousRequest:newRequest returningResponse:&newResponse error:&newError];
// NSString *stringReply = [[NSString alloc] initWithData:newDataReply encoding:NSUTF8StringEncoding];
// if (runningDebug == 1) if (runningDebug == 1) NSLog(stringReply);
if (newError==nil) {
NSXMLDocument *atomdoc2 = [[NSXMLDocument alloc] initWithData:newDataReply options:0 error:&xmlError];
if (runningDebug == 1) if (runningDebug == 1) NSLog(@"getUnreadCount1");
NSMutableArray *tempArray5 = [[NSMutableArray alloc] init];
// [tempArray5 autorelease];
if (runningDebug == 1) if (runningDebug == 1) NSLog(@"getUnreadCount2");
// if the user is on labels, use that to check instead!
if ([[prefs valueForKey:@"Label"] isEqualToString:@""])
{
// [tempArray5 addObjectsFromArray:[atomdoc2 objectsForXQuery:@"/object/list/object/number/text()" error:NULL]];
// [tempArray5 addObjectsFromArray:[atomdoc2 objectsForXQuery:@"for $x in /object/list/object where $x/string[contains(., 'feed/http://')] return $x/number/text()" error:NULL]];
[tempArray5 addObjectsFromArray:[atomdoc2 objectsForXQuery:@"for $x in /object/list/object where $x/string[contains(., 'feed/http://')] return $x/number[@name=\"count\"]/text()" error:NULL]]; // peters add
} else {
if (runningDebug == 1) if (runningDebug == 1) NSLog(@"getUnreadCount haslabel");
// if (runningDebug == 1) if (runningDebug == 1) NSLog(@"Hello");
// [tempArray5 addObjectsFromArray:[atomdoc2 objectsForXQuery:@"/object/list/object/number/text()" error:NULL]];
// REAL ONE [tempArray5 addObjectsFromArray:[atomdoc2 objectsForXQuery:[NSString stringWithFormat:@"for $x in /object/list/object where $x/string[contains(., '/%@')] return $x/number/text()", [self getLabel]] error:NULL]];
// if (runningDebug == 1) if (runningDebug == 1) NSLog(@"We use labels");
// [tempArray5 addObjectsFromArray:[atomdoc2 objectsForXQuery:[NSString stringWithFormat:@"for $x in /object/list/object where $x/string[contains(., '/label/%@')] return $x/number/text()", [prefs valueForKey:@"Label"]] error:NULL]];
[tempArray5 addObjectsFromArray:[atomdoc2 objectsForXQuery:[NSString stringWithFormat:@"for $x in /object/list/object where $x/string[contains(., '/label/%@')] return $x/number[@name=\"count\"]/text()", [prefs valueForKey:@"Label"]] error:NULL]]; // peters add
}
int k,t;
t = 0;
NSString *dString;
for (k=0; k<[tempArray5 count]; k++) {
dString = [[tempArray5 objectAtIndex:k] stringValue];
t = t + [dString intValue];
}
if (runningDebug == 1) NSLog(@"getUnreadCount3");
// [dString release];
[tempArray5 release];
[atomdoc2 release];
if (runningDebug == 1) NSLog(@"The total count of unread items is now %d", t);
totalUnreadItemsInGRInterface = t;
} else {
// there was an error
totalUnreadItemsInGRInterface = -1;
[self errorImageOn];
currentlyFetchingAndUpdating = NO;
[lastCheckTimer invalidate];
[self createLastCheckTimer];
[lastCheckTimer fire];
[statusItem setMenu:GRMenu];
}
//if (runningDebug == 1) NSLog([NSString stringWithFormat:@"%d", t]);
// if (runningDebug == 1) NSLog([NSString stringWithFormat:@"totalUnreadItemsInGRInterface is %d+", totalUnreadItemsInGRInterface]);
return totalUnreadItemsInGRInterface;
}
- (void)retrieveGoogleFeed
{
// threading
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed begin");
currentlyFetchingAndUpdating = YES;
[statusItem setMenu:tempMenuSec];
// in case we had an error before, clear the highlightedimage and displaymessage
[statusItem setAlternateImage:highlightedImage];
xmlError = [[NSError alloc] init];
[lastIds setArray:ids];
[results removeAllObjects];
[titles removeAllObjects];
[sources removeAllObjects];
[links removeAllObjects];
[feeds removeAllObjects];
[ids removeAllObjects];
[newItems removeAllObjects];
[summaries removeAllObjects];
[torrentcastlinks removeAllObjects];
[user removeAllObjects]; // if this is not done, we cannot be sure that a user will get a new userNo on re-entering login details
/* new */
NSError *newError = nil;
NSURLResponse *newResponse;
NSData *newDataReply;
NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@://www.google.com/reader/atom/user/-/%@?r=d&xt=user/-/state/com.google/read&n=%d",[self getURLPrefix],[self getLabel],[[prefs valueForKey:@"maxItems"] intValue]+1]]];
[newRequest setTimeoutInterval:5.0];
[newRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData];
if (isLeopard) {
[newRequest setHTTPShouldHandleCookies:NO];
} else {
[newRequest setHTTPShouldHandleCookies:YES];
}
[newRequest setHTTPMethod:@"GET"]; // Changing the setHTTPMethod to "POST" sends the HTTPBody
[newRequest setValue:[self loginToGoogle] forHTTPHeaderField:@"Cookie"];
newDataReply = [NSURLConnection sendSynchronousRequest:newRequest returningResponse:&newResponse error:&newError];
if (newError!=nil) {
[self errorImageOn];
currentlyFetchingAndUpdating = NO;
[lastCheckTimer invalidate];
[self createLastCheckTimer];
[lastCheckTimer fire];
[statusItem setMenu:GRMenu];
return;
}
NSXMLDocument *atomdoc = [[NSXMLDocument alloc] initWithData:[newDataReply retain] options:0 error:&xmlError];
[titles addObjectsFromArray:[atomdoc objectsForXQuery:@"/feed/entry/title/text()" error:NULL]];
// [summaries addObjectsFromArray:[atomdoc objectsForXQuery:@"/feed/entry/summary/text()" error:NULL]];
[sources addObjectsFromArray:[atomdoc objectsForXQuery:@"/feed/entry/source/title/text()" error:NULL]];
[ids addObjectsFromArray:[atomdoc objectsForXQuery:@"/feed/entry/id/text()" error:NULL]];
//[user addObjectsFromArray:[atomdoc objectsForXQuery:@"/feed/id/text()" error:NULL]];
//[links addObjectsFromArray:[atomdoc objectsForXQuery:@"/feed/entry/link[@rel='alternate']/@href" error:NULL]];
//[feeds addObjectsFromArray:[atomdoc objectsForXQuery:@"for $f in /feed/entry/source return $f/@gr:stream-id" error:NULL]];
[feeds addObjectsFromArray:[atomdoc objectsForXQuery:@"/feed/entry/source/@gr:stream-id" error:NULL]];
[user addObjectsFromArray:[atomdoc objectsForXQuery:@"/feed/id/text()" error:NULL]];
// NSMutableArray *tempArray = [[NSMutableArray alloc] init];
// [tempArray autorelease];
//NSMutableArray *tempArray0 = [[NSMutableArray alloc] init];
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 1");
int k;
for(k=0; k<[titles count]; k++){
NSMutableArray *tempArray0 = [[NSMutableArray alloc] initWithArray:[atomdoc objectsForXQuery:[NSString stringWithFormat:@"/feed/entry[%d]/link[@rel='alternate']/@href",k+1] error:NULL]];
if([tempArray0 count]>0){
[links insertObject:[[tempArray0 objectAtIndex:0] stringValue] atIndex:k];
} else {
[links insertObject:@"" atIndex:k];
}
[tempArray0 release];
}
/*
for(k=0; k<[titles count]; k++){
NSMutableArray *tempArray0 = [[NSMutableArray alloc] initWithArray:[atomdoc objectsForXQuery:[NSString stringWithFormat:@"/feed/entry[%d]/link[@rel='alternate']/@href",k+1] error:NULL]];
if([tempArray0 count]>0){
[links insertObject:[[tempArray0 objectAtIndex:0] stringValue] atIndex:k];
} else {
[links insertObject:@"" atIndex:k];
}
[tempArray0 release];
}
*/
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 2");
int m;
for (m=0; m<[titles count]; m++) {
NSMutableArray *tempArray2 = [[NSMutableArray alloc] initWithArray:[atomdoc objectsForXQuery:[NSString stringWithFormat:@"/feed/entry[%d]/summary/text()",m+1] error:NULL]];
if ( [tempArray2 count]>0 ) {
[summaries insertObject:[NSString stringWithFormat:@"\n\n%@", [self flattenHTML:[self trimDownString:[[tempArray2 objectAtIndex:0] stringValue]:maxLettersInSummary]]] atIndex:m];
} else {
NSMutableArray *tempArray3 = [[NSMutableArray alloc] initWithArray:[atomdoc objectsForXQuery:[NSString stringWithFormat:@"/feed/entry[%d]/content/text()",m+1] error:NULL]];
if( [tempArray3 count]>0 ) {
[summaries insertObject:[NSString stringWithFormat:@"\n\n%@", [self flattenHTML:[self trimDownString:[[tempArray3 objectAtIndex:0] stringValue]:maxLettersInSummary]]] atIndex:m];
} else {
[summaries insertObject:@"" atIndex:m];
}
[tempArray3 release];
}
[tempArray2 release];
}
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 2a");
// torrentcasting
int l;
for (l=0; l<[titles count]; l++) {
NSMutableArray *tempArray2 = [[NSMutableArray alloc] initWithArray:[atomdoc objectsForXQuery:[NSString stringWithFormat:@"/feed/entry[%d]/link[@type='application/x-bittorrent']/@href",l+1] error:NULL]];
if ( [tempArray2 count]>0 ) {
[torrentcastlinks insertObject:[[tempArray2 objectAtIndex:0] stringValue] atIndex:l];
} else {
[torrentcastlinks insertObject:@"" atIndex:l];
}
[tempArray2 release];
}
// cannot release here, because we'll release atomdoc as well
// [tempArray2 release];
// [tempArray3 release];
//if (runningDebug == 1) NSLog([self grabUserNo]);
//if (runningDebug == 1) NSLog([links description]);
/* int i;
for(i=0; i<[links count]; i++){
[links replaceObjectAtIndex:i withObject:[[links objectAtIndex:i] stringValue]];
}*/
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 3");
int j;
for(j=0; j<[feeds count]; j++){
[feeds replaceObjectAtIndex:j withObject:[[feeds objectAtIndex:j] stringValue]];
}
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 4");
int d;
for(d=0; d<[ids count]; d++){
[ids replaceObjectAtIndex:d withObject:[[ids objectAtIndex:d] stringValue]];
}
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 5");
// to sort everything with the newest on top
// titles = [self reverseArray:titles];
// sources = [self reverseArray:sources];
// ids = [self reverseArray:ids];
// feeds = [self reverseArray:feeds];
// links = [self reverseArray:links];
// summaries = [self reverseArray:summaries];
//if (runningDebug == 1) NSLog([[links objectAtIndex:0] stringValue]);
//if (runningDebug == 1) NSLog([feeds description]);
[atomdoc release];
//[tempArray2 release];
//[tempArray3 release];
// NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@://www.google.com/reader/api/0/unread-count?all=true&autorefresh=true&output=xml&client=scroll",[self getURLPrefix]]]];
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 6");
// [atomdoc autorelease];
if (xmlError!=nil) {
/*
if (runningDebug == 1) NSLog(@"%@ %d %@", [ xmlError domain], [ xmlError code], [ xmlError localizedDescription]);
/// if ([[prefs valueForKey:@"Label"] containsObject:[NSString stringWithString:@" "]]) {
/// [self displayMessage:@"error with Labels - only one allowed."];
/// } else {
[self displayMessage:@"no Internet connection"];
// if (runningDebug == 1) NSLog(@"no internet connection it seems!");
/// }
[self errorImageOn];
// NSImage *errorMenuicon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"png"]];
// [statusItem setImage:[[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"png"]]];
// [statusItem setAlternateImage:[[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"png"]]];
// [statusItem setMenu:GRMenu];
currentlyFetchingAndUpdating = NO;
*/
} else {
// We need to set the global whether there are (at least one) more unread items online in the google reader interface
if ([titles count] > [[prefs valueForKey:@"maxItems"] intValue]) {
moreUnreadExistInGRInterface = YES;
// We also remove the last item, since we do not wish to display it anywhere, or fuck up the count
// note, we remove the first item, which is actually the oldest (we reversed the array earlier)
// ! we could actually skip all the maxItems checks later, but they're nice to have.
/// UPDATE! We do not reverse it any longer! So now we just remove the last item
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 6");
if ([ids count] > 0) {
[titles removeLastObject];
[sources removeLastObject];
[ids removeLastObject];
[feeds removeLastObject];
[links removeLastObject];
[summaries removeLastObject];
[torrentcastlinks removeLastObject];
// [titles removeObjectAtIndex:0];
// [sources removeObjectAtIndex:0];
// [ids removeObjectAtIndex:0];
// [feeds removeObjectAtIndex:0];
// [links removeObjectAtIndex:0];
// [summaries removeObjectAtIndex:0];
}
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed 7");
// while we know that there are extra unread items, we want to get the exact count of them,
// the totalUnreadItemsInGRInterface will be updated automatically
//// HERE THERE IS AN ERROR!!! **** this call makes a memory-error
[self getUnreadCount];
} else {
moreUnreadExistInGRInterface = NO;
}
// threading
// [self performSelectorOnMainThread:@selector(updateMenu) withObject:self waitUntilDone:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:@"PleaseUpdateMenu" object:nil];
// threading off
// [self updateMenu];
}
// if (runningDebug == 1) NSLog(@"Test");
// [newDataReply release];
// [newReply release];
// [newRequest release];
if (runningDebug == 1) NSLog(@"retrieveGoogleFeed end");
// threading
[pool release];
}
- (void)updateMenu //updates the icon if necessary, updates the unread item
{
// threading
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[lastCheckTimer invalidate];
[self createLastCheckTimer];
[lastCheckTimer fire];
if (runningDebug == 1) NSLog(@"updateMenu begin");
// if (runningDebug == 1) NSLog(@"Updating menu");
currentlyFetchingAndUpdating = YES;
// [self performSelectorOnMainThread:@selector(removeAllItemsFromMenubar) withObject:nil waitUntilDone:YES];
int n;
n = [GRMenu numberOfItems];
int v;
for(v=itemsExclPreviewFields; v<n; v++) {
// [[GRMenu itemAtIndex:indexOfPreviewFields] release];
[GRMenu removeItemAtIndex:indexOfPreviewFields];
// [GRMenu removeItem:[GRMenu itemAtIndex:indexOfPreviewFields]];
}
// if (runningDebug == 1) NSLog(@"All items removed from Menubar");
// EXPERIMENTAL
/// This is a feature in development!
/// The automatical downloading of certain feeds
// TORRENTCASTING
if ([prefs boolForKey:@"EnableTorrentCastMode"] == YES) {
int i;
for(i=0; i<[titles count]; i++){
if (![[torrentcastlinks objectAtIndex:i] isEqualToString:@""]) {
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:[prefs valueForKey:@"torrentCastFolderPath"]] == YES) {
[self downloadFile:[torrentcastlinks objectAtIndex:i]:[NSString stringWithFormat:@"%@.torrent", [titles objectAtIndex:i]]];
NSMutableString *feedstring = [[NSMutableString alloc] initWithString:[feeds objectAtIndex:i]];
[feedstring replaceOccurrencesOfString:@"=" withString:@"-" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [feedstring length])];
[self sendConnectionRequest:[NSString stringWithFormat:@"%@://www.google.com/reader/api/0/edit-tag?s=%@&i=%@&ac=edit-tags&a=user/-/state/com.google/read&r=user/-/state/com.google/kept-unread&T=%@",[self getURLPrefix],feedstring,[ids objectAtIndex:i],[self getTokenFromGoogle]]:YES:[self loginToGoogle]:@"POST":@""];
[feedstring release];
if ([[prefs valueForKey:@"openTorrentAfterDownloading"] boolValue] == YES) {
if (runningDebug == 1) NSLog(@"%@/%@", [prefs valueForKey:@"torrentCastFolderPath"], [NSString stringWithFormat:@"%@.torrent", [titles objectAtIndex:i]]);
[[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/%@", [prefs valueForKey:@"torrentCastFolderPath"], [NSString stringWithFormat:@"%@.torrent", [titles objectAtIndex:i]]]];
}
[feeds removeObjectAtIndex:i];
[ids removeObjectAtIndex:i];
[links removeObjectAtIndex:i];
[titles removeObjectAtIndex:i];
[sources removeObjectAtIndex:i];
[summaries removeObjectAtIndex:i];
[torrentcastlinks removeObjectAtIndex:i];
} else {
[self displayAlert:NSLocalizedString(@"TorrentCast Error",nil):NSLocalizedString(@"Reader Notifier has found a new TorrentCast. However we are unable to download it because the folder you've specified does not exists. Please choose a new folder in the preferences. In addition, TorrentCasting has been disabled.",nil)];
[prefs setValue:NO forKey:@"EnableTorrentCastMode"];
}
}
}
}
int c;
for(c=0; c<[titles count]; c++){
[results addObject:[NSString stringWithFormat:@"%d", c]];
}
// if we have any items in the list, we should put a nice little bar between the normal buttons and the feeditems
if ([results count] > 0 && [[prefs valueForKey:@"minimalFunction"] boolValue] != YES) {
[GRMenu insertItem:[NSMenuItem separatorItem] atIndex:3];
}
// if (runningDebug == 1) NSLog(@"Putting in the new standard stuff");
// this will actually be put at the bottom
// if ([results count] == 1 && [[prefs valueForKey:@"minimalFunction"] boolValue] != YES) {
// [[GRMenu insertItemWithTitle:NSLocalizedString(@"Mark as read",nil) action:@selector(markAllAsRead:) keyEquivalent:@"" atIndex:indexOfPreviewFields] setTarget:self];
// [GRMenu insertItemWithTitle:NSLocalizedString(@"Open all items",nil) action:@selector(openAllItems:) keyEquivalent:@"" atIndex:indexOfPreviewFields];
// [GRMenu insertItem:[NSMenuItem separatorItem] atIndex:indexOfPreviewFields];
// } else if ([results count] > 0 && [[prefs valueForKey:@"minimalFunction"] boolValue] != YES && moreUnreadExistInGRInterface == YES) {
if ([results count] > 0 && [[prefs valueForKey:@"minimalFunction"] boolValue] != YES && moreUnreadExistInGRInterface == YES) {
// we don't want to display the Mark all as read if there are more items in the Google Reader Interface
// though we check if the users wants to override this
if ([[prefs valueForKey:@"alwaysEnableMarkAllAsRead"] boolValue] != YES) {
[GRMenu insertItemWithTitle:[NSString stringWithString:NSLocalizedString(@"More unread items exist",nil)] action:nil keyEquivalent:@"" atIndex:indexOfPreviewFields];
[[GRMenu itemAtIndex:indexOfPreviewFields] setToolTip:NSLocalizedString(@"Mark all as read has been disabled",nil)];
} else {
[[GRMenu insertItemWithTitle:NSLocalizedString(@"Mark all as read",nil) action:@selector(markAllAsRead:) keyEquivalent:@"" atIndex:indexOfPreviewFields] setTarget:self];
[[GRMenu itemAtIndex:indexOfPreviewFields] setAttributedTitle:[self makeAttributedMenuString:NSLocalizedString(@"Mark all as read",nil):NSLocalizedString(@"Warning, items online will be marked read",nil)]];
[[GRMenu itemAtIndex:indexOfPreviewFields] setToolTip:NSLocalizedString(@"There are more unread items online in the Google Reader interface. This function will cause Google Reader Notifier to mark all as read - whether or not they are visible in the menubar",nil)];
}
[[GRMenu insertItemWithTitle:NSLocalizedString(@"Open all items",nil) action:@selector(openAllItems:) keyEquivalent:@"" atIndex:indexOfPreviewFields] setTarget:self];
[GRMenu insertItem:[NSMenuItem separatorItem] atIndex:indexOfPreviewFields];
} else if ([results count] > 0 && [[prefs valueForKey:@"minimalFunction"] boolValue] != YES) {
[[GRMenu insertItemWithTitle:NSLocalizedString(@"Mark all as read",nil) action:@selector(markAllAsRead:) keyEquivalent:@"" atIndex:indexOfPreviewFields] setTarget:self];
[[GRMenu insertItemWithTitle:NSLocalizedString(@"Open all items",nil) action:@selector(openAllItems:) keyEquivalent:@"" atIndex:indexOfPreviewFields] setTarget:self];
[GRMenu insertItem:[NSMenuItem separatorItem] atIndex:indexOfPreviewFields];
}
int newCount;
int currentIndexCount;
newCount = 0;
currentIndexCount = indexOfPreviewFields;
// if (runningDebug == 1) NSLog(@"Looping through the results array");
// we loop through the results count, but we cannot go above the maxItems, even though we always fetch one row more than max
int j;
for (j = 0; j < [results count] && j < [[prefs valueForKey:@"maxItems"] intValue]; j++) {
if ([[prefs valueForKey:@"minimalFunction"] boolValue] != YES) {
NSString *trimmedTitleTag = [[NSString alloc] initWithString:[self trimDownString:[self flattenHTML:[[titles objectAtIndex:j] stringValue]]:60]];
NSString *trimmedSourceTag = [[NSString alloc] initWithString:[self trimDownString:[self flattenHTML:[[sources objectAtIndex:j] stringValue]]:maxLettersInSource]];
// trimmedSourceTag = [self trimDownString:[self flattenHTML:[[sources objectAtIndex:j] stringValue]]:maxLettersInSource];
// trimmedTitleTag = [self trimDownString:[self flattenHTML:[[titles objectAtIndex:j] stringValue]]:60];
NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:@selector(launchLink:) keyEquivalent:@""];
[item setAttributedTitle:[self makeAttributedMenuString:trimmedSourceTag:trimmedTitleTag]];
if ([[prefs valueForKey:@"dontShowTooltips"] boolValue] != YES) {
[item setToolTip:[NSString stringWithFormat:NSLocalizedString(@"Title: %@\nFeed: %@\nGoes to: %@%@",nil), [titles objectAtIndex:j], [[sources objectAtIndex:j] stringValue], [links objectAtIndex:j], [summaries objectAtIndex:j]]];
}
[item setTitle:[ids objectAtIndex:j]];
if ([[links objectAtIndex:j] length] > 0) {
[item setTarget:self];
}
// [[GRMenu itemAtIndex:currentIndexCount] setTitle:];
[item setKeyEquivalentModifierMask:0];
[GRMenu insertItem:item atIndex:currentIndexCount];
// and then set the alternate
NSMenuItem *itemSecondary = [[NSMenuItem alloc] initWithTitle:@"" action:@selector(doOptionalActionFromMenu:) keyEquivalent:@""];
// [GRMenu insertItemWithTitle:@"" action:@selector(doOptionalActionFromMenu:) keyEquivalent:@"" atIndex:currentIndexCount+1];
if ([[prefs valueForKey:@"onOptionalActAlsoStarItem"] boolValue] == YES) {
[itemSecondary setAttributedTitle:[self makeAttributedMenuString:trimmedSourceTag:NSLocalizedString(@"Star item and mark as read",nil)]];
} else {
[itemSecondary setAttributedTitle:[self makeAttributedMenuString:trimmedSourceTag:NSLocalizedString(@"Mark item as read",nil)]];
}
[itemSecondary setKeyEquivalentModifierMask:NSCommandKeyMask];
[itemSecondary setAlternate:YES];
// even though setting the title twice seems like doing double work, we have to, because [sender title] will always be the last set title!
[itemSecondary setTitle:[ids objectAtIndex:j]];
if ([[links objectAtIndex:j] length] > 0) {
[itemSecondary setTarget:self];
}
[GRMenu insertItem:itemSecondary atIndex:currentIndexCount+1];
[trimmedTitleTag release];
[trimmedSourceTag release];
[item release];
[itemSecondary release];
}
// if (runningDebug == 1) NSLog(@"Checking if last time had same");
if (![lastIds containsObject:[ids objectAtIndex:j]]){
// Growl help
[newItems addObject:[results objectAtIndex:j]];
newCount++;
}
currentIndexCount++;
currentIndexCount++; // the extra one is because we add two menuitems now, one for command-tabbing
}
if ([results count] == 0) {
[statusItem setImage:nounreadItemsImage];
} else {