VLCHTTPConnection.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. #import "VLCHTTPUploaderController.h"
  22. #import "HTTPDynamicFileResponse.h"
  23. #import "VLCThumbnailsCache.h"
  24. @interface VLCHTTPConnection()
  25. {
  26. MultipartFormDataParser *_parser;
  27. NSFileHandle *_storeFile;
  28. NSString *_filepath;
  29. UInt64 _contentLength;
  30. UInt64 _receivedContent;
  31. }
  32. @end
  33. @implementation VLCHTTPConnection
  34. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  35. {
  36. // Add support for POST
  37. if ([method isEqualToString:@"POST"]) {
  38. if ([path isEqualToString:@"/upload.json"])
  39. return YES;
  40. }
  41. return [super supportsMethod:method atPath:path];
  42. }
  43. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  44. {
  45. // Inform HTTP server that we expect a body to accompany a POST request
  46. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  47. // here we need to make sure, boundary is set in header
  48. NSString* contentType = [request headerField:@"Content-Type"];
  49. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  50. if (NSNotFound == paramsSeparator)
  51. return NO;
  52. if (paramsSeparator >= contentType.length - 1)
  53. return NO;
  54. NSString* type = [contentType substringToIndex:paramsSeparator];
  55. if (![type isEqualToString:@"multipart/form-data"]) {
  56. // we expect multipart/form-data content type
  57. return NO;
  58. }
  59. // enumerate all params in content-type, and find boundary there
  60. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  61. for (NSString* param in params) {
  62. paramsSeparator = [param rangeOfString:@"="].location;
  63. if ((NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1)
  64. continue;
  65. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  66. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  67. if ([paramName isEqualToString: @"boundary"])
  68. // let's separate the boundary from content-type, to make it more handy to handle
  69. [request setHeaderField:@"boundary" value:paramValue];
  70. }
  71. // check if boundary specified
  72. if (nil == [request headerField:@"boundary"])
  73. return NO;
  74. return YES;
  75. }
  76. return [super expectsRequestBodyFromMethod:method atPath:path];
  77. }
  78. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  79. {
  80. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  81. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  82. }
  83. if ([path hasPrefix:@"/download/"]) {
  84. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/download/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  85. HTTPFileResponse *fileResponse = [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
  86. fileResponse.contentType = @"application/octet-stream";
  87. return fileResponse;
  88. }
  89. if ([path hasPrefix:@"/thumbnail"]) {
  90. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/thumbnail/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  91. filePath = [filePath stringByReplacingOccurrencesOfString:@".png" withString:@""];
  92. NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
  93. NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
  94. NSManagedObject *mo = [moc existingObjectWithID:[psc managedObjectIDForURIRepresentation:[NSURL URLWithString:filePath]] error:nil];
  95. NSData *theData;
  96. if ([mo isKindOfClass:[MLFile class]])
  97. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForMediaFile:(MLFile *)mo]);
  98. else if ([mo isKindOfClass:[MLShow class]])
  99. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForShow:(MLShow *)mo]);
  100. else if ([mo isKindOfClass:[MLLabel class]])
  101. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForLabel:(MLLabel *)mo]);
  102. else if ([mo isKindOfClass:[MLAlbum class]])
  103. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForMediaFile:[[(MLAlbum *)mo tracks].anyObject files].anyObject]);
  104. else if ([mo isKindOfClass:[MLAlbumTrack class]])
  105. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForMediaFile:[(MLAlbumTrack *)mo files].anyObject]);
  106. else if ([mo isKindOfClass:[MLShowEpisode class]])
  107. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForMediaFile:[(MLShowEpisode *)mo files].anyObject]);
  108. if (theData) {
  109. HTTPDataResponse *dataResponse = [[HTTPDataResponse alloc] initWithData:theData];
  110. dataResponse.contentType = @"image/png";
  111. return dataResponse;
  112. }
  113. }
  114. NSString *filePath = [self filePathForURI:path];
  115. NSString *documentRoot = [config documentRoot];
  116. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  117. if ([relativePath isEqualToString:@"/index.html"]) {
  118. NSMutableArray *allMedia = [[NSMutableArray alloc] init];
  119. /* add all albums */
  120. NSArray *allAlbums = [MLAlbum allAlbums];
  121. for (MLAlbum *album in allAlbums) {
  122. if (album.name.length > 0 && album.tracks.count > 1)
  123. [allMedia addObject:album];
  124. }
  125. /* add all shows */
  126. NSArray *allShows = [MLShow allShows];
  127. for (MLShow *show in allShows) {
  128. if (show.name.length > 0 && show.episodes.count > 1)
  129. [allMedia addObject:show];
  130. }
  131. /* add all folders*/
  132. NSArray *allFolders = [MLLabel allLabels];
  133. for (MLLabel *folder in allFolders)
  134. [allMedia addObject:folder];
  135. /* add all remaining files */
  136. NSArray *allFiles = [MLFile allFiles];
  137. for (MLFile *file in allFiles) {
  138. if (file.labels.count > 0) continue;
  139. if (!file.isShowEpisode && !file.isAlbumTrack)
  140. [allMedia addObject:file];
  141. else if (file.isShowEpisode) {
  142. if (file.showEpisode.show.episodes.count < 2)
  143. [allMedia addObject:file];
  144. } else if (file.isAlbumTrack) {
  145. if (file.albumTrack.album.tracks.count < 2)
  146. [allMedia addObject:file];
  147. }
  148. }
  149. NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:allMedia.count];
  150. for (NSManagedObject *mo in allMedia) {
  151. if ([mo isKindOfClass:[MLFile class]])
  152. [mediaInHtml addObject:[NSString stringWithFormat:@"<li><img src=\"thumbnail/%@.png\" alt="" /> - <a href=\"download/%@\" download>%@</a></li>", mo.objectID.URIRepresentation, [[(MLFile *)mo url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], [(MLFile *)mo title]]];
  153. else if ([mo isKindOfClass:[MLShow class]]) {
  154. NSArray *episodes = [(MLShow *)mo sortedEpisodes];
  155. [mediaInHtml addObject:[NSString stringWithFormat:@"<li><img src=\"thumbnail/%@.png\" alt="" /> - %@</li>", mo.objectID.URIRepresentation, [(MLShow *)mo name]]];
  156. for (MLShowEpisode *showEp in episodes)
  157. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><img src=\"thumbnail/%@.png\" alt="" /> - <a href=\"download/%@\" download>%@</a></lu><br />", showEp.objectID.URIRepresentation, [[(MLFile *)[[showEp files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], showEp.name]];
  158. } else if ([mo isKindOfClass:[MLLabel class]]) {
  159. NSArray *folderItems = [(MLLabel *)mo sortedFolderItems];
  160. [mediaInHtml addObject:[NSString stringWithFormat:@"<li><img src=\"thumbnail/%@.png\" alt="" /> - %@</li>", mo.objectID.URIRepresentation, [(MLLabel *)mo name]]];
  161. for (MLFile *file in folderItems)
  162. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><img src=\"thumbnail/%@.png\" alt="" /> - <a href=\"download/%@\" download>%@</a></lu><br />", file.objectID.URIRepresentation, [[file url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], file.title]];
  163. } else if ([mo isKindOfClass:[MLAlbum class]]) {
  164. NSArray *albumTracks = [(MLAlbum *)mo sortedTracks];
  165. [mediaInHtml addObject:[NSString stringWithFormat:@"<li><img src=\"thumbnail/%@.png\" alt="" /> - %@</li>", mo.objectID.URIRepresentation, [(MLAlbum *)mo name]]];
  166. for (MLAlbumTrack *track in albumTracks)
  167. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><img src=\"thumbnail/%@.png\" alt="" /> - <a href=\"download/%@\" download>%@</a></lu><br />", track.objectID.URIRepresentation, [[(MLFile *)[[track files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], track.title]];
  168. }
  169. }
  170. NSDictionary *replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
  171. @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
  172. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  173. @"WEBINTF_DROPFILES_LONG" : NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil),
  174. @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
  175. @"WEBINTF_DOWNLOADFILES_LONG" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil)};
  176. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  177. forConnection:self
  178. separator:@"%%"
  179. replacementDictionary:replacementDict];
  180. } else if ([relativePath isEqualToString:@"/style.css"]) {
  181. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
  182. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  183. forConnection:self
  184. separator:@"%%"
  185. replacementDictionary:replacementDict];
  186. }
  187. return [super httpResponseForMethod:method URI:path];
  188. }
  189. - (void)prepareForBodyWithSize:(UInt64)contentLength
  190. {
  191. // set up mime parser
  192. NSString* boundary = [request headerField:@"boundary"];
  193. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  194. _parser.delegate = self;
  195. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  196. _contentLength = contentLength;
  197. }
  198. - (void)processBodyData:(NSData *)postDataChunk
  199. {
  200. /* append data to the parser. It will invoke callbacks to let us handle
  201. * parsed data. */
  202. [_parser appendData:postDataChunk];
  203. _receivedContent += postDataChunk.length;
  204. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  205. }
  206. //-----------------------------------------------------------------
  207. #pragma mark multipart form data parser delegate
  208. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  209. {
  210. /* in this sample, we are not interested in parts, other then file parts.
  211. * check content disposition to find out filename */
  212. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  213. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  214. if ((nil == filename) || [filename isEqualToString: @""]) {
  215. // it's either not a file part, or
  216. // an empty form sent. we won't handle it.
  217. return;
  218. }
  219. // create the path where to store the media temporarily
  220. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  221. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  222. NSFileManager *fileManager = [NSFileManager defaultManager];
  223. BOOL isDir = YES;
  224. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  225. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  226. }
  227. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  228. APLog(@"Saving file to %@", _filepath);
  229. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  230. APLog(@"Could not create directory at path: %@", _filepath);
  231. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  232. APLog(@"Could not create file at path: %@", _filepath);
  233. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  234. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  235. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  236. }
  237. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  238. {
  239. // here we just write the output from parser to the file.
  240. if (_storeFile) {
  241. @try {
  242. [_storeFile writeData:data];
  243. }
  244. @catch (NSException *exception) {
  245. APLog(@"File to write further data because storage is full.");
  246. [_storeFile closeFile];
  247. _storeFile = nil;
  248. /* don't block */
  249. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  250. }
  251. }
  252. }
  253. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  254. {
  255. // as the file part is over, we close the file.
  256. APLog(@"closing file");
  257. [_storeFile closeFile];
  258. _storeFile = nil;
  259. }
  260. - (BOOL)shouldDie
  261. {
  262. if (_filepath) {
  263. if (_filepath.length > 0)
  264. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
  265. }
  266. return [super shouldDie];
  267. }
  268. @end