VLCHTTPConnection.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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=\"No Image\" /> - <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:@"<div id=\"menu\"><ul><li><img src=\"thumbnail/%@.png\" alt=\"No Image\" /> - %@<ul>", mo.objectID.URIRepresentation, [(MLShow *)mo name]]];
  156. for (MLShowEpisode *showEp in episodes)
  157. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><img src=\"thumbnail/%@.png\" alt=\"No Image\" /> - <a href=\"download/%@\" download>Season %@ Episode %@ - %@</a></lu><br />", showEp.objectID.URIRepresentation, [[(MLFile *)[[showEp files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], showEp.seasonNumber, showEp.episodeNumber, showEp.name]];
  158. [mediaInHtml addObject:@"</ul></li></ul></div>"];
  159. } else if ([mo isKindOfClass:[MLLabel class]]) {
  160. NSArray *folderItems = [(MLLabel *)mo sortedFolderItems];
  161. [mediaInHtml addObject:[NSString stringWithFormat:@"<div id=\"menu\"><ul><li><img src=\"thumbnail/%@.png\" alt=\"No Image\" /> - %@<ul>", mo.objectID.URIRepresentation, [(MLLabel *)mo name]]];
  162. for (MLFile *file in folderItems)
  163. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><img src=\"thumbnail/%@.png\" alt=\"No Image\" /> - <a href=\"download/%@\" download>%@</a></lu><br />", file.objectID.URIRepresentation, [[file url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], file.title]];
  164. [mediaInHtml addObject:@"</ul></li></ul></div>"];
  165. } else if ([mo isKindOfClass:[MLAlbum class]]) {
  166. NSArray *albumTracks = [(MLAlbum *)mo sortedTracks];
  167. [mediaInHtml addObject:[NSString stringWithFormat:@"<div id=\"menu\"><ul><li><img src=\"thumbnail/%@.png\" alt=\"No Image\" /> - %@<ul>", mo.objectID.URIRepresentation, [(MLAlbum *)mo name]]];
  168. for (MLAlbumTrack *track in albumTracks)
  169. [mediaInHtml addObject:[NSString stringWithFormat:@"<lu><img src=\"thumbnail/%@.png\" alt=\"No Image\" /> - <a href=\"download/%@\" download>%@</a></lu><br />", track.objectID.URIRepresentation, [[(MLFile *)[[track files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], track.title]];
  170. [mediaInHtml addObject:@"</ul></li></ul></div>"];
  171. }
  172. }
  173. NSDictionary *replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
  174. @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
  175. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  176. @"WEBINTF_DROPFILES_LONG" : NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil),
  177. @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
  178. @"WEBINTF_DOWNLOADFILES_LONG" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil)};
  179. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  180. forConnection:self
  181. separator:@"%%"
  182. replacementDictionary:replacementDict];
  183. } else if ([relativePath isEqualToString:@"/style.css"]) {
  184. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
  185. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  186. forConnection:self
  187. separator:@"%%"
  188. replacementDictionary:replacementDict];
  189. }
  190. return [super httpResponseForMethod:method URI:path];
  191. }
  192. - (void)prepareForBodyWithSize:(UInt64)contentLength
  193. {
  194. // set up mime parser
  195. NSString* boundary = [request headerField:@"boundary"];
  196. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  197. _parser.delegate = self;
  198. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  199. _contentLength = contentLength;
  200. }
  201. - (void)processBodyData:(NSData *)postDataChunk
  202. {
  203. /* append data to the parser. It will invoke callbacks to let us handle
  204. * parsed data. */
  205. [_parser appendData:postDataChunk];
  206. _receivedContent += postDataChunk.length;
  207. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  208. }
  209. //-----------------------------------------------------------------
  210. #pragma mark multipart form data parser delegate
  211. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  212. {
  213. /* in this sample, we are not interested in parts, other then file parts.
  214. * check content disposition to find out filename */
  215. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  216. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  217. if ((nil == filename) || [filename isEqualToString: @""]) {
  218. // it's either not a file part, or
  219. // an empty form sent. we won't handle it.
  220. return;
  221. }
  222. // create the path where to store the media temporarily
  223. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  224. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  225. NSFileManager *fileManager = [NSFileManager defaultManager];
  226. BOOL isDir = YES;
  227. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  228. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  229. }
  230. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  231. APLog(@"Saving file to %@", _filepath);
  232. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  233. APLog(@"Could not create directory at path: %@", _filepath);
  234. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  235. APLog(@"Could not create file at path: %@", _filepath);
  236. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  237. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  238. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  239. }
  240. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  241. {
  242. // here we just write the output from parser to the file.
  243. if (_storeFile) {
  244. @try {
  245. [_storeFile writeData:data];
  246. }
  247. @catch (NSException *exception) {
  248. APLog(@"File to write further data because storage is full.");
  249. [_storeFile closeFile];
  250. _storeFile = nil;
  251. /* don't block */
  252. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  253. }
  254. }
  255. }
  256. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  257. {
  258. // as the file part is over, we close the file.
  259. APLog(@"closing file");
  260. [_storeFile closeFile];
  261. _storeFile = nil;
  262. }
  263. - (BOOL)shouldDie
  264. {
  265. if (_filepath) {
  266. if (_filepath.length > 0)
  267. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
  268. }
  269. return [super shouldDie];
  270. }
  271. @end