PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/AngelHackVisualization/AFNetworking/AFHTTPRequestOperation.m

https://bitbucket.org/PixelPatrol/hack1display
Objective C | 319 lines | 241 code | 50 blank | 28 comment | 52 complexity | 5464aeef2f2c801a9ea1f0d2b6e34cb5 MD5 | raw file
  1. // AFHTTPRequestOperation.m
  2. //
  3. // Copyright (c) 2011 Gowalla (http://gowalla.com/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. #import "AFHTTPRequestOperation.h"
  23. #import <objc/runtime.h>
  24. // Workaround for change in imp_implementationWithBlock() with Xcode 4.5
  25. #if defined(__IPHONE_6_0) || defined(__MAC_10_8)
  26. #define AF_CAST_TO_BLOCK id
  27. #else
  28. #define AF_CAST_TO_BLOCK __bridge void *
  29. #endif
  30. #pragma clang diagnostic push
  31. #pragma clang diagnostic ignored "-Wstrict-selector-match"
  32. NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
  33. if (!string) {
  34. return nil;
  35. }
  36. NSArray *mediaRanges = [string componentsSeparatedByString:@","];
  37. NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count];
  38. [mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, __unused NSUInteger idx, __unused BOOL *stop) {
  39. NSRange parametersRange = [mediaRange rangeOfString:@";"];
  40. if (parametersRange.location != NSNotFound) {
  41. mediaRange = [mediaRange substringToIndex:parametersRange.location];
  42. }
  43. mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  44. if (mediaRange.length > 0) {
  45. [mutableContentTypes addObject:mediaRange];
  46. }
  47. }];
  48. return [NSSet setWithSet:mutableContentTypes];
  49. }
  50. static void AFGetMediaTypeAndSubtypeWithString(NSString *string, NSString **type, NSString **subtype) {
  51. NSScanner *scanner = [NSScanner scannerWithString:string];
  52. [scanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  53. [scanner scanUpToString:@"/" intoString:type];
  54. [scanner scanString:@"/" intoString:nil];
  55. [scanner scanUpToString:@";" intoString:subtype];
  56. }
  57. static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
  58. NSMutableString *string = [NSMutableString string];
  59. NSRange range = NSMakeRange([indexSet firstIndex], 1);
  60. while (range.location != NSNotFound) {
  61. NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location];
  62. while (nextIndex == range.location + range.length) {
  63. range.length++;
  64. nextIndex = [indexSet indexGreaterThanIndex:nextIndex];
  65. }
  66. if (string.length) {
  67. [string appendString:@","];
  68. }
  69. if (range.length == 1) {
  70. [string appendFormat:@"%lu", (long)range.location];
  71. } else {
  72. NSUInteger firstIndex = range.location;
  73. NSUInteger lastIndex = firstIndex + range.length - 1;
  74. [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex];
  75. }
  76. range.location = nextIndex;
  77. range.length = 1;
  78. }
  79. return string;
  80. }
  81. static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) {
  82. Method originalMethod = class_getClassMethod(klass, selector);
  83. IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block);
  84. class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod));
  85. }
  86. #pragma mark -
  87. @interface AFHTTPRequestOperation ()
  88. @property (readwrite, nonatomic, strong) NSURLRequest *request;
  89. @property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
  90. @property (readwrite, nonatomic, strong) NSError *HTTPError;
  91. @end
  92. @implementation AFHTTPRequestOperation
  93. @synthesize HTTPError = _HTTPError;
  94. @synthesize successCallbackQueue = _successCallbackQueue;
  95. @synthesize failureCallbackQueue = _failureCallbackQueue;
  96. @dynamic request;
  97. @dynamic response;
  98. - (void)dealloc {
  99. if (_successCallbackQueue) {
  100. #if !OS_OBJECT_USE_OBJC
  101. dispatch_release(_successCallbackQueue);
  102. #endif
  103. _successCallbackQueue = NULL;
  104. }
  105. if (_failureCallbackQueue) {
  106. #if !OS_OBJECT_USE_OBJC
  107. dispatch_release(_failureCallbackQueue);
  108. #endif
  109. _failureCallbackQueue = NULL;
  110. }
  111. }
  112. - (NSError *)error {
  113. if (!self.HTTPError && self.response) {
  114. if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) {
  115. NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
  116. [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey];
  117. [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
  118. [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
  119. [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
  120. if (![self hasAcceptableStatusCode]) {
  121. NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
  122. [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey];
  123. self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo];
  124. } else if (![self hasAcceptableContentType]) {
  125. // Don't invalidate content type if there is no content
  126. if ([self.responseData length] > 0) {
  127. [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected content type %@, got %@", @"AFNetworking", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
  128. self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
  129. }
  130. }
  131. }
  132. }
  133. if (self.HTTPError) {
  134. return self.HTTPError;
  135. } else {
  136. return [super error];
  137. }
  138. }
  139. - (NSStringEncoding)responseStringEncoding {
  140. // When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value.
  141. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.4.1
  142. if (self.response && !self.response.textEncodingName && self.responseData && [self.response respondsToSelector:@selector(allHeaderFields)]) {
  143. NSString *type = nil;
  144. AFGetMediaTypeAndSubtypeWithString([[self.response allHeaderFields] valueForKey:@"Content-Type"], &type, nil);
  145. if ([type isEqualToString:@"text"]) {
  146. return NSISOLatin1StringEncoding;
  147. }
  148. }
  149. return [super responseStringEncoding];
  150. }
  151. - (void)pause {
  152. unsigned long long offset = 0;
  153. if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
  154. offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
  155. } else {
  156. offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
  157. }
  158. NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
  159. if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
  160. [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
  161. }
  162. [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
  163. self.request = mutableURLRequest;
  164. [super pause];
  165. }
  166. - (BOOL)hasAcceptableStatusCode {
  167. if (!self.response) {
  168. return NO;
  169. }
  170. NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
  171. return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
  172. }
  173. - (BOOL)hasAcceptableContentType {
  174. if (!self.response) {
  175. return NO;
  176. }
  177. // Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".
  178. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
  179. NSString *contentType = [self.response MIMEType];
  180. if (!contentType) {
  181. contentType = @"application/octet-stream";
  182. }
  183. return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
  184. }
  185. - (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
  186. if (successCallbackQueue != _successCallbackQueue) {
  187. if (_successCallbackQueue) {
  188. #if !OS_OBJECT_USE_OBJC
  189. dispatch_release(_successCallbackQueue);
  190. #endif
  191. _successCallbackQueue = NULL;
  192. }
  193. if (successCallbackQueue) {
  194. #if !OS_OBJECT_USE_OBJC
  195. dispatch_retain(successCallbackQueue);
  196. #endif
  197. _successCallbackQueue = successCallbackQueue;
  198. }
  199. }
  200. }
  201. - (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
  202. if (failureCallbackQueue != _failureCallbackQueue) {
  203. if (_failureCallbackQueue) {
  204. #if !OS_OBJECT_USE_OBJC
  205. dispatch_release(_failureCallbackQueue);
  206. #endif
  207. _failureCallbackQueue = NULL;
  208. }
  209. if (failureCallbackQueue) {
  210. #if !OS_OBJECT_USE_OBJC
  211. dispatch_retain(failureCallbackQueue);
  212. #endif
  213. _failureCallbackQueue = failureCallbackQueue;
  214. }
  215. }
  216. }
  217. - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  218. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
  219. {
  220. // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
  221. #pragma clang diagnostic push
  222. #pragma clang diagnostic ignored "-Warc-retain-cycles"
  223. #pragma clang diagnostic ignored "-Wgnu"
  224. self.completionBlock = ^{
  225. if (self.error) {
  226. if (failure) {
  227. dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
  228. failure(self, self.error);
  229. });
  230. }
  231. } else {
  232. if (success) {
  233. dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
  234. success(self, self.responseData);
  235. });
  236. }
  237. }
  238. };
  239. #pragma clang diagnostic pop
  240. }
  241. #pragma mark - AFHTTPRequestOperation
  242. + (NSIndexSet *)acceptableStatusCodes {
  243. return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
  244. }
  245. + (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
  246. NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]];
  247. [mutableStatusCodes addIndexes:statusCodes];
  248. AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(__unused id _self) {
  249. return mutableStatusCodes;
  250. });
  251. }
  252. + (NSSet *)acceptableContentTypes {
  253. return nil;
  254. }
  255. + (void)addAcceptableContentTypes:(NSSet *)contentTypes {
  256. NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES];
  257. [mutableContentTypes unionSet:contentTypes];
  258. AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(__unused id _self) {
  259. return mutableContentTypes;
  260. });
  261. }
  262. + (BOOL)canProcessRequest:(NSURLRequest *)request {
  263. if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
  264. return YES;
  265. }
  266. return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
  267. }
  268. @end
  269. #pragma clang diagnostic pop