Refactor Kotlin for iOS commonality

This commit is contained in:
James Babcock committed 2026-09-22 19:55:08 -07:00
1 parent 587364e5e6
commit c3a0ba9f56
31 files changed
+2780 -964

No files matched your search

-14
View File
@@ -1,14 +0,0 @@
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
/** Main-queue CoreBluetooth adapter. Protocol and MAC matching live in TS. */
@interface FaceclawBluetooth : NSObject <CBCentralManagerDelegate, CBPeripheralDelegate>
@property (nonatomic, copy) void (^eventHandler)(NSString *json);
- (void)initializeBluetooth;
- (void)scan:(BOOL)enabled;
- (void)connect:(NSString *)identifier requestId:(NSInteger)requestId;
- (void)connect:(NSString *)identifier requiresANCS:(BOOL)requiresANCS requestId:(NSInteger)requestId;
- (void)subscribe:(NSString *)identifier characteristic:(NSString *)uuid requestId:(NSInteger)requestId;
- (void)write:(NSString *)identifier characteristic:(NSString *)uuid data:(NSData *)data requestId:(NSInteger)requestId;
- (void)disconnect:(NSString *)identifier;
@end
-197
View File
@@ -1,197 +0,0 @@
#import "FaceclawBluetooth.h"
@interface FCBPeripheral : NSObject
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (nonatomic, strong) NSMutableDictionary<NSString *, CBCharacteristic *> *characteristics;
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSNumber *> *subscriptions;
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *writes;
@property (nonatomic, strong) NSNumber *connectRequest;
@property (nonatomic) NSInteger pendingServices;
@property (nonatomic) BOOL awaitingWriteResponse;
@end
@implementation FCBPeripheral
- (instancetype)init {
if ((self = [super init])) {
_characteristics = [NSMutableDictionary new]; _subscriptions = [NSMutableDictionary new];
_writes = [NSMutableArray new];
}
return self;
}
@end
@interface FaceclawBluetooth ()
@property (nonatomic, strong) CBCentralManager *central;
@property (nonatomic, strong) NSMutableDictionary<NSString *, FCBPeripheral *> *peers;
@property (nonatomic) BOOL scanRequested;
@end
@implementation FaceclawBluetooth
- (instancetype)init { if ((self = [super init])) _peers = [NSMutableDictionary new]; return self; }
- (void)emit:(NSDictionary *)event {
if (!self.eventHandler) return;
NSData *data = [NSJSONSerialization dataWithJSONObject:event options:0 error:nil];
if (data) self.eventHandler([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
- (void)complete:(NSNumber *)request error:(NSString *)error details:(NSDictionary *)details {
if (!request) return;
NSMutableDictionary *event = [@{ @"kind": @"completion", @"id": request } mutableCopy];
if (error) event[@"error"] = error;
if (details) event[@"details"] = details;
[self emit:event];
}
- (void)initializeBluetooth {
if (!self.central) self.central = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
else [self centralManagerDidUpdateState:self.central];
}
- (void)scan:(BOOL)enabled {
self.scanRequested = enabled;
if (!enabled) { [self.central stopScan]; return; }
[self initializeBluetooth];
if (self.central.state == CBManagerStatePoweredOn)
[self.central scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey: @YES}];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
[self emit:@{@"kind": @"state", @"state": @(central.state), @"authorization": @(CBManager.authorization)}];
if (central.state != CBManagerStatePoweredOn) {
for (FCBPeripheral *peer in self.peers.allValues) [self failPeer:peer reason:@"Bluetooth is unavailable"];
} else if (self.scanRequested) {
[central scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey: @YES}];
}
}
- (FCBPeripheral *)remember:(CBPeripheral *)peripheral {
NSString *identifier = peripheral.identifier.UUIDString;
FCBPeripheral *peer = self.peers[identifier];
if (!peer) { peer = [FCBPeripheral new]; peer.peripheral = peripheral; self.peers[identifier] = peer; }
peripheral.delegate = self;
return peer;
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisement RSSI:(NSNumber *)RSSI {
[self remember:peripheral];
NSData *data = advertisement[CBAdvertisementDataManufacturerDataKey];
NSMutableString *hex = [NSMutableString new];
const uint8_t *bytes = data.bytes;
for (NSUInteger i = 0; i < data.length; i++) [hex appendFormat:@"%02x", bytes[i]];
[self emit:@{@"kind": @"advertisement", @"identifier": peripheral.identifier.UUIDString,
@"name": advertisement[CBAdvertisementDataLocalNameKey] ?: peripheral.name ?: @"",
@"manufacturerData": hex, @"rssi": RSSI,
@"connectable": advertisement[CBAdvertisementDataIsConnectable] ?: @YES}];
}
- (void)connect:(NSString *)identifier requestId:(NSInteger)requestId {
[self connect:identifier requiresANCS:NO requestId:requestId];
}
- (void)connect:(NSString *)identifier requiresANCS:(BOOL)requiresANCS requestId:(NSInteger)requestId {
if (self.central.state != CBManagerStatePoweredOn) { [self complete:@(requestId) error:@"Bluetooth is not ready" details:nil]; return; }
FCBPeripheral *peer = self.peers[identifier.uppercaseString];
if (!peer) {
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:identifier];
CBPeripheral *peripheral = uuid ? [self.central retrievePeripheralsWithIdentifiers:@[uuid]].firstObject : nil;
if (peripheral) peer = [self remember:peripheral];
}
if (!peer) { [self complete:@(requestId) error:@"Peripheral is unknown; scan for the device first" details:nil]; return; }
if (peer.connectRequest || peer.peripheral.state != CBPeripheralStateDisconnected) {
[self complete:@(requestId) error:@"Peripheral is already connecting or connected" details:nil]; return;
}
[peer.characteristics removeAllObjects]; peer.connectRequest = @(requestId);
[self.central connectPeripheral:peer.peripheral options:requiresANCS ? @{CBConnectPeripheralOptionRequiresANCS: @YES} : nil];
}
- (void)centralManager:(CBCentralManager *)central didUpdateANCSAuthorizationForPeripheral:(CBPeripheral *)peripheral {
[self emit:@{@"kind": @"ancs-authorization", @"identifier": peripheral.identifier.UUIDString,
@"authorized": @(peripheral.ancsAuthorized)}];
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
[peripheral discoverServices:nil];
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
[self failPeer:[self remember:peripheral] reason:error.localizedDescription ?: @"Connection failed"];
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
[self failPeer:[self remember:peripheral] reason:error.localizedDescription ?: @"Disconnected"];
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
FCBPeripheral *peer = [self remember:peripheral];
if (error || !peripheral.services.count) { [self failPeer:peer reason:error.localizedDescription ?: @"No services found"]; return; }
peer.pendingServices = peripheral.services.count;
for (CBService *service in peripheral.services) [peripheral discoverCharacteristics:nil forService:service];
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
FCBPeripheral *peer = [self remember:peripheral];
if (!peer.connectRequest) return;
if (error) { [self failPeer:peer reason:error.localizedDescription]; return; }
for (CBCharacteristic *characteristic in service.characteristics) peer.characteristics[characteristic.UUID.UUIDString.lowercaseString] = characteristic;
if (--peer.pendingServices == 0) {
NSNumber *request = peer.connectRequest; peer.connectRequest = nil;
[self complete:request error:nil details:@{@"characteristics": peer.characteristics.allKeys,
@"maxWrite": @([peripheral maximumWriteValueLengthForType:CBCharacteristicWriteWithoutResponse])}];
}
}
- (void)subscribe:(NSString *)identifier characteristic:(NSString *)uuid requestId:(NSInteger)requestId {
FCBPeripheral *peer = self.peers[identifier.uppercaseString];
CBCharacteristic *characteristic = peer.characteristics[uuid.lowercaseString];
if (!characteristic || !(characteristic.properties & (CBCharacteristicPropertyNotify | CBCharacteristicPropertyIndicate))) {
[self complete:@(requestId) error:@"Notification characteristic is unavailable" details:nil]; return;
}
if (characteristic.isNotifying) { [self complete:@(requestId) error:nil details:nil]; return; }
if (peer.subscriptions[uuid.lowercaseString]) { [self complete:@(requestId) error:@"Subscription already pending" details:nil]; return; }
peer.subscriptions[uuid.lowercaseString] = @(requestId);
[peer.peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
FCBPeripheral *peer = [self remember:peripheral]; NSString *key = characteristic.UUID.UUIDString.lowercaseString;
NSNumber *request = peer.subscriptions[key]; [peer.subscriptions removeObjectForKey:key];
[self complete:request error:error.localizedDescription ?: (characteristic.isNotifying ? nil : @"Notifications not enabled") details:nil];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) { [self emit:@{@"kind": @"error", @"message": error.localizedDescription}]; return; }
NSMutableString *hex = [NSMutableString new]; NSData *data = characteristic.value; const uint8_t *bytes = data.bytes;
for (NSUInteger i = 0; i < data.length; i++) [hex appendFormat:@"%02x", bytes[i]];
[self emit:@{@"kind": @"notification", @"identifier": peripheral.identifier.UUIDString,
@"characteristic": characteristic.UUID.UUIDString.lowercaseString, @"data": hex}];
}
- (void)write:(NSString *)identifier characteristic:(NSString *)uuid data:(NSData *)data requestId:(NSInteger)requestId {
FCBPeripheral *peer = self.peers[identifier.uppercaseString];
CBCharacteristic *characteristic = peer.characteristics[uuid.lowercaseString];
if (!characteristic || peer.peripheral.state != CBPeripheralStateConnected) {
[self complete:@(requestId) error:@"Write characteristic is disconnected or unavailable" details:nil]; return;
}
CBCharacteristicWriteType type = (characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse)
? CBCharacteristicWriteWithoutResponse : CBCharacteristicWriteWithResponse;
if (!(characteristic.properties & (CBCharacteristicPropertyWriteWithoutResponse | CBCharacteristicPropertyWrite)) ||
data.length > [peer.peripheral maximumWriteValueLengthForType:type]) {
[self complete:@(requestId) error:@"Write exceeds the negotiated BLE payload size or is unsupported" details:nil]; return;
}
if (peer.writes.count >= 256) { [self complete:@(requestId) error:@"Bluetooth write queue is full" details:nil]; return; }
[peer.writes addObject:@{@"id": @(requestId), @"characteristic": characteristic, @"data": [data copy], @"type": @(type)}];
[self drain:peer];
}
- (void)drain:(FCBPeripheral *)peer {
while (peer.writes.count && !peer.awaitingWriteResponse && peer.peripheral.state == CBPeripheralStateConnected) {
NSDictionary *write = peer.writes.firstObject;
CBCharacteristicWriteType type = [write[@"type"] integerValue];
if (type == CBCharacteristicWriteWithoutResponse && !peer.peripheral.canSendWriteWithoutResponse) return;
if (type == CBCharacteristicWriteWithResponse) peer.awaitingWriteResponse = YES;
[peer.peripheral writeValue:write[@"data"] forCharacteristic:write[@"characteristic"] type:type];
if (peer.awaitingWriteResponse) return;
[peer.writes removeObjectAtIndex:0]; [self complete:write[@"id"] error:nil details:nil];
}
}
- (void)peripheralIsReadyToSendWriteWithoutResponse:(CBPeripheral *)peripheral { [self drain:[self remember:peripheral]]; }
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
FCBPeripheral *peer = [self remember:peripheral];
if (!peer.awaitingWriteResponse || !peer.writes.count) return;
NSDictionary *write = peer.writes.firstObject; [peer.writes removeObjectAtIndex:0]; peer.awaitingWriteResponse = NO;
[self complete:write[@"id"] error:error.localizedDescription details:nil]; [self drain:peer];
}
- (void)failPeer:(FCBPeripheral *)peer reason:(NSString *)reason {
if (!peer) return;
NSNumber *connect = peer.connectRequest; peer.connectRequest = nil;
[self complete:connect error:reason details:nil];
NSArray *subscriptions = peer.subscriptions.allValues; [peer.subscriptions removeAllObjects];
NSArray *writes = [peer.writes copy]; [peer.writes removeAllObjects]; peer.awaitingWriteResponse = NO;
for (NSNumber *request in subscriptions) [self complete:request error:reason details:nil];
for (NSDictionary *write in writes) [self complete:write[@"id"] error:reason details:nil];
[peer.characteristics removeAllObjects];
if (peer.peripheral.state != CBPeripheralStateDisconnected) [self.central cancelPeripheralConnection:peer.peripheral];
[self emit:@{@"kind": @"disconnected", @"identifier": peer.peripheral.identifier.UUIDString, @"message": reason}];
}
- (void)disconnect:(NSString *)identifier { [self failPeer:self.peers[identifier.uppercaseString] reason:@"Disconnected"]; }
@end
@@ -1,13 +0,0 @@
#import <Foundation/Foundation.h>
@interface FaceclawRemoteInput : NSObject
+ (instancetype)shared;
+ (NSString *)interfaces;
- (NSString *)start:(int)port;
- (NSString *)start:(int)port address:(NSString *)address;
- (void)stop;
- (void)setRequestListener:(void (^)(void))listener;
- (NSString *)nextRequest;
- (void)complete:(long long)identifier response:(NSString *)response;
- (NSString *)randomSecret;
- (NSString *)tokenDigest:(NSString *)value;
@end
-166
View File
@@ -1,166 +0,0 @@
#import "FaceclawRemoteInput.h"
#import "FaceclawCrypto.h"
#import <Security/Security.h>
#import <sys/socket.h>
#import <netinet/in.h>
#import <unistd.h>
#import <poll.h>
#import <ifaddrs.h>
#import <net/if.h>
#import <netdb.h>
#import <arpa/inet.h>
@implementation FaceclawRemoteInput {
NSCondition *_condition;
int _server, _client;
NSUInteger _generation;
long long _nextId, _requestId;
NSTimeInterval _deadline;
NSString *_pending, *_reply;
void (^_requestListener)(void);
}
+ (instancetype)shared {
static FaceclawRemoteInput *instance; static dispatch_once_t once;
dispatch_once(&once, ^{ instance = [self new]; }); return instance;
}
- (instancetype)init {
if ((self = [super init])) { _condition = [NSCondition new]; _server = _client = -1; }
return self;
}
- (NSString *)start:(int)port { return [self start:port address:@"127.0.0.1"]; }
- (NSString *)start:(int)port address:(NSString *)address {
[_condition lock];
if (_server >= 0) { [_condition unlock]; return @""; }
struct addrinfo hints = {0}, *resolved = NULL;
hints.ai_flags = AI_NUMERICHOST; hints.ai_socktype = SOCK_STREAM;
NSString *service = [NSString stringWithFormat:@"%d", port];
if (getaddrinfo(address.UTF8String, service.UTF8String, &hints, &resolved) != 0) {
[_condition unlock]; return @"Invalid local address.";
}
BOOL wildcard = resolved->ai_family == AF_INET ?
((struct sockaddr_in *)resolved->ai_addr)->sin_addr.s_addr == INADDR_ANY :
IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)resolved->ai_addr)->sin6_addr);
if (wildcard) { freeaddrinfo(resolved); [_condition unlock]; return @"Wildcard addresses are not allowed."; }
int fd = socket(resolved->ai_family, SOCK_STREAM, 0), yes = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
int result = fd < 0 ? -1 : bind(fd, resolved->ai_addr, (socklen_t)resolved->ai_addrlen);
freeaddrinfo(resolved);
if (result || listen(fd, 8)) {
if (fd >= 0) close(fd); [_condition unlock]; return @"Could not open input port on this address.";
}
_server = fd; NSUInteger generation = ++_generation;
[_condition unlock];
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ [self serve:fd generation:generation]; });
return @"";
}
- (void)stop {
[_condition lock]; ++_generation;
// The serving thread owns close(); shutdown interrupts its blocking I/O.
if (_server >= 0) shutdown(_server, SHUT_RDWR);
if (_client >= 0) shutdown(_client, SHUT_RDWR);
_server = _client = -1; _requestId = 0; _pending = _reply = nil;
[_condition broadcast]; [_condition unlock];
}
- (NSString *)nextRequest {
[_condition lock];
NSString *result = NSDate.date.timeIntervalSince1970 < _deadline ? _pending : nil;
_pending = nil; [_condition unlock]; return result;
}
- (void)setRequestListener:(void (^)(void))listener {
[_condition lock]; _requestListener = [listener copy]; [_condition unlock];
}
- (void)notifyRequestReady:(long long)identifier {
// Dispatch from under the condition lock; invoke JS only on the main thread,
// outside the lock, and discard notifications invalidated by stop/timeout.
dispatch_async(dispatch_get_main_queue(), ^{
[self->_condition lock];
void (^callback)(void) = self->_requestId == identifier && self->_pending &&
NSDate.date.timeIntervalSince1970 < self->_deadline ? self->_requestListener : nil;
[self->_condition unlock];
if (callback) callback();
});
}
- (void)complete:(long long)identifier response:(NSString *)response {
[_condition lock];
if (_requestId == identifier && NSDate.date.timeIntervalSince1970 < _deadline) { _reply = response; [_condition signal]; }
[_condition unlock];
}
- (void)serve:(int)listener generation:(NSUInteger)generation {
for (;;) {
[_condition lock]; BOOL current = generation == _generation; [_condition unlock];
if (!current) break;
// Poll also guarantees stop is observed on platforms where shutdown does not wake accept.
struct pollfd p = { .fd = listener, .events = POLLIN };
if (poll(&p, 1, 250) <= 0) continue;
int client = accept(listener, NULL, NULL);
if (client < 0) break;
@autoreleasepool {
[_condition lock]; current = generation == _generation;
if (current) _client = client;
[_condition unlock];
if (!current) { close(client); break; }
struct timeval timeout = {5, 0}; int yes = 1;
setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
setsockopt(client, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(yes));
NSTimeInterval readDeadline = NSDate.date.timeIntervalSince1970 + 5;
NSMutableData *body = [NSMutableData new]; unsigned char byte; BOOL complete = NO;
while (body.length <= 65536) {
NSTimeInterval remaining = readDeadline - NSDate.date.timeIntervalSince1970;
struct pollfd input = { .fd = client, .events = POLLIN };
if (remaining <= 0 || poll(&input, 1, (int)(remaining * 1000)) <= 0 || recv(client, &byte, 1, 0) != 1) break;
if (byte == '\n') { complete = YES; break; }
[body appendBytes:&byte length:1];
}
NSString *text = complete ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil;
if (text) {
[_condition lock];
if (generation == _generation) {
_requestId = ++_nextId; _deadline = NSDate.date.timeIntervalSince1970 + 5; _reply = nil;
NSData *json = [NSJSONSerialization dataWithJSONObject:@{@"id":@(_requestId), @"expiresAt":@(_deadline * 1000), @"body":text} options:0 error:nil];
_pending = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
[self notifyRequestReady:_requestId];
while (!_reply && generation == _generation && NSDate.date.timeIntervalSince1970 < _deadline)
[_condition waitUntilDate:[NSDate dateWithTimeIntervalSince1970:_deadline]];
NSString *reply = _reply ?: @"{\"ok\":false,\"error\":\"timeout\",\"message\":\"Faceclaw did not respond in time.\"}";
if (generation == _generation) { _pending = _reply = nil; _requestId = 0; }
[_condition unlock];
NSData *data = [[reply stringByAppendingString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger offset = 0;
while (offset < data.length) {
ssize_t n = send(client, (const char *)data.bytes + offset, data.length - offset, 0);
if (n <= 0) break; offset += n;
}
} else [_condition unlock];
}
[_condition lock]; if (generation == _generation) _client = -1; [_condition unlock];
close(client);
}
}
close(listener);
[_condition lock]; if (generation == _generation) _server = -1; [_condition unlock];
}
+ (NSString *)interfaces {
NSMutableArray *result = [NSMutableArray new]; struct ifaddrs *interfaces = NULL;
if (getifaddrs(&interfaces) == 0) {
for (struct ifaddrs *item = interfaces; item; item = item->ifa_next) {
if (!item->ifa_addr || !(item->ifa_flags & IFF_UP) || (item->ifa_flags & IFF_LOOPBACK)) continue;
int family = item->ifa_addr->sa_family;
if (family != AF_INET && family != AF_INET6) continue;
char address[NI_MAXHOST];
if (getnameinfo(item->ifa_addr, item->ifa_addr->sa_len, address, sizeof(address), NULL, 0, NI_NUMERICHOST)) continue;
[result addObject:@{@"name":@(item->ifa_name), @"address":@(address), @"pointToPoint":@((item->ifa_flags & IFF_POINTOPOINT) != 0)}];
}
freeifaddrs(interfaces);
}
return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:result options:0 error:nil] encoding:NSUTF8StringEncoding];
}
- (NSString *)randomSecret {
unsigned char bytes[32];
if (SecRandomCopyBytes(kSecRandomDefault, sizeof(bytes), bytes) != errSecSuccess) return @"";
NSMutableString *hex = [NSMutableString new];
for (NSUInteger i = 0; i < sizeof(bytes); i++) [hex appendFormat:@"%02x", bytes[i]];
return hex;
}
- (NSString *)tokenDigest:(NSString *)value { return [FaceclawCrypto sha256:[value dataUsingEncoding:NSUTF8StringEncoding]]; }
@end
@@ -1,8 +0,0 @@
#import <Foundation/Foundation.h>
/** Streaming POST. Events are polled by the owning JS isolate, including workers. */
@interface FaceclawSseRequest : NSObject <NSURLSessionDataDelegate>
- (instancetype)initWithURL:(NSString *)url body:(NSString *)body headers:(NSString *)headersJson;
- (NSString *)takeEvents;
- (void)cancel;
@end
-153
View File
@@ -1,153 +0,0 @@
#import "FaceclawSseRequest.h"
#import <TargetConditionals.h>
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
#endif
@interface FaceclawSseRequest ()
@property(nonatomic, strong) NSURLSession *session;
@property(nonatomic, strong) NSURLSessionDataTask *task;
@property(nonatomic, strong) NSMutableData *buffer;
@property(nonatomic, strong) NSMutableArray *events;
@property(nonatomic) NSUInteger queuedBytes;
@property(nonatomic) NSInteger status;
@property(nonatomic) BOOL finished;
@property(nonatomic) BOOL cancelled;
@property(nonatomic) BOOL firstLine;
#if TARGET_OS_IOS
@property(nonatomic) UIBackgroundTaskIdentifier backgroundTask;
#endif
@end
@implementation FaceclawSseRequest
- (instancetype)initWithURL:(NSString *)url body:(NSString *)body headers:(NSString *)headersJson {
if ((self = [super init])) {
_buffer = [NSMutableData new]; _events = [NSMutableArray new]; _firstLine = YES;
#if TARGET_OS_IOS
_backgroundTask = UIBackgroundTaskInvalid;
dispatch_async(dispatch_get_main_queue(), ^{
@synchronized(self) {
if (self.cancelled || self.finished) return;
self.backgroundTask = [UIApplication.sharedApplication beginBackgroundTaskWithName:@"Assistant response" expirationHandler:^{
[self finish:@{@"kind": @"failure", @"text": @"iOS background time expired. Open Faceclaw and retry."}];
[self endBackgroundTask];
}];
}
});
#endif
NSURL *target = [NSURL URLWithString:url];
if (!target || ![@[@"https", @"http"] containsObject:target.scheme.lowercaseString]) {
[self finish:@{@"kind": @"failure", @"text": @"Invalid streaming URL"}]; return self;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:target];
request.HTTPMethod = @"POST";
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"text/event-stream" forHTTPHeaderField:@"Accept"];
NSDictionary *headers = [NSJSONSerialization JSONObjectWithData:[headersJson dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
if ([headers isKindOfClass:NSDictionary.class]) for (NSString *name in headers) {
if ([headers[name] isKindOfClass:NSString.class]) [request setValue:headers[name] forHTTPHeaderField:name];
}
NSURLSessionConfiguration *config = NSURLSessionConfiguration.ephemeralSessionConfiguration;
config.timeoutIntervalForRequest = 180;
config.timeoutIntervalForResource = 180;
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
_task = [_session dataTaskWithRequest:request];
[_task resume];
}
return self;
}
- (void)endBackgroundTask {
#if TARGET_OS_IOS
dispatch_async(dispatch_get_main_queue(), ^{
@synchronized(self) {
if (self.backgroundTask == UIBackgroundTaskInvalid) return;
[UIApplication.sharedApplication endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}
});
#endif
}
- (void)finish:(NSDictionary *)event {
@synchronized(self) {
if (_finished || _cancelled) return;
_finished = YES; [_events addObject:event];
[_session invalidateAndCancel]; _session = nil; _task = nil;
[_buffer setLength:0];
}
}
- (NSString *)takeEvents {
@synchronized(self) {
NSData *data = [NSJSONSerialization dataWithJSONObject:_events options:0 error:nil];
[_events removeAllObjects]; _queuedBytes = 0;
if (_finished) [self endBackgroundTask];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"[]";
}
}
- (void)cancel {
@synchronized(self) {
_cancelled = YES;
[_events removeAllObjects]; [_buffer setLength:0]; _queuedBytes = 0;
[_session invalidateAndCancel]; _session = nil; _task = nil;
[self endBackgroundTask];
}
}
- (void)line:(NSData *)data {
NSString *line = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (!line) { [self finish:@{@"kind": @"failure", @"text": @"Invalid UTF-8 in streaming response"}]; return; }
if (_firstLine && [line hasPrefix:@"\uFEFF"]) line = [line substringFromIndex:1];
_firstLine = NO;
_queuedBytes += data.length;
if (_queuedBytes > 8 * 1024 * 1024 || _events.count >= 16384) {
[_events removeAllObjects];
[self finish:@{@"kind": @"failure", @"text": @"Streaming response queue overflow"}]; return;
}
[_events addObject:@{@"kind": @"line", @"text": line}];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
@synchronized(self) { _status = [(NSHTTPURLResponse *)response statusCode]; }
completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler {
// Never forward provider credentials to a redirected endpoint.
completionHandler(nil);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
@synchronized(self) {
if (_finished || _cancelled) return;
if (_status < 200 || _status >= 300) {
NSUInteger remaining = 65536 - _buffer.length;
[_buffer appendData:[data subdataWithRange:NSMakeRange(0, MIN(remaining, data.length))]];
return;
}
[_buffer appendData:data];
NSUInteger start = 0;
const uint8_t *bytes = _buffer.bytes;
for (NSUInteger i = 0; i < _buffer.length; i++) {
if (bytes[i] != '\r' && bytes[i] != '\n') continue;
if (bytes[i] == '\r' && i + 1 == _buffer.length) break;
[self line:[_buffer subdataWithRange:NSMakeRange(start, i - start)]];
if (_finished) return;
if (bytes[i] == '\r' && bytes[i + 1] == '\n') i++;
start = i + 1;
}
if (start) [_buffer replaceBytesInRange:NSMakeRange(0, start) withBytes:NULL length:0];
if (_buffer.length > 2 * 1024 * 1024) [self finish:@{@"kind": @"failure", @"text": @"Streaming response line too large"}];
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
@synchronized(self) {
if (_finished || _cancelled) return;
if (error) { [self finish:@{@"kind": @"failure", @"text": error.localizedDescription}]; return; }
if (_status < 200 || _status >= 300) {
NSString *body = [[NSString alloc] initWithData:_buffer encoding:NSUTF8StringEncoding] ?: @"";
[self finish:@{@"kind": @"http-error", @"code": @(_status), @"text": body}]; return;
}
if (_buffer.length) {
if (((const uint8_t *)_buffer.bytes)[_buffer.length - 1] == '\r') [_buffer setLength:_buffer.length - 1];
[self line:_buffer];
}
[self finish:@{@"kind": @"complete"}];
}
}
@end