cog/Application/PlaybackEventController.m

389 lines
15 KiB
Matlab
Raw Normal View History

2009-03-05 17:04:16 +00:00
//
// PlaybackEventController.m
// Cog
//
// Created by Vincent Spader on 3/5/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
#import "PlaybackEventController.h"
#import "AudioScrobbler.h"
NSString *TrackNotification = @"com.apple.iTunes.playerInfo";
NSString *TrackArtist = @"Artist";
NSString *TrackAlbum = @"Album";
NSString *TrackTitle = @"Name";
NSString *TrackGenre = @"Genre";
NSString *TrackNumber = @"Track Number";
NSString *TrackLength = @"Total Time";
NSString *TrackPath = @"Location";
NSString *TrackState = @"Player State";
2021-02-26 20:01:48 +00:00
typedef NS_ENUM(NSInteger, TrackStatus) { TrackPlaying, TrackPaused, TrackStopped };
@implementation PlaybackEventController {
AudioScrobbler *scrobbler;
NSOperationQueue *queue;
PlaylistEntry *entry;
Boolean didGainUN API_AVAILABLE(macosx(10.14));
}
- (void)initDefaults {
NSDictionary *defaultsDictionary = @{
@"enableAudioScrobbler" : @YES,
@"automaticallyLaunchLastFM" : @NO,
@"notifications.enable" : @YES,
@"notifications.itunes-style" : @YES,
@"notifications.show-album-art" : @YES
};
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDictionary];
2009-03-05 17:04:16 +00:00
}
2021-02-26 20:01:48 +00:00
- (id)init {
self = [super init];
if (self) {
[self initDefaults];
didGainUN = NO;
2021-02-26 20:01:48 +00:00
if (@available(macOS 10.14, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center
requestAuthorizationWithOptions:UNAuthorizationOptionAlert
completionHandler:^(BOOL granted, NSError *_Nullable error) {
self->didGainUN = granted;
if (granted) {
UNNotificationAction *skipAction = [UNNotificationAction
actionWithIdentifier:@"skip"
title:@"Skip"
options:UNNotificationActionOptionNone];
UNNotificationCategory *playCategory = [UNNotificationCategory
categoryWithIdentifier:@"play"
actions:@[ skipAction ]
intentIdentifiers:@[]
options:UNNotificationCategoryOptionNone];
[center setNotificationCategories:
[NSSet setWithObject:playCategory]];
}
}];
[center setDelegate:self];
}
2021-02-26 20:01:48 +00:00
queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];
scrobbler = [[AudioScrobbler alloc] init];
2014-12-04 05:36:55 +00:00
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
2021-02-26 20:01:48 +00:00
entry = nil;
2021-02-26 20:01:48 +00:00
}
return self;
2009-03-05 17:04:16 +00:00
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
2021-02-26 20:01:48 +00:00
withCompletionHandler:
(void (^)(UNNotificationPresentationOptions options))completionHandler
API_AVAILABLE(macos(10.14)) {
UNNotificationPresentationOptions presentationOptions = UNNotificationPresentationOptionAlert;
completionHandler(presentationOptions);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
2021-02-26 20:01:48 +00:00
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(macos(10.14)) {
if ([[response actionIdentifier] isEqualToString:@"skip"]) {
[playbackController next:self];
}
}
2021-02-26 20:01:48 +00:00
- (NSDictionary *)fillNotificationDictionary:(PlaylistEntry *)pe status:(TrackStatus)status {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
2021-02-26 20:01:48 +00:00
if (pe == nil) return dict;
[dict setObject:[[pe URL] absoluteString] forKey:TrackPath];
if ([pe title]) [dict setObject:[pe title] forKey:TrackTitle];
if ([pe artist]) [dict setObject:[pe artist] forKey:TrackArtist];
if ([pe album]) [dict setObject:[pe album] forKey:TrackAlbum];
if ([pe genre]) [dict setObject:[pe genre] forKey:TrackGenre];
2021-02-26 20:01:48 +00:00
if ([pe track])
[dict setObject:[NSString stringWithFormat:@"%@", [pe track]] forKey:TrackNumber];
if ([pe length])
[dict setObject:[NSNumber numberWithInteger:(NSInteger)([[pe length] doubleValue] * 1000.0)]
forKey:TrackLength];
NSString *state = nil;
switch (status) {
case TrackPlaying:
state = @"Playing";
break;
case TrackPaused:
state = @"Paused";
break;
case TrackStopped:
state = @"Stopped";
break;
default:
break;
}
2021-02-26 20:01:48 +00:00
[dict setObject:state forKey:TrackState];
2021-02-26 20:01:48 +00:00
return dict;
}
2021-02-26 20:01:48 +00:00
- (void)performPlaybackDidBeginActions:(PlaylistEntry *)pe {
2014-12-04 05:36:55 +00:00
if (NO == [pe error]) {
entry = pe;
2021-02-26 20:01:48 +00:00
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:TrackNotification
object:nil
userInfo:[self fillNotificationDictionary:pe status:TrackPlaying]
deliverImmediately:YES];
2014-12-04 05:36:55 +00:00
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:@"notifications.enable"]) {
2021-02-26 20:01:48 +00:00
if ([defaults boolForKey:@"enableAudioScrobbler"]) {
2014-12-04 05:36:55 +00:00
[scrobbler start:pe];
if ([AudioScrobbler isRunning]) return;
}
2021-02-26 20:01:48 +00:00
if (@available(macOS 10.14, *)) {
if (didGainUN) {
2021-02-26 20:01:48 +00:00
UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
UNMutableNotificationContent *content =
[[UNMutableNotificationContent alloc] init];
content.title = @"Now Playing";
2021-02-26 20:01:48 +00:00
NSString *subtitle;
if ([pe artist] && [pe album]) {
subtitle = [NSString stringWithFormat:@"%@ - %@", [pe artist], [pe album]];
} else if ([pe artist]) {
subtitle = [pe artist];
} else if ([pe album]) {
subtitle = [pe album];
} else {
subtitle = @"";
}
2021-02-26 20:01:48 +00:00
NSString *body = [NSString stringWithFormat:@"%@\n%@", [pe title], subtitle];
content.body = body;
content.sound = nil;
content.categoryIdentifier = @"play";
2021-02-26 20:01:48 +00:00
if ([defaults boolForKey:@"notifications.show-album-art"] &&
[pe albumArt]) {
2020-12-26 13:42:56 +00:00
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *tmpSubFolderURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()]
2021-02-26 20:01:48 +00:00
URLByAppendingPathComponent:@"cog-artworks-cache"
isDirectory:true];
2020-12-26 13:42:56 +00:00
if ([fileManager createDirectoryAtPath:[tmpSubFolderURL path]
withIntermediateDirectories:true
attributes:nil
error:&error]) {
2021-02-26 20:01:48 +00:00
NSString *tmpFileName =
[[NSProcessInfo.processInfo globallyUniqueString]
stringByAppendingString:@".jpg"];
NSURL *fileURL =
[tmpSubFolderURL URLByAppendingPathComponent:tmpFileName];
2020-12-26 13:42:56 +00:00
NSImage *image = [pe albumArt];
2021-02-26 20:01:48 +00:00
CGImageRef cgRef = [image CGImageForProposedRect:NULL
context:nil
hints:nil];
NSBitmapImageRep *newRep =
[[NSBitmapImageRep alloc] initWithCGImage:cgRef];
NSData *jpgData = [newRep
representationUsingType:NSBitmapImageFileTypeJPEG
properties:@{NSImageCompressionFactor : @0.5f}];
[jpgData writeToURL:fileURL atomically:YES];
2020-12-26 13:42:56 +00:00
2021-02-26 20:01:48 +00:00
UNNotificationAttachment *icon =
[UNNotificationAttachment attachmentWithIdentifier:@"art"
URL:fileURL
options:nil
error:&error];
if (error) {
// We have size limit of 10MB per image attachment.
NSLog(@"%@", error.localizedDescription);
} else {
2021-02-26 20:01:48 +00:00
content.attachments = @[ icon ];
}
2020-12-26 13:42:56 +00:00
}
}
2021-02-26 20:01:48 +00:00
UNNotificationRequest *request =
[UNNotificationRequest requestWithIdentifier:@"PlayTrack"
content:content
trigger:nil];
[center addNotificationRequest:request
withCompletionHandler:^(NSError *_Nullable error) {
NSLog(@"%@", error.localizedDescription);
}];
}
2021-02-26 20:01:48 +00:00
} else {
2014-12-04 05:36:55 +00:00
NSUserNotification *notif = [[NSUserNotification alloc] init];
notif.title = [pe title];
2021-02-26 20:01:48 +00:00
NSString *subtitle;
if ([pe artist] && [pe album]) {
subtitle = [NSString stringWithFormat:@"%@ - %@", [pe artist], [pe album]];
} else if ([pe artist]) {
subtitle = [pe artist];
} else if ([pe album]) {
subtitle = [pe album];
} else {
subtitle = @"";
}
2021-02-26 20:01:48 +00:00
2014-12-04 05:36:55 +00:00
if ([defaults boolForKey:@"notifications.itunes-style"]) {
notif.subtitle = subtitle;
2014-12-04 05:36:55 +00:00
[notif setValue:@YES forKey:@"_showsButtons"];
2021-02-26 20:01:48 +00:00
} else {
notif.informativeText = subtitle;
2014-12-04 05:36:55 +00:00
}
2021-02-26 20:01:48 +00:00
2014-12-04 05:36:55 +00:00
if ([notif respondsToSelector:@selector(setContentImage:)]) {
2021-02-26 20:01:48 +00:00
if ([defaults boolForKey:@"notifications.show-album-art"] &&
[pe albumArtInternal]) {
2014-12-04 05:36:55 +00:00
NSImage *image = [pe albumArt];
2021-02-26 20:01:48 +00:00
2014-12-04 05:36:55 +00:00
if ([defaults boolForKey:@"notifications.itunes-style"]) {
[notif setValue:image forKey:@"_identityImage"];
2021-02-26 20:01:48 +00:00
} else {
2014-12-04 05:36:55 +00:00
notif.contentImage = image;
}
}
}
2021-02-26 20:01:48 +00:00
2014-12-04 05:36:55 +00:00
notif.actionButtonTitle = @"Skip";
2021-02-26 20:01:48 +00:00
[[NSUserNotificationCenter defaultUserNotificationCenter]
scheduleNotification:notif];
2014-12-04 05:36:55 +00:00
}
}
2021-02-26 20:01:48 +00:00
}
2009-03-05 17:04:16 +00:00
}
2021-02-26 20:01:48 +00:00
- (void)performPlaybackDidPauseActions {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:TrackNotification
object:nil
userInfo:[self fillNotificationDictionary:entry status:TrackPaused]
deliverImmediately:YES];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"enableAudioScrobbler"]) {
[scrobbler pause];
}
2009-03-05 17:04:16 +00:00
}
2021-02-26 20:01:48 +00:00
- (void)performPlaybackDidResumeActions {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:TrackNotification
object:nil
userInfo:[self fillNotificationDictionary:entry status:TrackPlaying]
deliverImmediately:YES];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"enableAudioScrobbler"]) {
[scrobbler resume];
}
2009-03-05 17:04:16 +00:00
}
2021-02-26 20:01:48 +00:00
- (void)performPlaybackDidStopActions {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:TrackNotification
object:nil
userInfo:[self fillNotificationDictionary:entry status:TrackStopped]
deliverImmediately:YES];
entry = nil;
2021-02-26 20:01:48 +00:00
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"enableAudioScrobbler"]) {
[scrobbler stop];
}
}
2021-02-26 20:01:48 +00:00
- (void)awakeFromNib {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playbackDidBegin:)
name:CogPlaybackDidBeginNotficiation
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playbackDidPause:)
name:CogPlaybackDidPauseNotficiation
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playbackDidResume:)
name:CogPlaybackDidResumeNotficiation
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playbackDidStop:)
name:CogPlaybackDidStopNotficiation
object:nil];
}
2021-02-26 20:01:48 +00:00
- (void)playbackDidBegin:(NSNotification *)notification {
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[self performPlaybackDidBeginActions:(PlaylistEntry *)[notification object]];
}];
[queue addOperation:op];
}
2021-02-26 20:01:48 +00:00
- (void)playbackDidPause:(NSNotification *)notification {
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[self performPlaybackDidPauseActions];
}];
[queue addOperation:op];
}
2021-02-26 20:01:48 +00:00
- (void)playbackDidResume:(NSNotification *)notification {
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[self performPlaybackDidResumeActions];
}];
[queue addOperation:op];
}
2021-02-26 20:01:48 +00:00
- (void)playbackDidStop:(NSNotification *)notification {
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[self performPlaybackDidStopActions];
}];
[queue addOperation:op];
}
2021-02-26 20:01:48 +00:00
- (void)userNotificationCenter:(NSUserNotificationCenter *)center
didActivateNotification:(NSUserNotification *)notification {
switch (notification.activationType) {
2014-12-04 05:36:55 +00:00
case NSUserNotificationActivationTypeActionButtonClicked:
[playbackController next:self];
break;
2021-02-26 20:01:48 +00:00
case NSUserNotificationActivationTypeContentsClicked: {
NSWindow *window = [[NSUserDefaults standardUserDefaults] boolForKey:@"miniMode"]
? miniWindow
: mainWindow;
2014-12-04 05:36:55 +00:00
[NSApp activateIgnoringOtherApps:YES];
[window makeKeyAndOrderFront:self];
2021-02-26 20:01:48 +00:00
}; break;
2014-12-04 05:36:55 +00:00
default:
break;
}
}
2009-03-05 17:04:16 +00:00
@end