Add an iOS Spotify integration

This commit is contained in:
James Babcock committed 2026-10-24 00:18:04 -07:00
1 parent e36fb14a34
commit c9cf29e5c0
32 files changed
+3176 -50

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@ TARGETED_DEVICE_FAMILY = 1;
CODE_SIGN_STYLE = Automatic;
// Set IOS_TEAM_ID in build_paths.sh (or pass --teamId) to choose the signing team.
OTHER_LDFLAGS = $(inherited) -framework CoreBluetooth -framework CoreLocation -framework CoreText -framework Speech -framework AVFoundation -framework WebKit -framework SafariServices -framework UniformTypeIdentifiers -framework ImageIO -framework EventKit -framework MediaPlayer
OTHER_LDFLAGS = $(inherited) -framework CoreBluetooth -framework CoreLocation -framework CoreText -framework Speech -framework AVFoundation -framework WebKit -framework SafariServices -framework UniformTypeIdentifiers -framework ImageIO -framework EventKit -framework MediaPlayer -framework AuthenticationServices -framework Security
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+2 -24
View File
@@ -1,4 +1,5 @@
#import "FaceclawAppleMusic.h"
#import "FaceclawGraphics.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <UIKit/UIKit.h>
@@ -219,30 +220,7 @@ static NSDictionary *BrowseRow(NSString *mediaId, NSString *title, NSString *sub
- (NSData *)albumArt:(NSInteger)maxSize {
if (maxSize <= 0 || maxSize > 1024 || ![self hasPermission]) return nil;
MPMediaItemArtwork *artwork = MPMusicPlayerController.systemMusicPlayer.nowPlayingItem.artwork;
UIImage *image = [artwork imageWithSize:CGSizeMake(maxSize, maxSize)];
CGImageRef source = image.CGImage;
if (!source) return nil;
double sourceWidth = CGImageGetWidth(source), sourceHeight = CGImageGetHeight(source);
if (sourceWidth <= 0 || sourceHeight <= 0) return nil;
double scale = MIN(1.0, MIN(maxSize / sourceWidth, maxSize / sourceHeight));
NSInteger width = MAX(1, lround(sourceWidth * scale)), height = MAX(1, lround(sourceHeight * scale));
NSMutableData *packet = [NSMutableData dataWithLength:4 + width * height * 4];
uint8_t *bytes = packet.mutableBytes;
bytes[0] = width & 255; bytes[1] = (width >> 8) & 255;
bytes[2] = height & 255; bytes[3] = (height >> 8) & 255;
uint8_t *pixels = bytes + 4;
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
// Memory order B, G, R, A: one little-endian ARGB word per pixel.
CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * 4, space,
kCGBitmapByteOrder32Little | (CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(space);
if (!context) return nil;
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), source);
CGContextRelease(context);
// Composited over black (the display's see-through background); now opaque.
for (NSInteger i = 0; i < width * height; i++) pixels[i * 4 + 3] = 255;
return packet;
return [FaceclawGraphics bgraPacket:[artwork imageWithSize:CGSizeMake(maxSize, maxSize)].CGImage maxSize:maxSize];
}
#pragma mark - Queue
+4
View File
@@ -2,4 +2,8 @@
@interface FaceclawCrypto : NSObject
+ (NSString *)hmacSha256:(NSString *)secret message:(NSString *)message;
+ (NSString *)sha256:(NSData *)data;
/** byteCount bytes from the system CSPRNG, base64url without padding (an OAuth state or PKCE verifier). */
+ (NSString *)randomBase64Url:(NSInteger)byteCount;
/** SHA-256 of the text's UTF-8, base64url without padding (a PKCE S256 code challenge). */
+ (NSString *)sha256Base64Url:(NSString *)text;
@end
+21
View File
@@ -1,6 +1,15 @@
#import "FaceclawCrypto.h"
#import <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonDigest.h>
#import <Security/Security.h>
static NSString *Base64Url(NSData *data) {
NSString *base64 = [data base64EncodedStringWithOptions:0];
base64 = [base64 stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
base64 = [base64 stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
return [base64 stringByReplacingOccurrencesOfString:@"=" withString:@""];
}
@implementation FaceclawCrypto
+ (NSString *)hmacSha256:(NSString *)secret message:(NSString *)message {
NSData *key = [secret dataUsingEncoding:NSUTF8StringEncoding];
@@ -16,4 +25,16 @@
for (NSUInteger i = 0; i < sizeof(digest); i++) [hex appendFormat:@"%02x", digest[i]];
return hex;
}
+ (NSString *)randomBase64Url:(NSInteger)byteCount {
if (byteCount <= 0 || byteCount > 1024) return nil;
NSMutableData *bytes = [NSMutableData dataWithLength:(NSUInteger)byteCount];
if (SecRandomCopyBytes(kSecRandomDefault, bytes.length, bytes.mutableBytes) != errSecSuccess) return nil;
return Base64Url(bytes);
}
+ (NSString *)sha256Base64Url:(NSString *)text {
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.bytes, (CC_LONG)data.length, digest);
return Base64Url([NSData dataWithBytes:digest length:sizeof(digest)]);
}
@end
+7
View File
@@ -7,4 +7,11 @@
+ (NSData *)renderSVG:(NSString *)svg size:(NSInteger)size;
+ (NSData *)decodeImage:(NSData *)data width:(NSInteger)width height:(NSInteger)height;
+ (NSData *)decodeImageFile:(NSString *)path maxWidth:(NSInteger)maxWidth maxHeight:(NSInteger)maxHeight;
/**
* [widthLo, widthHi, heightLo, heightHi, BGRA...] fitted within maxSize (never upscaled),
* composited over black; the input of the shared Kotlin gray tone curve and dither.
*/
+ (NSData *)bgraPacket:(CGImageRef)image maxSize:(NSInteger)maxSize;
/** bgraPacket of encoded image bytes (JPEG, PNG, ...); nil when undecodable. */
+ (NSData *)bgraPacketFromImageData:(NSData *)data maxSize:(NSInteger)maxSize;
@end
+38
View File
@@ -120,4 +120,42 @@
CGColorSpaceRelease(space);
return gray;
}
+ (NSData *)bgraPacket:(CGImageRef)image maxSize:(NSInteger)maxSize {
if (!image || maxSize <= 0 || maxSize > 1024) return nil;
double sourceWidth = CGImageGetWidth(image), sourceHeight = CGImageGetHeight(image);
if (sourceWidth <= 0 || sourceHeight <= 0) return nil;
double scale = MIN(1.0, MIN(maxSize / sourceWidth, maxSize / sourceHeight));
NSInteger width = MAX(1, lround(sourceWidth * scale)), height = MAX(1, lround(sourceHeight * scale));
NSMutableData *packet = [NSMutableData dataWithLength:4 + width * height * 4];
uint8_t *bytes = packet.mutableBytes;
bytes[0] = width & 255; bytes[1] = (width >> 8) & 255;
bytes[2] = height & 255; bytes[3] = (height >> 8) & 255;
uint8_t *pixels = bytes + 4;
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
// Memory order B, G, R, A: one little-endian ARGB word per pixel.
CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * 4, space,
kCGBitmapByteOrder32Little | (CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(space);
if (!context) return nil;
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
CGContextRelease(context);
// Composited over black (the display's see-through background); now opaque.
for (NSInteger i = 0; i < width * height; i++) pixels[i * 4 + 3] = 255;
return packet;
}
+ (NSData *)bgraPacketFromImageData:(NSData *)data maxSize:(NSInteger)maxSize {
if (!data.length || maxSize <= 0 || maxSize > 1024) return nil;
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
if (!source) return nil;
NSDictionary *options = @{(id)kCGImageSourceCreateThumbnailFromImageAlways: @YES,
(id)kCGImageSourceCreateThumbnailWithTransform: @YES,
(id)kCGImageSourceThumbnailMaxPixelSize: @(maxSize)};
CGImageRef image = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef)options);
CFRelease(source);
if (!image) return nil;
NSData *packet = [self bgraPacket:image maxSize:maxSize];
CGImageRelease(image);
return packet;
}
@end
@@ -0,0 +1,16 @@
#import <Foundation/Foundation.h>
/**
* Catches an OAuth redirect to http://127.0.0.1:<port><path> (the loopback redirect that
* providers such as Spotify accept from native apps): listens on the loopback interface
* only, answers the browser's request for the path with a short "return to Faceclaw"
* page and hands back the full redirect URL, query included. Any other path (a favicon)
* gets a 404. Foundation-only, so the macOS test builds it as is.
*/
@interface FaceclawLoopbackRedirect : NSObject
/** Called on the main queue with each redirect to the path. */
@property(nonatomic, copy) void (^redirectHandler)(NSString *url);
/** Start listening; nil on success, otherwise why not (e.g. another app holds the port). */
- (NSString *)startOnPort:(NSInteger)port path:(NSString *)path;
- (void)stop;
@end
@@ -0,0 +1,128 @@
#import "FaceclawLoopbackRedirect.h"
#import <arpa/inet.h>
#import <errno.h>
#import <fcntl.h>
#import <netinet/in.h>
#import <sys/socket.h>
#import <unistd.h>
/** Request heads beyond this are not a browser's redirect; stop reading. */
static const NSUInteger kMaxRequestBytes = 16384;
static NSString *const kDonePage =
@"<!doctype html><html><head><meta charset=\"utf-8\">"
@"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Faceclaw</title></head>"
@"<body style=\"font-family: -apple-system, sans-serif; text-align: center; padding: 64px 24px\">"
@"<h2>Signed in</h2><p>You can return to Faceclaw.</p></body></html>";
@interface FaceclawLoopbackRedirect ()
@property(nonatomic, strong) dispatch_queue_t queue;
@property(nonatomic, strong) dispatch_source_t acceptSource;
@property(nonatomic) NSInteger port;
@property(nonatomic, copy) NSString *path;
@end
@implementation FaceclawLoopbackRedirect
- (instancetype)init {
if ((self = [super init])) {
_queue = dispatch_queue_create("com.faceclaw.loopback-redirect", DISPATCH_QUEUE_SERIAL);
}
return self;
}
- (void)dealloc {
[self stop];
}
- (NSString *)startOnPort:(NSInteger)port path:(NSString *)path {
[self stop];
if (port <= 0 || port > 65535 || ![path hasPrefix:@"/"]) return @"Invalid redirect address";
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) return [NSString stringWithFormat:@"Could not open a socket (errno %d)", errno];
int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
struct sockaddr_in address = {0};
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
address.sin_port = htons((uint16_t)port);
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(fd, (struct sockaddr *)&address, sizeof(address)) != 0 || listen(fd, 8) != 0) {
int error = errno;
close(fd);
return error == EADDRINUSE
? [NSString stringWithFormat:@"Another app is using port %ld; close it and try again", (long)port]
: [NSString stringWithFormat:@"Could not listen on port %ld (errno %d)", (long)port, error];
}
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
self.port = port;
self.path = path;
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, (uintptr_t)fd, 0, self.queue);
__weak typeof(self) weakSelf = self;
dispatch_source_set_event_handler(source, ^{
int client = accept(fd, NULL, NULL);
if (client < 0) return;
FaceclawLoopbackRedirect *strongSelf = weakSelf;
if (strongSelf) [strongSelf serve:client];
else close(client);
});
dispatch_source_set_cancel_handler(source, ^{ close(fd); });
self.acceptSource = source;
dispatch_resume(source);
return nil;
}
- (void)stop {
if (self.acceptSource) dispatch_source_cancel(self.acceptSource);
self.acceptSource = nil;
}
/** Read one request head and answer it; runs on the receiver's queue (blocking, with timeouts). */
- (void)serve:(int)client {
// BSD sockets inherit O_NONBLOCK from the listener.
fcntl(client, F_SETFL, fcntl(client, F_GETFL) & ~O_NONBLOCK);
int yes = 1;
setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(yes));
struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };
setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
setsockopt(client, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
NSMutableData *head = [NSMutableData data];
NSData *terminator = [@"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding];
char buffer[2048];
while (head.length < kMaxRequestBytes) {
ssize_t count = recv(client, buffer, sizeof(buffer), 0);
if (count <= 0) break;
[head appendBytes:buffer length:(NSUInteger)count];
if ([head rangeOfData:terminator options:0 range:NSMakeRange(0, head.length)].location != NSNotFound) break;
}
NSString *text = [[NSString alloc] initWithData:head encoding:NSUTF8StringEncoding] ?: @"";
NSArray<NSString *> *requestLine = [[text componentsSeparatedByString:@"\r\n"].firstObject componentsSeparatedByString:@" "];
NSString *target = requestLine.count >= 3 && [requestLine[0] isEqualToString:@"GET"] ? requestLine[1] : nil;
BOOL matched = target && [[target componentsSeparatedByString:@"?"].firstObject isEqualToString:self.path];
[self respond:client status:matched ? @"200 OK" : @"404 Not Found" body:matched ? kDonePage : @"Not found"];
close(client);
if (!matched) return;
NSString *url = [NSString stringWithFormat:@"http://127.0.0.1:%ld%@", (long)self.port, target];
void (^handler)(NSString *) = self.redirectHandler;
dispatch_async(dispatch_get_main_queue(), ^{
if (handler) handler(url);
});
}
- (void)respond:(int)client status:(NSString *)status body:(NSString *)body {
NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSString *headers = [NSString stringWithFormat:
@"HTTP/1.1 %@\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %lu\r\n"
@"Cache-Control: no-store\r\nConnection: close\r\n\r\n", status, (unsigned long)bodyData.length];
NSMutableData *response = [[headers dataUsingEncoding:NSASCIIStringEncoding] mutableCopy];
[response appendData:bodyData];
const uint8_t *bytes = response.bytes;
NSUInteger sent = 0;
while (sent < response.length) {
ssize_t count = send(client, bytes + sent, response.length - sent, 0);
if (count <= 0) break;
sent += (NSUInteger)count;
}
}
@end
+21
View File
@@ -0,0 +1,21 @@
#import <Foundation/Foundation.h>
/**
* OAuth sign-in in the system browser sheet (ASWebAuthenticationSession, which shares
* Safari's cookies, so a provider the user is already signed in to needs only a consent
* tap) for providers that redirect to a loopback address: a FaceclawLoopbackRedirect
* catches the redirect, then the sheet is closed. Presenting needs Faceclaw in the
* foreground, so a sign-in started from the glasses waits until the user opens the app.
* One sign-in at a time; starting another cancels the first. Call from the main thread.
*/
@interface FaceclawWebSignIn : NSObject
+ (instancetype)shared;
/**
* completion(redirectUrl, nil) once the provider redirects to http://127.0.0.1:<port><path>;
* (nil, "cancelled") when the user closes the sheet or cancel is called; (nil, message)
* when the sheet or the receiver cannot start. Called once, on the main queue.
*/
- (void)signIn:(NSString *)authorizeUrl port:(NSInteger)port path:(NSString *)path
completion:(void (^)(NSString *redirectUrl, NSString *error))completion;
- (void)cancel;
@end
+110
View File
@@ -0,0 +1,110 @@
#import "FaceclawWebSignIn.h"
#import "FaceclawLoopbackRedirect.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import <UIKit/UIKit.h>
/** Never reached: the loopback receiver ends the session before any custom-scheme redirect. */
static NSString *const kUnusedCallbackScheme = @"faceclaw-signin";
@interface FaceclawWebSignIn () <ASWebAuthenticationPresentationContextProviding>
@property(nonatomic, strong) FaceclawLoopbackRedirect *receiver;
@property(nonatomic, strong) ASWebAuthenticationSession *session;
@property(nonatomic, copy) void (^completion)(NSString *redirectUrl, NSString *error);
/** The sign-in page waiting for Faceclaw to come to the foreground. */
@property(nonatomic, copy) NSURL *pendingUrl;
@property(nonatomic, strong) id activeObserver;
@end
@implementation FaceclawWebSignIn
+ (instancetype)shared {
static FaceclawWebSignIn *instance;
static dispatch_once_t once;
dispatch_once(&once, ^{ instance = [FaceclawWebSignIn new]; });
return instance;
}
- (void)signIn:(NSString *)authorizeUrl port:(NSInteger)port path:(NSString *)path
completion:(void (^)(NSString *, NSString *))completion {
[self finishWithUrl:nil error:@"cancelled"];
NSURL *url = [NSURL URLWithString:authorizeUrl];
if (!url || ![url.scheme isEqualToString:@"https"]) {
if (completion) completion(nil, @"Invalid sign-in address");
return;
}
FaceclawLoopbackRedirect *receiver = [FaceclawLoopbackRedirect new];
NSString *error = [receiver startOnPort:port path:path];
if (error) {
if (completion) completion(nil, error);
return;
}
__weak typeof(self) weakSelf = self;
receiver.redirectHandler = ^(NSString *redirectUrl) {
[weakSelf finishWithUrl:redirectUrl error:nil];
};
self.receiver = receiver;
self.completion = completion;
if (UIApplication.sharedApplication.applicationState == UIApplicationStateActive) {
[self present:url];
return;
}
self.pendingUrl = url;
self.activeObserver = [NSNotificationCenter.defaultCenter addObserverForName:UIApplicationDidBecomeActiveNotification
object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
FaceclawWebSignIn *strongSelf = weakSelf;
NSURL *pending = strongSelf.pendingUrl;
if (!pending) return;
[strongSelf removeActiveObserver];
[strongSelf present:pending];
}];
}
- (void)cancel {
[self finishWithUrl:nil error:@"cancelled"];
}
- (void)present:(NSURL *)url {
__weak typeof(self) weakSelf = self;
ASWebAuthenticationSession *session = [[ASWebAuthenticationSession alloc] initWithURL:url
callbackURLScheme:kUnusedCallbackScheme completionHandler:^(NSURL *callbackURL, NSError *error) {
// The sheet closed: the user dismissed it, or finishing already cancelled it.
BOOL dismissed = !error || ([error.domain isEqualToString:ASWebAuthenticationSessionErrorDomain]
&& error.code == ASWebAuthenticationSessionErrorCodeCanceledLogin);
[weakSelf finishWithUrl:callbackURL.absoluteString
error:callbackURL ? nil : dismissed ? @"cancelled" : error.localizedDescription];
}];
session.presentationContextProvider = self;
session.prefersEphemeralWebBrowserSession = NO;
self.session = session;
if (![session start]) [self finishWithUrl:nil error:@"Could not open the sign-in page"];
}
/** Report the outcome once; tear down the receiver and close the sheet. */
- (void)finishWithUrl:(NSString *)url error:(NSString *)error {
void (^completion)(NSString *, NSString *) = self.completion;
ASWebAuthenticationSession *session = self.session;
self.completion = nil;
self.session = nil;
self.pendingUrl = nil;
[self removeActiveObserver];
[self.receiver stop];
self.receiver = nil;
// Re-enters through the session's completion handler, which then finds nothing to report.
[session cancel];
if (completion) completion(url, url ? nil : error);
}
- (void)removeActiveObserver {
if (self.activeObserver) [NSNotificationCenter.defaultCenter removeObserver:self.activeObserver];
self.activeObserver = nil;
}
- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session {
for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
if (![scene isKindOfClass:UIWindowScene.class]) continue;
NSArray<UIWindow *> *windows = ((UIWindowScene *)scene).windows;
for (UIWindow *window in windows) if (window.isKeyWindow) return window;
if (windows.firstObject) return windows.firstObject;
}
return [UIWindow new];
}
@end
+2
View File
@@ -11,5 +11,7 @@ module FaceclawGraphics {
header "FaceclawEvenHubWebView.h"
header "FaceclawCrypto.h"
header "FaceclawQrScanner.h"
header "FaceclawLoopbackRedirect.h"
header "FaceclawWebSignIn.h"
export *
}