VLCHTTPConnection.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. NSString *duration;
  151. for (NSManagedObject *mo in allMedia) {
  152. if ([mo isKindOfClass:[MLFile class]]) {
  153. duration = [[VLCTime timeWithNumber:[(MLFile *)mo duration]] stringValue];
  154. [mediaInHtml addObject:[NSString stringWithFormat:
  155. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  156. <a href=\"download/%@\" class=\"inner\"> \
  157. <div class=\"down icon\"></div> \
  158. <div class=\"infos\"> \
  159. <span class=\"first-line\">%@</span> \
  160. <span class=\"second-line\">%@ - %0.2f MB</span> \
  161. </div> \
  162. </a> \
  163. </div>",
  164. mo.objectID.URIRepresentation,
  165. [[(MLFile *)mo url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
  166. [(MLFile *)mo title],
  167. duration, (float)([(MLFile *)mo fileSizeInBytes] / 1e6)]];
  168. }
  169. else if ([mo isKindOfClass:[MLShow class]]) {
  170. NSArray *episodes = [(MLShow *)mo sortedEpisodes];
  171. [mediaInHtml addObject:[NSString stringWithFormat:
  172. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  173. <a href=\"#\" class=\"inner\"> \
  174. <div class=\"open icon\"></div> \
  175. <div class=\"infos\"> \
  176. <span class=\"first-line\">%@</span> \
  177. <span class=\"second-line\">%d items</span> \
  178. </div> \
  179. </a> \
  180. <div class=\"content\">",
  181. mo.objectID.URIRepresentation,
  182. [(MLShow *)mo name],
  183. [episodes count]]];
  184. for (MLShowEpisode *showEp in episodes) {
  185. duration = [[VLCTime timeWithNumber:[(MLFile *)[[showEp files] anyObject] duration]] stringValue];
  186. [mediaInHtml addObject:[NSString stringWithFormat:
  187. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  188. <a href=\"download/%@\" class=\"inner\"> \
  189. <div class=\"down icon\"></div> \
  190. <div class=\"infos\"> \
  191. <span class=\"first-line\">S%@E%@ - %@</span> \
  192. <span class=\"second-line\">%@ - %0.2f MB</span> \
  193. </div> \
  194. </a> \
  195. </div>",
  196. showEp.objectID.URIRepresentation,
  197. [[(MLFile *)[[showEp files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
  198. showEp.seasonNumber,
  199. showEp.episodeNumber,
  200. showEp.name,
  201. duration, (float)([(MLFile *)[[showEp files] anyObject] fileSizeInBytes] / 1e6)]];
  202. }
  203. [mediaInHtml addObject:@"</div></div>"];
  204. } else if ([mo isKindOfClass:[MLLabel class]]) {
  205. NSArray *folderItems = [(MLLabel *)mo sortedFolderItems];
  206. [mediaInHtml addObject:[NSString stringWithFormat:
  207. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  208. <a href=\"#\" class=\"inner\"> \
  209. <div class=\"open icon\"></div> \
  210. <div class=\"infos\"> \
  211. <span class=\"first-line\">%@</span> \
  212. <span class=\"second-line\">%d items</span> \
  213. </div> \
  214. </a> \
  215. <div class=\"content\">",
  216. mo.objectID.URIRepresentation,
  217. [(MLLabel *)mo name],
  218. [folderItems count]]];
  219. for (MLFile *file in folderItems) {
  220. duration = [[VLCTime timeWithNumber:[file duration]] stringValue];
  221. [mediaInHtml addObject:[NSString stringWithFormat:
  222. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  223. <a href=\"download/%@\" class=\"inner\"> \
  224. <div class=\"down icon\"></div> \
  225. <div class=\"infos\"> \
  226. <span class=\"first-line\">%@</span> \
  227. <span class=\"second-line\">%@ - %0.2f MB</span> \
  228. </div> \
  229. </a> \
  230. </div>",
  231. file.objectID.URIRepresentation,
  232. [[file url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
  233. file.title,
  234. duration, (float)([file fileSizeInBytes] / 1e6)]];
  235. }
  236. [mediaInHtml addObject:@"</div></div>"];
  237. } else if ([mo isKindOfClass:[MLAlbum class]]) {
  238. NSArray *albumTracks = [(MLAlbum *)mo sortedTracks];
  239. [mediaInHtml addObject:[NSString stringWithFormat:
  240. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  241. <a href=\"#\" class=\"inner\"> \
  242. <div class=\"open icon\"></div> \
  243. <div class=\"infos\"> \
  244. <span class=\"first-line\">%@</span> \
  245. <span class=\"second-line\">%d items</span> \
  246. </div> \
  247. </a> \
  248. <div class=\"content\">",
  249. mo.objectID.URIRepresentation,
  250. [(MLAlbum *)mo name],
  251. [albumTracks count]]];
  252. for (MLAlbumTrack *track in albumTracks) {
  253. duration = [[VLCTime timeWithNumber:[(MLFile *)[[track files] anyObject] duration]] stringValue];
  254. [mediaInHtml addObject:[NSString stringWithFormat:
  255. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  256. <a href=\"download/%@\" class=\"inner\"> \
  257. <div class=\"down icon\"></div> \
  258. <div class=\"infos\"> \
  259. <span class=\"first-line\">%@</span> \
  260. <span class=\"second-line\">%@ - %0.2f MB</span> \
  261. </div> \
  262. </a> \
  263. </div>",
  264. track.objectID.URIRepresentation,
  265. [[(MLFile *)[[track files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
  266. track.title,
  267. duration, (float)([(MLFile *)[[track files] anyObject] fileSizeInBytes] / 1e6)]];
  268. }
  269. [mediaInHtml addObject:@"</div></div>"];
  270. }
  271. }
  272. NSString *deviceModel = [[UIDevice currentDevice] model];
  273. NSDictionary *replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
  274. @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
  275. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  276. @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil), deviceModel],
  277. @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
  278. @"WEBINTF_DOWNLOADFILES_LONG" : [NSString stringWithFormat: NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil), deviceModel]};
  279. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  280. forConnection:self
  281. separator:@"%%"
  282. replacementDictionary:replacementDict];
  283. } else if ([relativePath isEqualToString:@"/style.css"]) {
  284. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
  285. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  286. forConnection:self
  287. separator:@"%%"
  288. replacementDictionary:replacementDict];
  289. }
  290. return [super httpResponseForMethod:method URI:path];
  291. }
  292. - (void)prepareForBodyWithSize:(UInt64)contentLength
  293. {
  294. // set up mime parser
  295. NSString* boundary = [request headerField:@"boundary"];
  296. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  297. _parser.delegate = self;
  298. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  299. _contentLength = contentLength;
  300. }
  301. - (void)processBodyData:(NSData *)postDataChunk
  302. {
  303. /* append data to the parser. It will invoke callbacks to let us handle
  304. * parsed data. */
  305. [_parser appendData:postDataChunk];
  306. _receivedContent += postDataChunk.length;
  307. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  308. }
  309. //-----------------------------------------------------------------
  310. #pragma mark multipart form data parser delegate
  311. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  312. {
  313. /* in this sample, we are not interested in parts, other then file parts.
  314. * check content disposition to find out filename */
  315. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  316. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  317. if ((nil == filename) || [filename isEqualToString: @""]) {
  318. // it's either not a file part, or
  319. // an empty form sent. we won't handle it.
  320. return;
  321. }
  322. // create the path where to store the media temporarily
  323. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  324. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  325. NSFileManager *fileManager = [NSFileManager defaultManager];
  326. BOOL isDir = YES;
  327. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  328. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  329. }
  330. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  331. APLog(@"Saving file to %@", _filepath);
  332. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  333. APLog(@"Could not create directory at path: %@", _filepath);
  334. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  335. APLog(@"Could not create file at path: %@", _filepath);
  336. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  337. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  338. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  339. }
  340. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  341. {
  342. // here we just write the output from parser to the file.
  343. if (_storeFile) {
  344. @try {
  345. [_storeFile writeData:data];
  346. }
  347. @catch (NSException *exception) {
  348. APLog(@"File to write further data because storage is full.");
  349. [_storeFile closeFile];
  350. _storeFile = nil;
  351. /* don't block */
  352. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  353. }
  354. }
  355. }
  356. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  357. {
  358. // as the file part is over, we close the file.
  359. APLog(@"closing file");
  360. [_storeFile closeFile];
  361. _storeFile = nil;
  362. }
  363. - (BOOL)shouldDie
  364. {
  365. if (_filepath) {
  366. if (_filepath.length > 0)
  367. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
  368. }
  369. return [super shouldDie];
  370. }
  371. @end