VLCHTTPConnection.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /*****************************************************************************
  2. * VLCHTTPConnection.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Pierre Sagaspe <pierre.sagaspe # me.com>
  10. * Carola Nitz <caro # videolan.org>
  11. * Jean-Baptiste Kempf <jb # videolan.org>
  12. *
  13. * Refer to the COPYING file of the official project for license.
  14. *****************************************************************************/
  15. #import "VLCActivityManager.h"
  16. #import "VLCHTTPConnection.h"
  17. #import "MultipartFormDataParser.h"
  18. #import "HTTPMessage.h"
  19. #import "HTTPDataResponse.h"
  20. #import "HTTPFileResponse.h"
  21. #import "MultipartMessageHeaderField.h"
  22. #import "HTTPDynamicFileResponse.h"
  23. #import "NSString+SupportedMedia.h"
  24. #import "UIDevice+VLC.h"
  25. #import "VLCHTTPUploaderController.h"
  26. #if TARGET_OS_IOS
  27. #import "VLCThumbnailsCache.h"
  28. #endif
  29. @interface VLCHTTPConnection()
  30. {
  31. MultipartFormDataParser *_parser;
  32. NSFileHandle *_storeFile;
  33. NSString *_filepath;
  34. UInt64 _contentLength;
  35. UInt64 _receivedContent;
  36. #if TARGET_OS_TV
  37. BOOL _playbackStarted;
  38. #endif
  39. }
  40. @end
  41. @implementation VLCHTTPConnection
  42. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  43. {
  44. // Add support for POST
  45. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
  46. return YES;
  47. return [super supportsMethod:method atPath:path];
  48. }
  49. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  50. {
  51. // Inform HTTP server that we expect a body to accompany a POST request
  52. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  53. // here we need to make sure, boundary is set in header
  54. NSString* contentType = [request headerField:@"Content-Type"];
  55. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  56. if (NSNotFound == paramsSeparator)
  57. return NO;
  58. if (paramsSeparator >= contentType.length - 1)
  59. return NO;
  60. NSString* type = [contentType substringToIndex:paramsSeparator];
  61. if (![type isEqualToString:@"multipart/form-data"]) {
  62. // we expect multipart/form-data content type
  63. return NO;
  64. }
  65. // enumerate all params in content-type, and find boundary there
  66. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  67. NSUInteger count = params.count;
  68. for (NSUInteger i = 0; i < count; i++) {
  69. NSString *param = params[i];
  70. paramsSeparator = [param rangeOfString:@"="].location;
  71. if ((NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1)
  72. continue;
  73. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  74. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  75. if ([paramName isEqualToString: @"boundary"])
  76. // let's separate the boundary from content-type, to make it more handy to handle
  77. [request setHeaderField:@"boundary" value:paramValue];
  78. }
  79. // check if boundary specified
  80. if (nil == [request headerField:@"boundary"])
  81. return NO;
  82. return YES;
  83. }
  84. return [super expectsRequestBodyFromMethod:method atPath:path];
  85. }
  86. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  87. {
  88. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
  89. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  90. #if TARGET_OS_IOS
  91. if ([path hasPrefix:@"/download/"]) {
  92. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/download/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  93. HTTPFileResponse *fileResponse = [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
  94. fileResponse.contentType = @"application/octet-stream";
  95. return fileResponse;
  96. }
  97. if ([path hasPrefix:@"/thumbnail"]) {
  98. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/thumbnail/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  99. filePath = [filePath stringByReplacingOccurrencesOfString:@".png" withString:@""];
  100. NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
  101. if (moc) {
  102. NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
  103. if (psc) {
  104. NSManagedObject *mo = nil;
  105. @try {
  106. mo = [moc existingObjectWithID:[psc managedObjectIDForURIRepresentation:[NSURL URLWithString:filePath]] error:nil];
  107. }@catch (NSException *exeption) {
  108. // somebody gave us a malformed or stale URIRepresentation
  109. }
  110. NSData *theData;
  111. NSString *contentType;
  112. /* devices category 3 and faster include HW accelerated JPEG encoding
  113. * so we can make our transfers faster by using waaay smaller images */
  114. if ([[UIDevice currentDevice] speedCategory] < 3) {
  115. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForManagedObject:mo]);
  116. contentType = @"image/png";
  117. } else {
  118. theData = UIImageJPEGRepresentation([VLCThumbnailsCache thumbnailForManagedObject:mo], .9);
  119. contentType = @"image/jpg";
  120. }
  121. if (theData) {
  122. HTTPDataResponse *dataResponse = [[HTTPDataResponse alloc] initWithData:theData];
  123. dataResponse.contentType = contentType;
  124. return dataResponse;
  125. }
  126. }
  127. }
  128. }
  129. NSString *filePath = [self filePathForURI:path];
  130. NSString *documentRoot = [config documentRoot];
  131. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  132. BOOL shouldReturnLibVLCXML = [relativePath isEqualToString:@"/libMediaVLC.xml"];
  133. if ([relativePath isEqualToString:@"/index.html"] || shouldReturnLibVLCXML) {
  134. NSMutableArray *allMedia = [[NSMutableArray alloc] init];
  135. /* add all albums */
  136. NSArray *allAlbums = [MLAlbum allAlbums];
  137. for (MLAlbum *album in allAlbums) {
  138. if (album.name.length > 0 && album.tracks.count > 1)
  139. [allMedia addObject:album];
  140. }
  141. /* add all shows */
  142. NSArray *allShows = [MLShow allShows];
  143. for (MLShow *show in allShows) {
  144. if (show.name.length > 0 && show.episodes.count > 1)
  145. [allMedia addObject:show];
  146. }
  147. /* add all folders*/
  148. NSArray *allFolders = [MLLabel allLabels];
  149. for (MLLabel *folder in allFolders)
  150. [allMedia addObject:folder];
  151. /* add all remaining files */
  152. NSArray *allFiles = [MLFile allFiles];
  153. for (MLFile *file in allFiles) {
  154. if (file.labels.count > 0) continue;
  155. if (!file.isShowEpisode && !file.isAlbumTrack)
  156. [allMedia addObject:file];
  157. else if (file.isShowEpisode) {
  158. if (file.showEpisode.show.episodes.count < 2)
  159. [allMedia addObject:file];
  160. } else if (file.isAlbumTrack) {
  161. if (file.albumTrack.album.tracks.count < 2)
  162. [allMedia addObject:file];
  163. }
  164. }
  165. NSUInteger mediaCount = allMedia.count;
  166. NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
  167. NSMutableArray *mediaInXml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
  168. NSString *hostName = [[VLCHTTPUploaderController sharedInstance] hostname];
  169. NSString *duration;
  170. for (NSManagedObject *mo in allMedia) {
  171. if ([mo isKindOfClass:[MLFile class]]) {
  172. MLFile *file = (MLFile *)mo;
  173. duration = [[VLCTime timeWithNumber:file.duration] stringValue];
  174. [mediaInHtml addObject:[NSString stringWithFormat:
  175. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  176. <a href=\"download/%@\" class=\"inner\"> \
  177. <div class=\"down icon\"></div> \
  178. <div class=\"infos\"> \
  179. <span class=\"first-line\">%@</span> \
  180. <span class=\"second-line\">%@ - %0.2f MB</span> \
  181. </div> \
  182. </a> \
  183. </div>",
  184. file.objectID.URIRepresentation,
  185. [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  186. file.title,
  187. duration, (float)(file.fileSizeInBytes / 1e6)]];
  188. if (shouldReturnLibVLCXML) {
  189. NSString *pathSub = [self _checkIfSubtitleWasFound:file.path];
  190. if (pathSub)
  191. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  192. [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/thumbnail/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", file.title, hostName, file.objectID.URIRepresentation.absoluteString, duration, file.fileSizeInBytes, hostName, [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], pathSub]];
  193. }
  194. }
  195. else if ([mo isKindOfClass:[MLShow class]]) {
  196. MLShow *show = (MLShow *)mo;
  197. NSArray *episodes = [show sortedEpisodes];
  198. [mediaInHtml addObject:[NSString stringWithFormat:
  199. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  200. <a href=\"#\" class=\"inner folder\"> \
  201. <div class=\"open icon\"></div> \
  202. <div class=\"infos\"> \
  203. <span class=\"first-line\">%@</span> \
  204. <span class=\"second-line\">%lu items</span> \
  205. </div> \
  206. </a> \
  207. <div class=\"content\">",
  208. mo.objectID.URIRepresentation,
  209. show.name,
  210. (unsigned long)[episodes count]]];
  211. for (MLShowEpisode *showEp in episodes) {
  212. MLFile *anyFileFromEpisode = (MLFile *)[[showEp files] anyObject];
  213. duration = [[VLCTime timeWithNumber:[anyFileFromEpisode duration]] stringValue];
  214. [mediaInHtml addObject:[NSString stringWithFormat:
  215. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  216. <a href=\"download/%@\" class=\"inner\"> \
  217. <div class=\"down icon\"></div> \
  218. <div class=\"infos\"> \
  219. <span class=\"first-line\">S%@E%@ - %@</span> \
  220. <span class=\"second-line\">%@ - %0.2f MB</span> \
  221. </div> \
  222. </a> \
  223. </div>",
  224. showEp.objectID.URIRepresentation,
  225. [anyFileFromEpisode.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  226. showEp.seasonNumber,
  227. showEp.episodeNumber,
  228. showEp.name,
  229. duration, (float)([anyFileFromEpisode fileSizeInBytes] / 1e6)]];
  230. if (shouldReturnLibVLCXML) {
  231. NSString *pathSub = [self _checkIfSubtitleWasFound:[anyFileFromEpisode path]];
  232. if (![pathSub isEqualToString:@""])
  233. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  234. [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@ - S%@E%@\" thumb=\"http://%@/thumbnail/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", show.name, showEp.seasonNumber, showEp.episodeNumber, hostName, showEp.objectID.URIRepresentation, duration, [anyFileFromEpisode fileSizeInBytes], hostName, [anyFileFromEpisode.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], pathSub]];
  235. }
  236. }
  237. [mediaInHtml addObject:@"</div></div>"];
  238. } else if ([mo isKindOfClass:[MLLabel class]]) {
  239. MLLabel *label = (MLLabel *)mo;
  240. NSArray *folderItems = [label sortedFolderItems];
  241. [mediaInHtml addObject:[NSString stringWithFormat:
  242. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  243. <a href=\"#\" class=\"inner folder\"> \
  244. <div class=\"open icon\"></div> \
  245. <div class=\"infos\"> \
  246. <span class=\"first-line\">%@</span> \
  247. <span class=\"second-line\">%lu items</span> \
  248. </div> \
  249. </a> \
  250. <div class=\"content\">",
  251. label.objectID.URIRepresentation,
  252. label.name,
  253. (unsigned long)folderItems.count]];
  254. for (MLFile *file in folderItems) {
  255. duration = [[VLCTime timeWithNumber:[file duration]] stringValue];
  256. [mediaInHtml addObject:[NSString stringWithFormat:
  257. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  258. <a href=\"download/%@\" class=\"inner\"> \
  259. <div class=\"down icon\"></div> \
  260. <div class=\"infos\"> \
  261. <span class=\"first-line\">%@</span> \
  262. <span class=\"second-line\">%@ - %0.2f MB</span> \
  263. </div> \
  264. </a> \
  265. </div>",
  266. file.objectID.URIRepresentation,
  267. [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  268. file.title,
  269. duration, (float)(file.fileSizeInBytes / 1e6)]];
  270. if (shouldReturnLibVLCXML) {
  271. NSString *pathSub = [self _checkIfSubtitleWasFound:file.path];
  272. if (pathSub)
  273. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  274. [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/thumbnail/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", file.title, hostName, file.objectID.URIRepresentation, duration, file.fileSizeInBytes, hostName, [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], pathSub]];
  275. }
  276. }
  277. [mediaInHtml addObject:@"</div></div>"];
  278. } else if ([mo isKindOfClass:[MLAlbum class]]) {
  279. MLAlbum *album = (MLAlbum *)mo;
  280. NSArray *albumTracks = [album sortedTracks];
  281. [mediaInHtml addObject:[NSString stringWithFormat:
  282. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  283. <a href=\"#\" class=\"inner folder\"> \
  284. <div class=\"open icon\"></div> \
  285. <div class=\"infos\"> \
  286. <span class=\"first-line\">%@</span> \
  287. <span class=\"second-line\">%lu items</span> \
  288. </div> \
  289. </a> \
  290. <div class=\"content\">",
  291. album.objectID.URIRepresentation,
  292. album.name,
  293. (unsigned long)albumTracks.count]];
  294. for (MLAlbumTrack *track in albumTracks) {
  295. MLFile *anyFileFromTrack = [track anyFileFromTrack];
  296. duration = [[VLCTime timeWithNumber:[anyFileFromTrack duration]] stringValue];
  297. [mediaInHtml addObject:[NSString stringWithFormat:
  298. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  299. <a href=\"download/%@\" class=\"inner\"> \
  300. <div class=\"down icon\"></div> \
  301. <div class=\"infos\"> \
  302. <span class=\"first-line\">%@</span> \
  303. <span class=\"second-line\">%@ - %0.2f MB</span> \
  304. </div> \
  305. </a> \
  306. </div>",
  307. track.objectID.URIRepresentation,
  308. [anyFileFromTrack.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  309. track.title,
  310. duration, (float)([anyFileFromTrack fileSizeInBytes] / 1e6)]];
  311. if (shouldReturnLibVLCXML)
  312. [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/thumbnail/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"\"/>", track.title, hostName, track.objectID.URIRepresentation, duration, [anyFileFromTrack fileSizeInBytes], hostName, [anyFileFromTrack.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
  313. }
  314. [mediaInHtml addObject:@"</div></div>"];
  315. }
  316. }
  317. UIDevice *currentDevice = [UIDevice currentDevice];
  318. NSString *deviceModel = [currentDevice model];
  319. NSDictionary *replacementDict;
  320. HTTPDynamicFileResponse *fileResponse;
  321. if (shouldReturnLibVLCXML) {
  322. replacementDict = @{@"FILES" : [mediaInXml componentsJoinedByString:@" "],
  323. @"NB_FILE" : [NSString stringWithFormat:@"%li", (unsigned long)mediaInXml.count],
  324. @"LIB_TITLE" : [currentDevice name]};
  325. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  326. forConnection:self
  327. separator:@"%%"
  328. replacementDictionary:replacementDict];
  329. fileResponse.contentType = @"application/xml";
  330. } else {
  331. replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
  332. @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
  333. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  334. @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil), deviceModel],
  335. @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
  336. @"WEBINTF_DOWNLOADFILES_LONG" : [NSString stringWithFormat: NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil), deviceModel]};
  337. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  338. forConnection:self
  339. separator:@"%%"
  340. replacementDictionary:replacementDict];
  341. fileResponse.contentType = @"text/html";
  342. }
  343. #else
  344. UIDevice *currentDevice = [UIDevice currentDevice];
  345. NSString *deviceModel = [currentDevice model];
  346. NSString *filePath = [self filePathForURI:path];
  347. NSString *documentRoot = [config documentRoot];
  348. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  349. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE_ATV", nil),
  350. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  351. @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG_ATV", nil), deviceModel]};
  352. HTTPDynamicFileResponse *fileResponse;
  353. if ([relativePath isEqualToString:@"/index.html"]) {
  354. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  355. forConnection:self
  356. separator:@"%%"
  357. replacementDictionary:replacementDict];
  358. fileResponse.contentType = @"text/html";
  359. #endif
  360. return fileResponse;
  361. } else if ([relativePath isEqualToString:@"/style.css"]) {
  362. #if TARGET_OS_IOS
  363. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
  364. #else
  365. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE_ATV", nil)};
  366. #endif
  367. HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  368. forConnection:self
  369. separator:@"%%"
  370. replacementDictionary:replacementDict];
  371. fileResponse.contentType = @"text/css";
  372. return fileResponse;
  373. }
  374. return [super httpResponseForMethod:method URI:path];
  375. }
  376. - (void)prepareForBodyWithSize:(UInt64)contentLength
  377. {
  378. // set up mime parser
  379. NSString* boundary = [request headerField:@"boundary"];
  380. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  381. _parser.delegate = self;
  382. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  383. _contentLength = contentLength;
  384. }
  385. - (void)processBodyData:(NSData *)postDataChunk
  386. {
  387. /* append data to the parser. It will invoke callbacks to let us handle
  388. * parsed data. */
  389. [_parser appendData:postDataChunk];
  390. _receivedContent += postDataChunk.length;
  391. long long percentage = ((_receivedContent * 100) / _contentLength);
  392. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, percentage);
  393. #if TARGET_OS_TV
  394. if (!_playbackStarted) {
  395. if (percentage >= 10) {
  396. _playbackStarted = YES;
  397. APLog(@"Starting playback of %@", _filepath);
  398. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  399. [vpc playURL:[NSURL fileURLWithPath:_filepath] successCallback:nil errorCallback:nil];
  400. VLCFullscreenMovieTVViewController *moviewVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  401. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:moviewVC
  402. animated:YES
  403. completion:nil];
  404. }
  405. }
  406. #endif
  407. }
  408. //-----------------------------------------------------------------
  409. #pragma mark multipart form data parser delegate
  410. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  411. {
  412. /* in this sample, we are not interested in parts, other then file parts.
  413. * check content disposition to find out filename */
  414. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  415. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  416. if ((nil == filename) || [filename isEqualToString: @""]) {
  417. // it's either not a file part, or
  418. // an empty form sent. we won't handle it.
  419. return;
  420. }
  421. // create the path where to store the media temporarily
  422. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  423. NSString *uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  424. NSFileManager *fileManager = [NSFileManager defaultManager];
  425. BOOL isDir = YES;
  426. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir])
  427. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  428. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  429. NSNumber *freeSpace = [[UIDevice currentDevice] freeDiskspace];
  430. if (_contentLength >= freeSpace.longLongValue) {
  431. /* avoid deadlock since we are on a background thread */
  432. [self performSelectorOnMainThread:@selector(notifyUserAboutEndOfFreeStorage:) withObject:filename waitUntilDone:NO];
  433. [self handleResourceNotFound];
  434. [self stop];
  435. return;
  436. }
  437. APLog(@"Saving file to %@", _filepath);
  438. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  439. APLog(@"Could not create directory at path: %@", _filepath);
  440. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  441. APLog(@"Could not create file at path: %@", _filepath);
  442. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  443. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  444. [activityManager networkActivityStarted];
  445. [activityManager disableIdleTimer];
  446. }
  447. - (void)notifyUserAboutEndOfFreeStorage:(NSString *)filename
  448. {
  449. #if TARGET_OS_IOS
  450. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  451. message:[NSString stringWithFormat:
  452. NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  453. filename,
  454. [[UIDevice currentDevice] model]]
  455. delegate:self
  456. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  457. otherButtonTitles:nil];
  458. [alert show];
  459. #else
  460. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  461. message:[NSString stringWithFormat:
  462. NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  463. filename,
  464. [[UIDevice currentDevice] model]]
  465. preferredStyle:UIAlertControllerStyleAlert];
  466. [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  467. style:UIAlertActionStyleCancel
  468. handler:nil]];
  469. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  470. #endif
  471. }
  472. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  473. {
  474. // here we just write the output from parser to the file.
  475. if (_storeFile) {
  476. @try {
  477. [_storeFile writeData:data];
  478. }
  479. @catch (NSException *exception) {
  480. APLog(@"File to write further data because storage is full.");
  481. [_storeFile closeFile];
  482. _storeFile = nil;
  483. /* don't block */
  484. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  485. }
  486. }
  487. }
  488. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  489. {
  490. // as the file part is over, we close the file.
  491. APLog(@"closing file");
  492. [_storeFile closeFile];
  493. _storeFile = nil;
  494. }
  495. - (BOOL)shouldDie
  496. {
  497. if (_filepath) {
  498. if (_filepath.length > 0)
  499. [[VLCHTTPUploaderController sharedInstance] moveFileFrom:_filepath];
  500. }
  501. return [super shouldDie];
  502. }
  503. #pragma mark subtitle
  504. - (NSMutableArray *)_listOfSubtitles
  505. {
  506. NSMutableArray *listOfSubtitles = [[NSMutableArray alloc] init];
  507. NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  508. NSArray *allFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
  509. NSString *filePath;
  510. NSUInteger count = allFiles.count;
  511. for (NSUInteger i = 0; i < count; i++) {
  512. filePath = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, allFiles[i]] stringByReplacingOccurrencesOfString:@"file://"withString:@""];
  513. if ([filePath isSupportedSubtitleFormat])
  514. [listOfSubtitles addObject:filePath];
  515. }
  516. return listOfSubtitles;
  517. }
  518. - (NSString *)_checkIfSubtitleWasFound:(NSString *)filePath
  519. {
  520. NSString *subtitlePath;
  521. NSString *fileSub;
  522. NSString *currentPath;
  523. NSString *fileName = [[filePath lastPathComponent] stringByDeletingPathExtension];
  524. if (fileName == nil)
  525. return nil;
  526. NSMutableArray *listOfSubtitles = [self _listOfSubtitles];
  527. NSUInteger count = listOfSubtitles.count;
  528. for (NSUInteger i = 0; i < count; i++) {
  529. currentPath = listOfSubtitles[i];
  530. fileSub = [NSString stringWithFormat:@"%@", currentPath];
  531. if ([fileSub rangeOfString:fileName].location != NSNotFound)
  532. subtitlePath = currentPath;
  533. }
  534. return subtitlePath;
  535. }
  536. @end