forked from bps/scrobblepod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppController.m
1041 lines (821 loc) · 40.6 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
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
#import "AppController.h"
#import "Defines.h"
#import "HubStrings.h"
#import <Security/Security.h>
#import <QuartzCore/CoreAnimation.h>
#import "CocoaCryptoHashing.h"
#import "GrowlHub.h"
#import "iPodWatcher.h"
#import "BGTrackCollector.h"
#import "BGScrobbleDecisionManager.h"
#import "BGLastFmHandshaker.h"
#import "BGLastFmHandshakeResponse.h"
#import "BGLastFmScrobbler.h"
#import "BGLastFmScrobbleResponse.h"
#import "BGLastFmWebServiceCaller.h"
#import "BGLastFmWebServiceParameterList.h"
#import "BGLastFmWebServiceResponse.h"
#import "BGMultipleSongPlayManager.h"
#import "NSCalendarDate+RelativeDateDescription.h"
#import "SFHFKeychainUtils.h"
#import "StatusItemView.h"
#include <ApplicationServices/ApplicationServices.h>
#import "NSString+UrlEncoding.h"
#import "NSString+Contains.h"
//#import "BGConnectionCaller.h"
@implementation AppController
#pragma mark Application Starting/Quitting
-(void)showStatusMenu:(id)sender {
[statusItem popUpStatusItemMenu:statusMenu];
}
-(void)menuWillOpen:(NSMenu *)menu {
[[BGScrobbleDecisionManager sharedManager] resetRefreshTimer];
[arrowWindow properClose];
}
-(void)awakeFromNib {
// URL Cache trick
// NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
// [NSURLCache setSharedURLCache:sharedCache];
// [sharedCache release];
[self setIsScrobbling:NO];
[self setIsPostingNP:NO];
[updater setDelegate:self];
[updater setSendsSystemProfile:YES];
isLoadingCommonTags = NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults registerDefaults: [NSDictionary dictionaryWithObjectsAndKeys:
@"...",BGPrefUsername,
@"",BGWebServiceSessionKey,
@"",BGSubmissionSessionKey,
[NSNumber numberWithBool:YES],BGPrefFirstRunKey,
[[[NSCalendarDate calendarDate] dateByAddingYears:0 months:0 days:0 hours:0 minutes:-2 seconds:0] descriptionWithCalendarFormat:DATE_FORMAT_STRING],BGPrefLastScrobbled,
[NSNumber numberWithBool:YES],@"SUEnableAutomaticChecks",
[NSNumber numberWithBool:YES],BGPrefWantMultiPost,
[NSNumber numberWithBool:NO],BGPrefShouldPlaySound,
[NSNumber numberWithBool:NO],BGPrefShouldIgnoreComments,
@"dontpost",BGPrefIgnoreCommentString,
[NSNumber numberWithBool:NO],BGPrefShouldIgnoreGenre,
@"",BGPrefIgnoreGenreString,
[NSNumber numberWithBool:YES],BGPrefShouldIgnoreShort,
[NSNumber numberWithInt:30],BGPrefIgnoreShortLength,
[NSNumber numberWithInt:3],BGPrefPodFreshnessInterval,
[NSNumber numberWithBool:YES],BGPrefShouldIgnorePodcasts,
[NSNumber numberWithBool:YES],BGPrefShouldIgnoreVideo,
[NSNumber numberWithBool:YES],BGPrefWantNowPlaying,
[NSNumber numberWithBool:YES],BGPrefWantStatusItem,
[NSNumber numberWithBool:YES],BGPrefUsePodFreshnessInterval,
[NSNumber numberWithInt:0],BGTracksScrobbledTotal,
[NSNumber numberWithBool:YES],BGPref_Growl_SongChange,
[NSNumber numberWithBool:YES],BGPref_Growl_ScrobbleFail,
[NSNumber numberWithBool:YES],BGPref_Growl_ScrobbleDecisionChanged,
[NSNumber numberWithBool:NO],BGPrefWantOldIcon,
[NSNumber numberWithBool:YES],BGPrefShouldDoMultiPlay,
[NSNumber numberWithBool:NO],BGPrefShouldUseAlbumArtist,
[NSNumber numberWithBool:NO],BGPrefShouldUseComposerInsteadOfArtist,
[NSNumber numberWithBool:NO],BGPrefShouldUseGroupingInTitle,
[NSNumber numberWithBool:NO],BGPrefLastScrobbledWithCorrectOffsetFromGMT,
[NSNumber numberWithBool:NO],BGPrefNewMultiplayDBFormat,
@"~/Music/iTunes/iTunes Music Library.xml",BGPrefXmlLocation,
nil] ];
// DLog(@"Last iPod Sync Date: %@",[defaults objectForKey:BGLastSyncDate]);
// DLog(@"Last Scrobbled: %@",[defaults objectForKey:BGPrefLastScrobbled]);
statusItem = nil;
if ([defaults boolForKey:BGPrefWantStatusItem]) {
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:23];//NSVariableStatusItemLength
[statusItem setEnabled:YES];
// [statusItem setHighlightMode:YES];
// [statusItem setMenu:statusMenu];
// [statusItem setImage:[NSImage imageNamed:@"MenuNote"]];
// [statusItem setAlternateImage:[NSImage imageNamed:@"MenuNote_On"]];
// [statusItem setToolTip:@"ScrobblePod"];
// [statusItem setTarget:self];
// [statusItem sendActionOn:NSLeftMouseDownMask];
// [statusItem setAction:@selector(showStatusMenu:)];
// [statusItem retain];
StatusItemView *tempView = [[StatusItemView alloc] initWithStatusItem:statusItem];
[tempView setImage:[NSImage imageNamed:(![defaults boolForKey:BGPrefWantOldIcon] ? @"MenuNote" : @"old_menu_icon")]];
[tempView setAlternateImage:(![defaults boolForKey:BGPrefWantOldIcon] ? [NSImage imageNamed:@"MenuNote_On"] : nil)];
[tempView setTarget:self];
[tempView setAction:@selector(showStatusMenu:)];
[statusItem setView:tempView];
[tempView release];
[statusItem retain];
}
[currentSongMenuItem setView:infoView];
// A combination of containerView and infoView was making those ugly dark stripes on the sides of the menu.
//[currentSongMenuItem setView:containerView];
//[containerView addSubview:infoView];
if (![self cacheFileExists]) {
[self primeSongPlayCache];
}
if (![defaults boolForKey:BGPrefNewMultiplayDBFormat]) {
[self primeSongPlayCache];
[defaults setBool:YES forKey:BGPrefNewMultiplayDBFormat];
}
NSString *storedDateString = [defaults valueForKey:BGPrefLastScrobbled];
if ([NSCalendarDate dateWithString:storedDateString calendarFormat:DATE_FORMAT_STRING]==nil)
{
[defaults setValue:[[NSCalendarDate calendarDate] descriptionWithCalendarFormat:DATE_FORMAT_STRING] forKey:BGPrefLastScrobbled];
[defaults setBool:YES forKey:BGPrefLastScrobbledWithCorrectOffsetFromGMT];
}
// TODO: This fixes incorrect Last Scrobbled date, which could be set into the future or past because of a bug introduced in 0.6.0.7. The bug was fixed in 0.6.3 and this code should remain here at least till next major version.
if (![defaults boolForKey:BGPrefLastScrobbledWithCorrectOffsetFromGMT])
{
[defaults setValue:[[NSCalendarDate dateWithTimeIntervalSinceReferenceDate:([[NSCalendarDate dateWithString:storedDateString calendarFormat:DATE_FORMAT_STRING] timeIntervalSinceReferenceDate] - [[NSTimeZone localTimeZone] secondsFromGMT] + 7200.00)] descriptionWithCalendarFormat:DATE_FORMAT_STRING] forKey:BGPrefLastScrobbled];
DLog(@"Changing Last Scrobbled date to correct offset from GMT");
DLog(@"Last Scrobbled: %@",[defaults objectForKey:BGPrefLastScrobbled]);
[defaults setBool:YES forKey:BGPrefLastScrobbledWithCorrectOffsetFromGMT];
[defaults synchronize];
}
NSNotificationCenter *defaultNotificationCenter = [NSNotificationCenter defaultCenter];
[defaultNotificationCenter addObserver:self selector:@selector(podWatcherMountedPod:) name:BGNotificationPodMounted object:nil];
[defaultNotificationCenter addObserver:self selector:@selector(xmlFileChanged:) name:XMLChangedNotification object:nil];
[defaultNotificationCenter addObserver:self selector:@selector(amdsSyncCompleted:) name:AMDSSyncComplete object:nil];
authManager = [[BGLastFmAuthenticationManager alloc] initWithDelegate:self];
[[iTunesWatcher sharedManager] setDelegate:self];
myiPodWatcher = [[iPodWatcher alloc] init];
NSNotificationCenter *workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
[workspaceNotificationCenter addObserver:self selector:@selector(workspaceDidLaunchApplication:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
[workspaceNotificationCenter addObserver:self selector:@selector(workspaceDidTerminateApplication:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
xmlWatcher = [[FileWatcher alloc] init];
[xmlWatcher startWatchingXMLFile];
// DLog(@"XML Path: %@",[xmlWatcher fullXmlPath]);
apiQueue = [NSMutableArray new];
}
#pragma mark Sparkle
- (NSArray *)feedParametersForUpdater:(SUUpdater *)updater sendingSystemProfile:(BOOL)sendingProfile {
NSArray *keys = [NSArray arrayWithObjects:@"key", @"value", nil];
NSArray *parameters = [NSArray arrayWithObject: [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: @"uuid", [self installationId], nil] forKeys:keys]];
return parameters;
}
- (NSString*)installationId {
NSString *uuid = [[NSUserDefaults standardUserDefaults] valueForKey:INSTALLATIONID];
if (uuid == nil) {
uuid_t buffer;
char str[37];
uuid_generate(buffer);
uuid_unparse_upper(buffer, str);
uuid = [NSString stringWithFormat:@"%s", str];
DLog(@"Generated UUID %@", uuid);
[[NSUserDefaults standardUserDefaults] setValue:uuid forKey:INSTALLATIONID];
}
return uuid;
}
#pragma mark Authorization Manager
-(IBAction)openAuthPage:(id)sender {
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.last.fm/api/auth?api_key=%@",API_KEY]]];
}
-(void)newWebServiceSessionKeyAcquired {
[[GrowlHub sharedManager] postGrowlNotificationWithName:SP_Growl_LoginComplete andTitle:@"Authorization Successful" andDescription:@"ScrobblePod is now authorized to communicate with Last.fm" andImage:nil andIdentifier:SP_Growl_LoginComplete];
}
-(void)newSubmissionSessionKeyAcquired {
[self detachNowPlayingThread];
[self detachScrobbleThreadWithoutConsideration:NO];
[self popApiQueue];
}
-(void)primeSongPlayCache {
BGTrackCollector *collector = [[BGTrackCollector alloc] init];
NSArray *allTracks = [collector collectTracksFromXMLFile:self.fullXmlPath withCutoffDate:[[NSCalendarDate date] dateByAddingYears:-35 months:0 days:0 hours:0 minutes:0 seconds:0] includingPodcasts:YES includingVideo:YES ignoringComment:@"" ignoringGenre:nil withMinimumDuration:30];
[collector release];
NSMutableDictionary *primedCache = [[NSMutableDictionary alloc] initWithCapacity:allTracks.count];
BGLastFmSong *currentSong;
for (currentSong in allTracks) {
[primedCache setObject:[NSNumber numberWithInt:currentSong.playCount] forKey:currentSong.persistentIdentifier];
}
[primedCache writeToFile:[self pathForCachedDatabase] atomically:YES]; // DISABLE TEMPORARILY SO THAT WE ACTUALLY HAVE SOME EXTRA PLAYS
[primedCache release];
}
-(NSString *)pathForCachedDatabase { //Method from CocoaDevCentral.com
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *folder = @"~/Library/Application Support/ScrobblePod/";
folder = [folder stringByExpandingTildeInPath];
if ([fileManager fileExistsAtPath: folder] == NO) [fileManager createDirectoryAtPath: folder withIntermediateDirectories:YES attributes:nil error:NULL];
NSString *fileName = @"PlayCountDB.xml";
return [folder stringByAppendingPathComponent: fileName];
}
-(BOOL)cacheFileExists {
return [[NSFileManager defaultManager] fileExistsAtPath:[self pathForCachedDatabase]];
}
-(void)menuDidClose:(NSMenu *)menu {
[(StatusItemView *)statusItem.view setSelected:NO];
[infoView resetBlueToOffState];
[infoView stopScrolling];
}
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
prefController = [[PreferencesController alloc] init];
NSString *username, *wsKey;
username = [defaults objectForKey:BGPrefUsername];
wsKey = [defaults objectForKey:BGWebServiceSessionKey];
if ([defaults boolForKey:BGPrefFirstRunKey] || !username || username.length==0 || [username isEqualToString:@"..."] || !wsKey || wsKey.length==0) [self doFirstRun];
[self setAppropriateRoundedString];
// let the user know if scrobbling is enabled
[self performSelector:@selector(podWatcherMountedPod:) withObject:nil afterDelay:10.0];
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
DLog(@"Quit Decision - NP:%d\nSC:%d",isPostingNP,isScrobbling);
if (isPostingNP == YES || isScrobbling == YES)
return NSTerminateLater;
return NSTerminateNow;
}
-(void)doFirstRun {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *overrideCalendarDate = [[[NSCalendarDate calendarDate] dateByAddingYears:0 months:0 days:0 hours:0 minutes:0 seconds:-60] descriptionWithCalendarFormat:DATE_FORMAT_STRING];
[defaults setValue:overrideCalendarDate forKey:BGPrefLastScrobbled];
[defaults setBool:YES forKey:BGPrefLastScrobbledWithCorrectOffsetFromGMT];
[defaults setBool:FALSE forKey:BGPrefFirstRunKey];
[NSApp activateIgnoringOtherApps:YES];
[welcomeWindow center];
[welcomeWindow orderFront:self];
}
-(IBAction)quit:(id)sender;
{
wantsToQuit = YES;
[infoView setStringValue:@"Wating for operations to finish before quitting..." isActive:NO];
[NSApp terminate:self];
}
-(void)applicationWillTerminate:(NSNotification *)aNotification {
if (statusItem) [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void) dealloc {
[statusItem release];
[scrobbleSound release];
[prefController release];
[tagAutocompleteList release];
[friendsAutocompleteList release];
[xmlWatcher release];
[apiQueue release];
[super dealloc];
}
#pragma mark Delegate Methods
-(void)podWatcherMountedPod:(NSNotification *)notification {
[[BGScrobbleDecisionManager sharedManager] refreshDecisionAndNotifyIfChanged:YES];
}
-(void)amdsSyncCompleted:(NSNotification *)notification {
[self detachScrobbleThreadWithoutConsideration:NO];
}
-(void)xmlFileChanged:(NSNotification *)notification {
DLog(@"OMG! XML change!");
[self detachScrobbleThreadWithoutConsideration:NO];
}
-(void)workspaceDidLaunchApplication:(NSNotification *)notification {
if ([[[notification userInfo] objectForKey:@"NSApplicationName"] isEqualToString:@"iTunes"]) {
[self setAppropriateRoundedString];
}
}
-(void)workspaceDidTerminateApplication:(NSNotification *)notification {
if ([[[notification userInfo] objectForKey:@"NSApplicationName"] isEqualToString:@"iTunes"]) {
[self setAppropriateRoundedString];
}
}
-(void)iTunesWatcherDidDetectStartOfNewSongWithName:(NSString *)aName artist:(NSString *)anArtist artwork:(NSImage *)anArtwork {
if (wantsToQuit == YES) return;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSImage *growlImage;
if (anArtwork) {
growlImage = anArtwork;
} else {
growlImage = [NSImage imageNamed:@"iTunesSmall"];
}
NSData *tiffImage = [NSData dataWithData:[growlImage TIFFRepresentation]];
[[GrowlHub sharedManager] postGrowlNotificationWithName:SP_Growl_TrackChanged andTitle:aName andDescription:anArtist andImage:tiffImage andIdentifier:@"SP_Track"];
tiffImage = nil;
growlImage = nil;
NSString *songTitleString;
if (anArtist == nil && aName == nil) {
songTitleString = [NSString stringWithFormat:@"Unnamed Track"];
}
else if (aName == nil) {
songTitleString = [NSString stringWithFormat:@"%@ ", anArtist];
}
else if (anArtist == nil) {
songTitleString = [NSString stringWithFormat:@"%@ ", aName];
}
else {
songTitleString = [NSString stringWithFormat:@"%@: %@ ", anArtist, aName];
}
[infoView setStringValue:songTitleString isActive:YES];
[self detachNowPlayingThread];
if ([arrowWindow isVisible]) [self updateTagLabel:self];
[pool drain];
}
-(void)iTunesWatcherDidDetectSongStopped {
[self setAppropriateRoundedString];
if ([arrowWindow isVisible]) [arrowWindow close];
}
-(NSString *)fullXmlPath {
return [[[NSUserDefaults standardUserDefaults] stringForKey:BGPrefXmlLocation] stringByExpandingTildeInPath];
}
-(IBAction)updateTagLabel:(id)sender {
NSString *properString = nil;
BGLastFmSong *currentSong = [[iTunesWatcher sharedManager] currentSong];
if (currentSong) {
if (!isLoadingCommonTags) {
[arrowWindow setShouldClose:NO];
int selectedTag = [tagTypeChooser selectedSegment];
if (selectedTag==0) {
properString = currentSong.title;
} else if (selectedTag==1) {
properString = currentSong.artist;
} else if (selectedTag==2) {
properString = currentSong.album;
}
tagLabel.stringValue = [NSString stringWithFormat:@"Tags for: \"%@\"", properString];
[NSThread detachNewThreadSelector:@selector(populateCommonTags) toTarget:self withObject:nil];
[arrowWindow setShouldClose:YES];
}
} else {
[arrowWindow close];
}
}
-(NSArray *)tokenField:(NSTokenField *)tokenField completionsForSubstring:(NSString *)substring indexOfToken:(int)tokenIndex indexOfSelectedItem:(int *)selectedIndex {
NSArray *arrayToMatchAgainst;
arrayToMatchAgainst = (tokenField==tagEntryField ? tagAutocompleteList : friendsAutocompleteList);
NSMutableArray *matchingTags = [NSMutableArray array];
NSString *substringLower = [substring lowercaseString];
NSString *currentTag;
for (currentTag in arrayToMatchAgainst) {
if ([currentTag.lowercaseString rangeOfString:substringLower].location == 0) [matchingTags addObject:currentTag];
}
return matchingTags;
}
@synthesize tagAutocompleteList;
@synthesize friendsAutocompleteList;
-(void)populateCommonTags {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
isLoadingCommonTags = YES;
[commonTagsField setObjectValue:[NSArray array]];
[commonTagsLoadingView setHidden:NO];
[commonTagsLoadingIndicator startAnimation:self];
NSArray *tagList = [self popularTagsForCurrentSong];
if (tagList.count > 0) {
self.tagAutocompleteList = tagList;
} else {
self.tagAutocompleteList = [NSArray arrayWithObjects:@"Common", @"Tags", @"Could", @"Not", @"Be", @"Loaded",nil];
}
[commonTagsField setObjectValue:self.tagAutocompleteList];
[commonTagsLoadingIndicator stopAnimation:self];
[commonTagsLoadingView setHidden:YES];
isLoadingCommonTags = NO;
[pool drain];
}
-(NSArray *)popularTagsForCurrentSong {
NSMutableArray *tagList = [NSMutableArray array];
int tagType = tagTypeChooser.selectedSegment;
BOOL needAlbum = BGOperationType_Album == tagType;
BOOL needTrack = BGOperationType_Song == tagType;
if ([self dataIsAvailableForAPICallUsingArtist:NO andAlbum:needAlbum andTrack:needTrack]) {
NSString *sessionKey = authManager.webServiceSessionKey;
NSString *apiMethod;
switch (tagType) {
case BGOperationType_Song:
apiMethod = @"track.getTopTags";
break;
case BGOperationType_Artist:
apiMethod = @"artist.getTopTags";
break;
case BGOperationType_Album:
apiMethod = nil;//@"album.addTags";
break;
default:
apiMethod = nil;
break;
}
if (apiMethod) {
BGLastFmWebServiceParameterList *params = [[BGLastFmWebServiceParameterList alloc] initWithMethod:apiMethod andSessionKey:sessionKey];
BGLastFmSong *currentSong = [iTunesWatcher sharedManager].currentSong;
[params setParameter:currentSong.artist forKey:@"artist"];
if (needTrack) [params setParameter:currentSong.title forKey:@"track"];
if (needAlbum) [params setParameter:currentSong.album forKey:@"album"];
BGLastFmWebServiceCaller *sc = [[BGLastFmWebServiceCaller alloc] init];
BGLastFmWebServiceResponse *resp = [sc callWithParameters:params usingPostMethod:YES usingAuthentication:NO];
NSXMLDocument *tagsXML = resp.responseDocument;
NSArray *tagNodes = [tagsXML nodesForXPath:@"/lfm/toptags/tag/name" error:nil];
NSXMLNode *currentTagNode;
for (currentTagNode in tagNodes) {
[tagList addObject:[currentTagNode stringValue]];
}
[sc release];
[params release];
}
}
return tagList;
}
#pragma mark Scrobbling Status Methods
-(void)setAppropriateRoundedString {
if (wantsToQuit == YES) return;
iTunesWatcher *tunesWatcher = [iTunesWatcher sharedManager];
if ([tunesWatcher itunesIsRunning]) {
if (![tunesWatcher iTunesIsPlaying]) {
[infoView setStringValue:@"iTunes is not playing" isActive:NO];
} else {
[infoView setActive:YES];
}
} else {
[infoView setStringValue:@"iTunes is not running" isActive:NO];
}
}
-(void)setIsScrobblingWithNumber:(NSNumber *)aNumber {
[self setIsScrobbling: [aNumber boolValue] ];
}
-(void)setIsScrobbling:(BOOL)aBool {
isScrobbling = aBool;
if (!isPostingNP && !isScrobbling && wantsToQuit == YES)
[NSApp replyToApplicationShouldTerminate:YES];
}
-(void)setIsPostingNP:(BOOL)aBool
{
isPostingNP = aBool;
if (!isPostingNP && !isScrobbling && wantsToQuit == YES)
[NSApp replyToApplicationShouldTerminate:YES];
}
-(void)setWantsToQuit:(BOOL)aBool {
wantsToQuit = aBool;
}
#pragma mark Last.fm API Interaction
-(void)queueApiCall:(BGLastFmWebServiceParameterList *)theCall popQueueToo:(BOOL)shouldPopQueue {
[apiQueue addObject:theCall];
if (shouldPopQueue) [self popApiQueue];
}
-(void)popApiQueue {
if (apiQueue.count > 0) {
BGLastFmWebServiceParameterList *params = [apiQueue objectAtIndex:0];
//DLog(@"Going to pop queue with params:%@",params);
BGLastFmWebServiceCaller *sc = [[BGLastFmWebServiceCaller alloc] init];
BGLastFmWebServiceResponse *resp = [sc callWithParameters:params usingPostMethod:YES usingAuthentication:YES];
// DLog(@"Got response: '%@'",[resp className]);
if (resp.wasOK) {
[apiQueue removeObject:params];
if (apiQueue.count > 0) [self performSelector:@selector(popApiQueue) withObject:nil afterDelay:1.0];
} else if (resp.failedDueToInvalidKey) {
[self openAuthPage:self];
}
[sc release];
}
}
-(IBAction)loveSong:(id)sender {
[self startTasteCommand:ServiceWorker_LoveCommand];
}
-(IBAction)banSong:(id)sender {
[self startTasteCommand:ServiceWorker_BanCommand];
}
-(BOOL)dataIsAvailableForAPICallUsingArtist:(BOOL)useArtist andAlbum:(BOOL)useAlbum andTrack:(BOOL)useTrack {
iTunesWatcher *tunesWatcher = [iTunesWatcher sharedManager];
NSString *username = authManager.username;
NSString *sessionKey = authManager.webServiceSessionKey;
BOOL isPlaying = tunesWatcher.iTunesIsPlaying;
if (isPlaying && username && username.length > 0 && sessionKey && sessionKey.length > 0) {
BGLastFmSong *currentSong = tunesWatcher.currentSong;
if (currentSong) {
NSString *songTitle = currentSong.title;
NSString *songArtist = currentSong.artist;
NSString *songAlbum = currentSong.album;
return ( (!useArtist || (useArtist && songArtist)) && (!useAlbum || (useAlbum && songAlbum)) && (!useTrack || (useTrack && songTitle)) );
} else return NO;
} else return NO;
}
-(void)startTasteCommand:(NSString *)tasteCommand { //tasteCommand is either @"track.love" or @"track.ban"
if ([self dataIsAvailableForAPICallUsingArtist:YES andAlbum:NO andTrack:YES]) {
NSString *sessionKey = authManager.webServiceSessionKey;
BGLastFmSong *currentSong = [iTunesWatcher sharedManager].currentSong;
BGLastFmWebServiceParameterList *params = [[BGLastFmWebServiceParameterList alloc] initWithMethod:tasteCommand andSessionKey:sessionKey];
[params setParameter:currentSong.title forKey:@"track"];
[params setParameter:currentSong.artist forKey:@"artist"];
[self queueApiCall:params popQueueToo:YES];
[params release];
}
}
-(IBAction)tagSong:(id)sender {
[tagEntryField setObjectValue:[NSArray array]];
[self showArrowWindowForView:tagEntryView];
[self updateTagLabel:self];
[arrowWindow makeFirstResponder:tagEntryField];
}
-(IBAction)performTagSong:(id)sender {
[arrowWindow setShouldClose:NO];
int tagType = [tagTypeChooser selectedSegment];
BOOL needAlbum = BGOperationType_Album == tagType;
BOOL needTrack = BGOperationType_Song == tagType;
if ([self dataIsAvailableForAPICallUsingArtist:YES andAlbum:needAlbum andTrack:needTrack]) {
NSString *apiMethod;
switch (tagType) {
case BGOperationType_Song:
apiMethod = @"track.addTags";
break;
case BGOperationType_Artist:
apiMethod = @"artist.addTags";
break;
case BGOperationType_Album:
apiMethod = @"album.addTags";
break;
default:
apiMethod = nil;
break;
}
if (apiMethod != nil) {
NSString *sessionKey = authManager.webServiceSessionKey;
BGLastFmSong *currentSong = [iTunesWatcher sharedManager].currentSong;
BGLastFmWebServiceParameterList *params = [[BGLastFmWebServiceParameterList alloc] initWithMethod:apiMethod andSessionKey:sessionKey];
[params setParameter:currentSong.artist forKey:@"artist"];
if (needTrack) [params setParameter:currentSong.title forKey:@"track"];
if (needAlbum) [params setParameter:currentSong.album forKey:@"album"];
NSArray *theTags = [tagEntryField objectValue];
if (theTags.count > 0) {
[params setParameter:[theTags componentsJoinedByString:@","] forKey:@"tags"];
}
[self queueApiCall:params popQueueToo:YES];
[params release];
}
}
[arrowWindow setShouldClose:YES];
}
-(IBAction)recommendSong:(id)sender {
[self showArrowWindowForView:recommendationEntryView];
// [self updateFriendsList];
//[arrowWindow makeFirstResponder:tagEntryField];
}
-(IBAction)performRecommendSong:(id)sender {
[arrowWindow setShouldClose:NO];
int tagType = recommendTypeChooser.selectedSegment;
BOOL needAlbum = BGOperationType_Album == tagType;
BOOL needTrack = BGOperationType_Song == tagType;
if ([self dataIsAvailableForAPICallUsingArtist:YES andAlbum:needAlbum andTrack:needTrack]) {
NSString *apiMethod;
switch (tagType) {
case BGOperationType_Song:
apiMethod = @"track.share";
break;
case BGOperationType_Artist:
apiMethod = @"artist.share";
break;
case BGOperationType_Album:
apiMethod = nil;//@"album.share"; //album.share not yet supported by last.fm
break;
default:
apiMethod = nil;
break;
}
if (apiMethod != nil) {
NSString *sessionKey = authManager.webServiceSessionKey;
BGLastFmSong *currentSong = [iTunesWatcher sharedManager].currentSong;
BGLastFmWebServiceParameterList *params = [[BGLastFmWebServiceParameterList alloc] initWithMethod:apiMethod andSessionKey:sessionKey];
[params setParameter:currentSong.artist forKey:@"artist"];
if (needTrack) [params setParameter:currentSong.title forKey:@"track"];
if (needAlbum) [params setParameter:currentSong.album forKey:@"album"];
NSArray *theFriends = [friendsEntryField objectValue];
if (theFriends.count > 10) theFriends = [theFriends objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 9)]];
if (theFriends.count > 0) {
[params setParameter:[theFriends componentsJoinedByString:@","] forKey:@"recipient"];
}
NSString *theMessage = recommendMessageField.stringValue;
if (theMessage.length > 0) [params setParameter:theMessage forKey:@"message"];
[self queueApiCall:params popQueueToo:YES];
[params release];
}
}
[arrowWindow setShouldClose:YES];
}
-(void)updateFriendsList {
self.friendsAutocompleteList = [self friendsForUser];
}
-(NSArray *)friendsForUser {
NSMutableArray *friendsList = [NSMutableArray array];
if ([self dataIsAvailableForAPICallUsingArtist:NO andAlbum:NO andTrack:NO]) {
NSString *username = authManager.username;
NSString *sessionKey = authManager.webServiceSessionKey;
BGLastFmWebServiceParameterList *params = [[BGLastFmWebServiceParameterList alloc] initWithMethod:@"user.getFriends" andSessionKey:sessionKey];
[params setParameter:username forKey:@"user"];
BGLastFmWebServiceCaller *sc = [[BGLastFmWebServiceCaller alloc] init];
BGLastFmWebServiceResponse *resp = [sc callWithParameters:params usingPostMethod:YES usingAuthentication:NO];
NSXMLDocument *friendsXML = resp.responseDocument;
NSArray *friendNodes = [friendsXML nodesForXPath:@"/lfm/friends/user/name" error:nil];
NSXMLNode *currentNameNode;
for (currentNameNode in friendNodes) {
[friendsList addObject:[currentNameNode stringValue]];
}
[sc release];
[params release];
}
return friendsList;
}
-(void)showArrowWindowForView:(NSView *)theView {
float xVal, yVal;
NSPoint statusItemLocation = [[[statusItem view] window] frame].origin;
xVal = statusItemLocation.x;
yVal = statusItemLocation.y;
[NSApp activateIgnoringOtherApps:YES];
[statusMenu cancelTracking];
[arrowWindow setFrame:theView.frame display:YES];
[arrowWindow setContentView:theView];
[arrowWindow positionAtMenuBarForHorizontalValue:xVal-(theView.frame.size.width/2)+(statusItem.view.frame.size.width/2) andVerticalValue:yVal-theView.frame.size.height+2];
[self performSelector:@selector(showArrowWindow) withObject:nil afterDelay:0.15];
}
-(void)showArrowWindow {
arrowWindow.alphaValue = 0.0;
[arrowWindow makeKeyAndOrderFront:self];
[arrowWindow makeMainWindow];
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.1];
[arrowWindow.animator setAlphaValue:1.0f];
[NSAnimationContext endGrouping];
}
#pragma mark Preferences
-(IBAction)showAboutPanel:(id)sender {
[NSApp activateIgnoringOtherApps:YES];
[NSApp orderFrontStandardAboutPanel:self];
}
-(IBAction)raiseLoginPanel:(id)sender {
if (!prefController) {
prefController = [[PreferencesController alloc] init];
}
[prefController showWindow:self];
}
#pragma mark Main Scrobbling Methods
-(void)detachScrobbleThreadWithoutConsideration:(BOOL)passThrough {
if (isScrobbling)
return;
BOOL shouldContinue = passThrough;
if (!passThrough)
shouldContinue = [[BGScrobbleDecisionManager sharedManager] shouldScrobble];
if (shouldContinue)
[NSThread detachNewThreadSelector:@selector(postScrobble) toTarget:self withObject:nil];
}
-(IBAction)goToUserProfilePage:(id)sender {
[statusMenu cancelTracking];
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.last.fm/user/%@",[[NSUserDefaults standardUserDefaults] stringForKey:BGPrefUsername] ] ]];
}
-(IBAction)manualScrobble:(id)sender {
NSCalendarDate *lastScrobbled = [NSCalendarDate dateWithString:[[NSUserDefaults standardUserDefaults] valueForKey:BGPrefLastScrobbled] calendarFormat:DATE_FORMAT_STRING];
[NSApp activateIgnoringOtherApps:YES];
int shouldForceScrobble = NSRunAlertPanel(@"Scrobble songs before syncing your iPod?", @"Songs played on your iPod after %@ will not be scrobbled when the iPod is next connected." , @"Scrobble Anyway", @"Cancel", nil, [lastScrobbled relativeDateDescription], nil);
if (shouldForceScrobble == NSAlertDefaultReturn) [self detachScrobbleThreadWithoutConsideration:YES];
}
-(void)postScrobble {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:@selector(setIsScrobblingWithNumber:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];// setIsScrobbling:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *lastScrobbleDateString = [defaults valueForKey:BGPrefLastScrobbled];
DLog(@"-- Last Scrobbled Date: %@",lastScrobbleDateString);
NSCalendarDate *applescriptInputDateString = [NSCalendarDate dateWithString:lastScrobbleDateString calendarFormat:DATE_FORMAT_STRING];// descriptionWithCalendarFormat:DATE_FORMAT_STRING];
DLog(@"Started collecting previously played tracks");
BGTrackCollector *trackCollector = [[BGTrackCollector alloc] init];
NSArray *recentTracksSimple = [trackCollector collectTracksFromXMLFile:self.fullXmlPath
withCutoffDate:applescriptInputDateString
includingPodcasts:(![defaults boolForKey:BGPrefShouldIgnorePodcasts])
includingVideo:(![defaults boolForKey:BGPrefShouldIgnoreVideo])
ignoringComment:([defaults boolForKey:BGPrefShouldIgnoreComments] ? [defaults stringForKey:BGPrefIgnoreCommentString] : nil)
ignoringGenre:([defaults boolForKey:BGPrefShouldIgnoreGenre] ? [defaults stringForKey:BGPrefIgnoreGenreString] : nil)
withMinimumDuration:[defaults integerForKey:BGPrefIgnoreShortLength]];//![defaults boolForKey:BGPrefShouldIgnorePodcasts]
[trackCollector release];
DLog(@"Assigning song list to variable");
NSArray *allRecentTracks = nil;
// Calculate extra plays, and insert them into recent songs array
if ([defaults boolForKey:BGPrefShouldDoMultiPlay]) {
BGMultipleSongPlayManager *multiPlayManager = [[BGMultipleSongPlayManager alloc] init];
allRecentTracks = [multiPlayManager completeSongListForRecentTracks:recentTracksSimple sinceDate:applescriptInputDateString];
[allRecentTracks retain];
[multiPlayManager release];
} else {
allRecentTracks = recentTracksSimple;
recentTracksSimple = nil;
}
DLog(@"Using multi-play: %@",([defaults boolForKey:BGPrefShouldDoMultiPlay] ? @"Yes" : @"No"));
DLog(@"Got all recent tracks:\n%@",allRecentTracks);
int recentTracksCount = allRecentTracks.count;
if (recentTracksCount > 0) {
if (recentTracksCount > 1) [[GrowlHub sharedManager] postGrowlNotificationWithName:SP_Growl_StartedScrobbling andTitle:SP_Growl_StartedScrobbling andDescription:[NSString stringWithFormat:@"Scrobbling %d track%@ to Last.fm", recentTracksCount, ( recentTracksCount == 1 ? @"" : @"s" )] andImage:nil andIdentifier:SP_Growl_StartedScrobbling];
int scrobbleAttempts = 0;
while (scrobbleAttempts < 2) {
NSString *theSessionKey = authManager.submissionSessionKey;
NSString *thePostAddress = authManager.scrobbleSubmissionURL;
if (theSessionKey && thePostAddress && theSessionKey.length>0 && thePostAddress.length>0) {
BGLastFmScrobbler *theScrobbler = [[BGLastFmScrobbler alloc] init];
BGLastFmScrobbleResponse *scrobbleResponse = [theScrobbler performScrobbleWithSongs:allRecentTracks andSessionKey:theSessionKey toURL:[NSURL URLWithString:thePostAddress]];
[scrobbleResponse retain];
if (!scrobbleResponse.wasSuccessful) {
if (scrobbleResponse.responseType==SCROBBLE_RESPONSE_BADAUTH) {
// Need to rehandshake
[authManager fetchNewSubmissionSessionKeyUsingWebServiceSessionKey];
scrobbleAttempts = 2;
} else if (scrobbleResponse.responseType==SCROBBLE_RESPONSE_FAILED) {
[[GrowlHub sharedManager] postGrowlNotificationWithName:SP_Growl_FailedScrobbling andTitle:@"Tracks could not be scrobbled" andDescription:[NSString stringWithFormat:@"Server said \"%@\"",[scrobbleResponse failureReason]] andImage:nil andIdentifier:SP_Growl_StartedScrobbling];
[prefController addHistoryWithSuccess:NO andDate:[NSDate date] andDescription:[NSString stringWithFormat:@"Scrobble failed: ",[scrobbleResponse failureReason]]];
} else if (scrobbleResponse.responseType==SCROBBLE_RESPONSE_UNKNOWN && scrobbleAttempts==0) {
// Because the scrobble post URL is stored in the user defaults (and handshake is not updated on launch), there is a
// chance that the stored URL (IP address) may no longer point to Last.fm. In this case, we re-handshake.
[authManager fetchNewSubmissionSessionKeyUsingWebServiceSessionKey];
scrobbleAttempts = 2;
} else {
if (scrobbleAttempts==1) {
[[GrowlHub sharedManager] postGrowlNotificationWithName:SP_Growl_FailedScrobbling andTitle:@"Tracks could not be scrobbled" andDescription:@"Scrobbling probably timed out" andImage:nil andIdentifier:SP_Growl_StartedScrobbling];
[prefController addHistoryWithSuccess:NO andDate:[NSDate date] andDescription:@"Scrobble failed likely due to timeout"];
}
}
} else {
[prefController addHistoryWithSuccess:YES andDate:[NSDate date] andDescription:[NSString stringWithFormat:@"Scrobbled %d song%@",recentTracksCount,(recentTracksCount==1?@"":@"s")]];
NSCalendarDate *returnedDate = [scrobbleResponse lastScrobbleDate];
DLog(@"-- After Scrobbling Date Returned: %@",returnedDate);
if (returnedDate!=nil) {
NSString *updatedDateString = [returnedDate descriptionWithCalendarFormat:DATE_FORMAT_STRING];
[defaults setValue:updatedDateString forKey:BGPrefLastScrobbled];
DLog(@"-- Setting Last Scrobbling Date To: %@",updatedDateString);
[defaults synchronize];
}
[defaults setObject: [NSNumber numberWithInt: [[NSUserDefaults standardUserDefaults] integerForKey:BGTracksScrobbledTotal]+recentTracksCount ] forKey:BGTracksScrobbledTotal];
if (recentTracksCount>1) [[GrowlHub sharedManager] postGrowlNotificationWithName:SP_Growl_FinishedScrobbling andTitle:@"Finished Scrobbling" andDescription:[NSString stringWithFormat:@"%d track%@ successfully scrobbled to Last.fm",recentTracksCount,( recentTracksCount == 1 ? @"" : @"s" )] andImage:nil andIdentifier:SP_Growl_StartedScrobbling];
if ([defaults boolForKey:BGPrefShouldPlaySound]) [self playScrobblingSound];
scrobbleAttempts = 2;
}
[scrobbleResponse release];
[theScrobbler release];
} else {
DLog(@"Scrobbling didn't work because not all values set:\n Key:'%@'\n URL:%@",theSessionKey,thePostAddress);
[prefController addHistoryWithSuccess:NO andDate:[NSDate date] andDescription:@"Handshake Failed"];
}//end if handshake worked
scrobbleAttempts++;
} //end while around handshake&scrobble processes
}
if ([defaults boolForKey:BGPrefShouldDoMultiPlay]) {
// Clang complains, but I think it's wrong. This if statement could also fix the mysterious crash on thread 6.
[allRecentTracks release];
}
[self performSelectorOnMainThread:@selector(setIsScrobblingWithNumber:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];// setIsScrobbling:NO];
[self performSelectorOnMainThread:@selector(detachNowPlayingThread) withObject:nil waitUntilDone:YES];
// URL Cache trick
// NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
// [NSURLCache setSharedURLCache:sharedCache];
// [sharedCache release];
[pool drain];
}
-(void)playScrobblingSound {
if (!scrobbleSound) {
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"bubbles" ofType:@"aif"];
scrobbleSound = [[NSSound alloc] initWithContentsOfFile:soundPath byReference:NO];
}
[scrobbleSound play];
}
-(void)detachNowPlayingThread {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (!isPostingNP && ![defaults boolForKey:BGPrefWantNowPlaying])
return;
iTunesWatcher *tunesWatcher = [iTunesWatcher sharedManager];
[tunesWatcher manuallyRetrieveCurrentSongInfo];
BGLastFmSong *currentPlayingSong = tunesWatcher.currentSong;
NSString *commentToIgnore = [defaults stringForKey:BGPrefIgnoreCommentString];
NSString *genreToIgnore = [defaults stringForKey:BGPrefIgnoreGenreString];
if ([defaults boolForKey:BGPrefShouldIgnoreComments] && currentPlayingSong.comment && commentToIgnore != nil && [commentToIgnore length] > 0 && [currentPlayingSong.comment containsString:commentToIgnore])
return;
else if ([defaults boolForKey:BGPrefShouldIgnoreGenre] && currentPlayingSong.genre && genreToIgnore != nil && [genreToIgnore length] > 0 && [currentPlayingSong.genre containsString:genreToIgnore])
return;
else if ([defaults boolForKey:BGPrefShouldIgnoreGenre] && currentPlayingSong.genre && genreToIgnore != nil && [genreToIgnore length] == 0 && [currentPlayingSong.genre isEqualToString:genreToIgnore])
return;
else if (tunesWatcher.currentSong == nil)
return;
[NSThread detachNewThreadSelector:@selector(postNowPlayingNotificationForSong:) toTarget:self withObject:currentPlayingSong];
}
-(void)postNowPlayingNotificationForSong:(BGLastFmSong *)nowPlayingSong {
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
DLog(@"Posting now playing notification");
[self setIsPostingNP:YES];
if (nowPlayingSong) {
int notifyAttempts = 0;
while (notifyAttempts < 2)
{
NSString *theSessionKey = authManager.submissionSessionKey;
NSString *thePostAddress = authManager.nowPlayingSubmissionURL;
if (theSessionKey && thePostAddress && theSessionKey.length>0 && thePostAddress.length>0) {
NSString *npPostString = [NSString stringWithFormat:@"s=%@&a=%@&t=%@&b=%@&l=%d&n=&m=",theSessionKey,nowPlayingSong.artist.urlEncodedString,nowPlayingSong.title.urlEncodedString,nowPlayingSong.album.urlEncodedString,nowPlayingSong.length];