Private
Public Access
1
0
Files
Kordophone/kordophone/Bridge/MBIMHTTPConnection.m
2018-11-20 19:57:35 -07:00

88 lines
2.3 KiB
Objective-C

//
// MBIMHTTPConnection.m
// CocoaHTTPServer
//
// Created by James Magahern on 11/16/18.
// Copyright © 2018 James Magahern. All rights reserved.
//
#import "MBIMHTTPConnection.h"
#import "MBIMBridge.h"
#import "MBIMBridgeOperation.h"
@implementation MBIMHTTPConnection {
NSMutableData *_bodyData;
MBIMBridgeOperation *_currentOperation;
}
- (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
{
if ([method isEqualToString:@"GET"] || [method isEqualToString:@"POST"]) {
return YES;
}
return NO;
}
- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
{
__block NSObject<HTTPResponse> *response = nil;
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
MBIMBridgeOperationCompletionBlock completion = ^(NSObject<HTTPResponse> *incomingResponse) {
response = incomingResponse;
dispatch_semaphore_signal(sema);
};
NSURL *url = [NSURL URLWithString:path];
NSString *endpointName = [url lastPathComponent];
BOOL requestTimedOut = NO;
Class operationClass = [MBIMBridgeOperation operationClassForEndpointName:endpointName];
if (operationClass != nil) {
_currentOperation = [[operationClass alloc] initWithRequestURL:url completion:completion];
_currentOperation.requestBodyData = _bodyData;
[[[MBIMBridge sharedInstance] operationQueue] addOperation:_currentOperation];
long status = dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60.0 * NSEC_PER_SEC)));
if (status != 0) {
requestTimedOut = YES;
}
} else {
response = [[HTTPErrorResponse alloc] initWithErrorCode:404];
}
if (requestTimedOut) {
response = [_currentOperation cancelAndReturnTimeoutResponse];
}
return response;
}
- (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
{
if ([method isEqualToString:@"POST"]) {
return YES;
}
return NO;
}
- (void)prepareForBodyWithSize:(UInt64)contentLength
{
_bodyData = [[NSMutableData alloc] initWithCapacity:contentLength];
}
- (void)processBodyData:(NSData *)postDataChunk
{
[_bodyData appendData:postDataChunk];
}
- (void)die
{
[_currentOperation cancel];
[super die];
}
@end