// // AutoLyrics.m // iLyrics // // Created by Kim Wittenburg on 16.06.12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #import "AutoLyrics.h" @implementation AutoLyrics { NSTimer *timer; NSUInteger interval; BOOL enabled; } @synthesize replaceOldLyrics; AutoLyrics *instace; +(AutoLyrics *)autoLyrics { if (instace == nil) { instace = [[AutoLyrics alloc] init]; [instace loadFromDefaults:[NSUserDefaults standardUserDefaults]]; } return instace; } -(id)init { enabled = NO; replaceOldLyrics = NO; [self setInterval:5]; return [super init]; } -(BOOL)enabled { return enabled; } -(void)setEnabled:(BOOL)flag { enabled = flag; } //In seconds -(void)setInterval:(NSUInteger)i { interval = i; if (timer) { [timer invalidate]; } timer = [[NSTimer alloc] initWithFireDate:[[NSDate alloc]init] interval:interval target:self selector:@selector(shouldSetLyrics:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; } -(NSUInteger)interval { return interval; } -(void)shouldSetLyrics: (NSTimer *) sender { if (enabled) { iTunesApplication *iTunes = [[iLyrics sharediLyrics] iTunes]; iTunesTrack *current = [iTunes currentTrack]; if ([current name] != nil) { if (replaceOldLyrics || [[current lyrics] length] == 0) { [self setLyrics]; } } } } -(void)setLyrics { iTunesApplication *iTunes = [[iLyrics sharediLyrics] iTunes]; iTunesTrack *track = [iTunes currentTrack]; id hoster = [[iLyrics sharediLyrics] preferredHoster]; [hoster startNewSearchForQuery:[NSString stringWithFormat:@"%@ - %@", [track name], [track artist]]]; NSArray *results = [hoster nextResults]; if (results != nil && [results count] > 0) { Lyrics *lyrics = [hoster lyricsBySearchResult:[results objectAtIndex:0]]; [track setLyrics:[lyrics lyrics]]; [GrowlApplicationBridge notifyWithTitle:NSLocalizedString(@"Growl.messages.lyricsSent.title", @"") description:[NSString stringWithFormat:NSLocalizedString(@"Growl.messages.lyricsSent.detail", @""), [track name]] notificationName:@"Lyrics sent to iTunes" iconData:nil priority:0 isSticky:NO clickContext:nil]; } } -(void)saveToDefaults:(NSUserDefaults *)defaults { [defaults setBool:enabled forKey:@"Auto Lyrics Enabled"]; [defaults setBool:replaceOldLyrics forKey:@"Auto Lyrics replaces old lyrics"]; } -(void)loadFromDefaults:(NSUserDefaults *)defaults { enabled = [defaults boolForKey:@"Auto Lyrics Enabled"]; replaceOldLyrics = [defaults boolForKey:@"Auto Lyrics replaces old lyrics"]; } @end