VLCHTTPConnection.m 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*****************************************************************************
  2. * VLCHTTPConnection.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Jean-Baptiste Kempf <jb # videolan.org>
  10. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. #import "VLCAppDelegate.h"
  14. #import "VLCHTTPConnection.h"
  15. #import "HTTPConnection.h"
  16. #import "MultipartFormDataParser.h"
  17. #import "HTTPMessage.h"
  18. #import "HTTPDataResponse.h"
  19. #import "HTTPFileResponse.h"
  20. #import "MultipartMessageHeaderField.h"
  21. @interface VLCHTTPConnection()
  22. {
  23. MultipartFormDataParser *_parser;
  24. NSFileHandle *_storeFile;
  25. NSString *_filepath;
  26. NSString *_filename;
  27. UInt64 _contentLength;
  28. UInt64 _receivedContent;
  29. }
  30. @end
  31. @implementation VLCHTTPConnection
  32. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  33. {
  34. // Add support for POST
  35. if ([method isEqualToString:@"POST"]) {
  36. if ([path isEqualToString:@"/upload.json"])
  37. return YES;
  38. }
  39. return [super supportsMethod:method atPath:path];
  40. }
  41. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  42. {
  43. // Inform HTTP server that we expect a body to accompany a POST request
  44. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  45. // here we need to make sure, boundary is set in header
  46. NSString* contentType = [request headerField:@"Content-Type"];
  47. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  48. if (NSNotFound == paramsSeparator)
  49. return NO;
  50. if (paramsSeparator >= contentType.length - 1)
  51. return NO;
  52. NSString* type = [contentType substringToIndex:paramsSeparator];
  53. if (![type isEqualToString:@"multipart/form-data"]) {
  54. // we expect multipart/form-data content type
  55. return NO;
  56. }
  57. // enumerate all params in content-type, and find boundary there
  58. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  59. for (NSString* param in params) {
  60. paramsSeparator = [param rangeOfString:@"="].location;
  61. if ((NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1)
  62. continue;
  63. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  64. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  65. if ([paramName isEqualToString: @"boundary"])
  66. // let's separate the boundary from content-type, to make it more handy to handle
  67. [request setHeaderField:@"boundary" value:paramValue];
  68. }
  69. // check if boundary specified
  70. if (nil == [request headerField:@"boundary"])
  71. return NO;
  72. return YES;
  73. }
  74. return [super expectsRequestBodyFromMethod:method atPath:path];
  75. }
  76. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  77. {
  78. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  79. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  80. }
  81. if ([method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"]) {
  82. // let download the uploaded files
  83. return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];
  84. }
  85. return [super httpResponseForMethod:method URI:path];
  86. }
  87. - (void)prepareForBodyWithSize:(UInt64)contentLength
  88. {
  89. // set up mime parser
  90. NSString* boundary = [request headerField:@"boundary"];
  91. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  92. _parser.delegate = self;
  93. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  94. _contentLength = contentLength;
  95. }
  96. - (void)processBodyData:(NSData *)postDataChunk
  97. {
  98. /* append data to the parser. It will invoke callbacks to let us handle
  99. * parsed data. */
  100. [_parser appendData:postDataChunk];
  101. _receivedContent += postDataChunk.length;
  102. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  103. }
  104. //-----------------------------------------------------------------
  105. #pragma mark multipart form data parser delegate
  106. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  107. {
  108. /* in this sample, we are not interested in parts, other then file parts.
  109. * check content disposition to find out filename */
  110. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  111. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  112. if ((nil == filename) || [filename isEqualToString: @""]) {
  113. // it's either not a file part, or
  114. // an empty form sent. we won't handle it.
  115. return;
  116. }
  117. _filename = filename;
  118. // create the path where to store the media temporarily
  119. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES);
  120. NSString* uploadDirPath = searchPaths[0];
  121. NSFileManager *fileManager = [NSFileManager defaultManager];
  122. BOOL isDir = YES;
  123. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  124. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  125. }
  126. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  127. APLog(@"Saving file to %@", _filepath);
  128. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  129. APLog(@"Could not create directory at path: %@", _filepath);
  130. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  131. APLog(@"Could not create file at path: %@", _filepath);
  132. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  133. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  134. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  135. }
  136. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  137. {
  138. // here we just write the output from parser to the file.
  139. if (_storeFile)
  140. [_storeFile writeData:data];
  141. }
  142. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  143. {
  144. // as the file part is over, we close the file.
  145. APLog(@"closing file");
  146. [_storeFile closeFile];
  147. _storeFile = nil;
  148. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  149. NSString *libraryPath = searchPaths[0];
  150. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:_filename];
  151. NSFileManager *fileManager = [NSFileManager defaultManager];
  152. if ([fileManager fileExistsAtPath:finalFilePath]) {
  153. /* we don't want to over-write existing files, so add an integer to the file name */
  154. NSString *potentialFilename;
  155. NSString *fileExtension = [_filename pathExtension];
  156. NSString *rawFileName = [_filename stringByDeletingPathExtension];
  157. for (NSUInteger x = 1; x < 100; x++) {
  158. potentialFilename = [NSString stringWithFormat:@"%@ %i.%@", rawFileName, x, fileExtension];
  159. if (![[NSFileManager defaultManager] fileExistsAtPath:[libraryPath stringByAppendingPathComponent:potentialFilename]])
  160. break;
  161. }
  162. finalFilePath = [libraryPath stringByAppendingPathComponent:potentialFilename];
  163. }
  164. NSError *error;
  165. [fileManager moveItemAtPath:_filepath toPath:finalFilePath error:&error];
  166. if (error) {
  167. APLog(@"Moving received media %@ to library folder failed (%i), deleting", _filename, error.code);
  168. [fileManager removeItemAtPath:_filepath error:nil];
  169. }
  170. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  171. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate activateIdleTimer];
  172. /* update media library when file upload was completed */
  173. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  174. [appDelegate updateMediaList];
  175. }
  176. - (void)die
  177. {
  178. if (_storeFile) {
  179. _storeFile = nil;
  180. [[NSFileManager defaultManager] removeItemAtPath:_filepath error:nil];
  181. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  182. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate activateIdleTimer];
  183. }
  184. [super die];
  185. }
  186. @end