VLCHTTPConnection.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. return [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
  86. }
  87. if ([path hasPrefix:@"/thumbnail"]) {
  88. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/thumbnail/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  89. filePath = [filePath stringByReplacingOccurrencesOfString:@".png" withString:@""];
  90. NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
  91. NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
  92. NSManagedObject *mo = [moc existingObjectWithID:[psc managedObjectIDForURIRepresentation:[NSURL URLWithString:filePath]] error:nil];
  93. NSData *theData;
  94. if ([mo isKindOfClass:[MLFile class]])
  95. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForMediaFile:(MLFile *)mo]);
  96. else if ([mo isKindOfClass:[MLShow class]])
  97. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForShow:(MLShow *)mo]);
  98. else if ([mo isKindOfClass:[MLLabel class]])
  99. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForLabel:(MLLabel *)mo]);
  100. else if ([mo isKindOfClass:[MLAlbum class]])
  101. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForMediaFile:[[(MLAlbum *)mo tracks].anyObject files].anyObject]);
  102. else if ([mo isKindOfClass:[MLAlbumTrack class]])
  103. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForMediaFile:[(MLAlbumTrack *)mo files].anyObject]);
  104. else if ([mo isKindOfClass:[MLShowEpisode class]])
  105. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForMediaFile:[(MLShowEpisode *)mo files].anyObject]);
  106. if (theData)
  107. return [[HTTPDataResponse alloc] initWithData:theData];
  108. }
  109. NSString *filePath = [self filePathForURI:path];
  110. NSString *documentRoot = [config documentRoot];
  111. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  112. if ([relativePath isEqualToString:@"/index.html"]) {
  113. NSMutableArray *allMedia = [[NSMutableArray alloc] init];
  114. /* add all albums */
  115. NSArray *allAlbums = [MLAlbum allAlbums];
  116. for (MLAlbum *album in allAlbums) {
  117. if (album.name.length > 0 && album.tracks.count > 1)
  118. [allMedia addObject:album];
  119. }
  120. /* add all shows */
  121. NSArray *allShows = [MLShow allShows];
  122. for (MLShow *show in allShows) {
  123. if (show.name.length > 0 && show.episodes.count > 1)
  124. [allMedia addObject:show];
  125. }
  126. /* add all folders*/
  127. NSArray *allFolders = [MLLabel allLabels];
  128. for (MLLabel *folder in allFolders)
  129. [allMedia addObject:folder];
  130. /* add all remaining files */
  131. NSArray *allFiles = [MLFile allFiles];
  132. for (MLFile *file in allFiles) {
  133. if (file.labels.count > 0) continue;
  134. if (!file.isShowEpisode && !file.isAlbumTrack)
  135. [allMedia addObject:file];
  136. else if (file.isShowEpisode) {
  137. if (file.showEpisode.show.episodes.count < 2)
  138. [allMedia addObject:file];
  139. } else if (file.isAlbumTrack) {
  140. if (file.albumTrack.album.tracks.count < 2)
  141. [allMedia addObject:file];
  142. }
  143. }
  144. NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:allMedia.count];
  145. for (NSManagedObject *mo in allMedia) {
  146. if ([mo isKindOfClass:[MLFile class]])
  147. [mediaInHtml addObject:[NSString stringWithFormat:@"<li><a href=\"download/%@\" download>%@</a> — <a href=\"thumbnail/%@.png\">preview</a></li>", [[(MLFile *)mo url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], [(MLFile *)mo title], mo.objectID.URIRepresentation]];
  148. else if ([mo isKindOfClass:[MLShow class]]) {
  149. NSArray *episodes = [(MLShow *)mo sortedEpisodes];
  150. [mediaInHtml addObject:[NSString stringWithFormat:@"<li>%@ — <a href=\"thumbnail/%@.png\">preview</a></li>", [(MLShow *)mo name], mo.objectID.URIRepresentation]];
  151. for (MLShowEpisode *showEp in episodes)
  152. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><a href=\"download/%@\" download>%@</a> — <a href=\"thumbnail/%@.png\">preview</a></lu><br />", [[(MLFile *)[[showEp files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], showEp.name, showEp.objectID.URIRepresentation]];
  153. } else if ([mo isKindOfClass:[MLLabel class]]) {
  154. NSArray *folderItems = [(MLLabel *)mo sortedFolderItems];
  155. [mediaInHtml addObject:[NSString stringWithFormat:@"<li>%@ — <a href=\"thumbnail/%@.png\">preview</a></li>", [(MLLabel *)mo name], mo.objectID.URIRepresentation]];
  156. for (MLFile *file in folderItems)
  157. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><a href=\"download/%@\" download>%@</a> — <a href=\"thumbnail/%@.png\">preview</a></lu><br />", [[file url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], file.title, file.objectID.URIRepresentation]];
  158. } else if ([mo isKindOfClass:[MLAlbum class]]) {
  159. NSArray *albumTracks = [(MLAlbum *)mo sortedTracks];
  160. [mediaInHtml addObject:[NSString stringWithFormat:@"<li>%@ — <a href=\"thumbnail/%@.png\">preview</a></li>", [(MLAlbum *)mo name], mo.objectID.URIRepresentation]];
  161. for (MLAlbumTrack *track in albumTracks)
  162. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><a href=\"download/%@\" download>%@</a> — <a href=\"thumbnail/%@.png\">preview</a></lu><br />", [[(MLFile *)[[track files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], track.title, track.objectID.URIRepresentation]];
  163. }
  164. }
  165. NSDictionary *replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
  166. @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
  167. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  168. @"WEBINTF_DROPFILES_LONG" : NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil),
  169. @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
  170. @"WEBINTF_DOWNLOADFILES_LONG" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil)};
  171. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  172. forConnection:self
  173. separator:@"%%"
  174. replacementDictionary:replacementDict];
  175. } else if ([relativePath isEqualToString:@"/style.css"]) {
  176. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
  177. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  178. forConnection:self
  179. separator:@"%%"
  180. replacementDictionary:replacementDict];
  181. }
  182. return [super httpResponseForMethod:method URI:path];
  183. }
  184. - (void)prepareForBodyWithSize:(UInt64)contentLength
  185. {
  186. // set up mime parser
  187. NSString* boundary = [request headerField:@"boundary"];
  188. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  189. _parser.delegate = self;
  190. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  191. _contentLength = contentLength;
  192. }
  193. - (void)processBodyData:(NSData *)postDataChunk
  194. {
  195. /* append data to the parser. It will invoke callbacks to let us handle
  196. * parsed data. */
  197. [_parser appendData:postDataChunk];
  198. _receivedContent += postDataChunk.length;
  199. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  200. }
  201. //-----------------------------------------------------------------
  202. #pragma mark multipart form data parser delegate
  203. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  204. {
  205. /* in this sample, we are not interested in parts, other then file parts.
  206. * check content disposition to find out filename */
  207. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  208. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  209. if ((nil == filename) || [filename isEqualToString: @""]) {
  210. // it's either not a file part, or
  211. // an empty form sent. we won't handle it.
  212. return;
  213. }
  214. // create the path where to store the media temporarily
  215. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  216. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  217. NSFileManager *fileManager = [NSFileManager defaultManager];
  218. BOOL isDir = YES;
  219. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  220. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  221. }
  222. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  223. APLog(@"Saving file to %@", _filepath);
  224. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  225. APLog(@"Could not create directory at path: %@", _filepath);
  226. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  227. APLog(@"Could not create file at path: %@", _filepath);
  228. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  229. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  230. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  231. }
  232. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  233. {
  234. // here we just write the output from parser to the file.
  235. if (_storeFile) {
  236. @try {
  237. [_storeFile writeData:data];
  238. }
  239. @catch (NSException *exception) {
  240. APLog(@"File to write further data because storage is full.");
  241. [_storeFile closeFile];
  242. _storeFile = nil;
  243. /* don't block */
  244. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  245. }
  246. }
  247. }
  248. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  249. {
  250. // as the file part is over, we close the file.
  251. APLog(@"closing file");
  252. [_storeFile closeFile];
  253. _storeFile = nil;
  254. }
  255. - (BOOL)shouldDie
  256. {
  257. if (_filepath) {
  258. if (_filepath.length > 0)
  259. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
  260. }
  261. return [super shouldDie];
  262. }
  263. @end