VLCHTTPConnection.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. * 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. #import "NSString+SupportedMedia.h"
  25. #import "UIDevice+VLC.h"
  26. @interface VLCHTTPConnection()
  27. {
  28. MultipartFormDataParser *_parser;
  29. NSFileHandle *_storeFile;
  30. NSString *_filepath;
  31. UInt64 _contentLength;
  32. UInt64 _receivedContent;
  33. }
  34. @property (nonatomic) VLCHTTPUploaderController *uploadController;
  35. @end
  36. @implementation VLCHTTPConnection
  37. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  38. {
  39. // Add support for POST
  40. if ([method isEqualToString:@"POST"]) {
  41. if ([path isEqualToString:@"/upload.json"])
  42. return YES;
  43. }
  44. return [super supportsMethod:method atPath:path];
  45. }
  46. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  47. {
  48. // Inform HTTP server that we expect a body to accompany a POST request
  49. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  50. // here we need to make sure, boundary is set in header
  51. NSString* contentType = [request headerField:@"Content-Type"];
  52. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  53. if (NSNotFound == paramsSeparator)
  54. return NO;
  55. if (paramsSeparator >= contentType.length - 1)
  56. return NO;
  57. NSString* type = [contentType substringToIndex:paramsSeparator];
  58. if (![type isEqualToString:@"multipart/form-data"]) {
  59. // we expect multipart/form-data content type
  60. return NO;
  61. }
  62. // enumerate all params in content-type, and find boundary there
  63. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  64. for (NSString* param in params) {
  65. paramsSeparator = [param rangeOfString:@"="].location;
  66. if ((NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1)
  67. continue;
  68. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  69. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  70. if ([paramName isEqualToString: @"boundary"])
  71. // let's separate the boundary from content-type, to make it more handy to handle
  72. [request setHeaderField:@"boundary" value:paramValue];
  73. }
  74. // check if boundary specified
  75. if (nil == [request headerField:@"boundary"])
  76. return NO;
  77. return YES;
  78. }
  79. return [super expectsRequestBodyFromMethod:method atPath:path];
  80. }
  81. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  82. {
  83. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  84. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  85. }
  86. if ([path hasPrefix:@"/download/"]) {
  87. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/download/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  88. HTTPFileResponse *fileResponse = [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
  89. fileResponse.contentType = @"application/octet-stream";
  90. return fileResponse;
  91. }
  92. if ([path hasPrefix:@"/thumbnail"]) {
  93. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/thumbnail/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  94. filePath = [filePath stringByReplacingOccurrencesOfString:@".png" withString:@""];
  95. NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
  96. if (moc) {
  97. NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
  98. if (psc) {
  99. NSManagedObject *mo = [moc existingObjectWithID:[psc managedObjectIDForURIRepresentation:[NSURL URLWithString:filePath]] error:nil];
  100. NSData *theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForManagedObject:mo]);
  101. if (theData) {
  102. HTTPDataResponse *dataResponse = [[HTTPDataResponse alloc] initWithData:theData];
  103. dataResponse.contentType = @"image/png";
  104. return dataResponse;
  105. }
  106. }
  107. }
  108. }
  109. NSString *filePath = [self filePathForURI:path];
  110. NSString *documentRoot = [config documentRoot];
  111. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  112. BOOL shouldReturnLibVLCXML = [relativePath isEqualToString:@"/libMediaVLC.xml"];
  113. if ([relativePath isEqualToString:@"/index.html"] || shouldReturnLibVLCXML) {
  114. NSMutableArray *allMedia = [[NSMutableArray alloc] init];
  115. /* add all albums */
  116. NSArray *allAlbums = [MLAlbum allAlbums];
  117. for (MLAlbum *album in allAlbums) {
  118. if (album.name.length > 0 && album.tracks.count > 1)
  119. [allMedia addObject:album];
  120. }
  121. /* add all shows */
  122. NSArray *allShows = [MLShow allShows];
  123. for (MLShow *show in allShows) {
  124. if (show.name.length > 0 && show.episodes.count > 1)
  125. [allMedia addObject:show];
  126. }
  127. /* add all folders*/
  128. NSArray *allFolders = [MLLabel allLabels];
  129. for (MLLabel *folder in allFolders)
  130. [allMedia addObject:folder];
  131. /* add all remaining files */
  132. NSArray *allFiles = [MLFile allFiles];
  133. for (MLFile *file in allFiles) {
  134. if (file.labels.count > 0) continue;
  135. if (!file.isShowEpisode && !file.isAlbumTrack)
  136. [allMedia addObject:file];
  137. else if (file.isShowEpisode) {
  138. if (file.showEpisode.show.episodes.count < 2)
  139. [allMedia addObject:file];
  140. } else if (file.isAlbumTrack) {
  141. if (file.albumTrack.album.tracks.count < 2)
  142. [allMedia addObject:file];
  143. }
  144. }
  145. NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:allMedia.count];
  146. NSMutableArray *mediaInXml = [[NSMutableArray alloc] initWithCapacity:allMedia.count];
  147. self.uploadController = [[VLCHTTPUploaderController alloc] init];
  148. NSString *hostName = [self.uploadController hostname];
  149. NSString *pathLibrary = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  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. if (shouldReturnLibVLCXML) {
  169. NSString *pathSub = [self _checkSubtitleFound:[(MLFile *)mo url]];
  170. if (![pathSub isEqualToString:@""])
  171. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  172. [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/download/%@/Thumbnails/File/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", [(MLFile *)mo title], hostName, pathLibrary, [[NSString stringWithFormat:@"%@", mo.objectID.URIRepresentation] lastPathComponent], duration, [(MLFile *)mo fileSizeInBytes], hostName, [[(MLFile *)mo url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], pathSub]];
  173. }
  174. }
  175. else if ([mo isKindOfClass:[MLShow class]]) {
  176. NSArray *episodes = [(MLShow *)mo sortedEpisodes];
  177. [mediaInHtml addObject:[NSString stringWithFormat:
  178. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  179. <a href=\"#\" class=\"inner folder\"> \
  180. <div class=\"open icon\"></div> \
  181. <div class=\"infos\"> \
  182. <span class=\"first-line\">%@</span> \
  183. <span class=\"second-line\">%lu items</span> \
  184. </div> \
  185. </a> \
  186. <div class=\"content\">",
  187. mo.objectID.URIRepresentation,
  188. [(MLShow *)mo name],
  189. (unsigned long)[episodes count]]];
  190. for (MLShowEpisode *showEp in episodes) {
  191. duration = [[VLCTime timeWithNumber:[(MLFile *)[[showEp files] anyObject] duration]] stringValue];
  192. [mediaInHtml addObject:[NSString stringWithFormat:
  193. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  194. <a href=\"download/%@\" class=\"inner\"> \
  195. <div class=\"down icon\"></div> \
  196. <div class=\"infos\"> \
  197. <span class=\"first-line\">S%@E%@ - %@</span> \
  198. <span class=\"second-line\">%@ - %0.2f MB</span> \
  199. </div> \
  200. </a> \
  201. </div>",
  202. showEp.objectID.URIRepresentation,
  203. [[(MLFile *)[[showEp files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
  204. showEp.seasonNumber,
  205. showEp.episodeNumber,
  206. showEp.name,
  207. duration, (float)([(MLFile *)[[showEp files] anyObject] fileSizeInBytes] / 1e6)]];
  208. if (shouldReturnLibVLCXML) {
  209. NSString *pathSub = [self _checkSubtitleFound:[(MLFile *)[[showEp files] anyObject] url]];
  210. if (![pathSub isEqualToString:@""])
  211. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  212. [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@ - S%@E%@\" thumb=\"http://%@/download/%@/Thumbnails/File/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", [(MLShow *)mo name], showEp.seasonNumber, showEp.episodeNumber, hostName, pathLibrary, [[NSString stringWithFormat:@"%@", showEp.objectID.URIRepresentation] lastPathComponent], duration, [(MLFile *)[[showEp files] anyObject] fileSizeInBytes], hostName, [[(MLFile *)[[showEp files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], pathSub]];
  213. }
  214. }
  215. [mediaInHtml addObject:@"</div></div>"];
  216. } else if ([mo isKindOfClass:[MLLabel class]]) {
  217. NSArray *folderItems = [(MLLabel *)mo sortedFolderItems];
  218. [mediaInHtml addObject:[NSString stringWithFormat:
  219. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  220. <a href=\"#\" class=\"inner folder\"> \
  221. <div class=\"open icon\"></div> \
  222. <div class=\"infos\"> \
  223. <span class=\"first-line\">%@</span> \
  224. <span class=\"second-line\">%lu items</span> \
  225. </div> \
  226. </a> \
  227. <div class=\"content\">",
  228. mo.objectID.URIRepresentation,
  229. [(MLLabel *)mo name],
  230. (unsigned long)[folderItems count]]];
  231. for (MLFile *file in folderItems) {
  232. duration = [[VLCTime timeWithNumber:[file duration]] stringValue];
  233. [mediaInHtml addObject:[NSString stringWithFormat:
  234. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  235. <a href=\"download/%@\" class=\"inner\"> \
  236. <div class=\"down icon\"></div> \
  237. <div class=\"infos\"> \
  238. <span class=\"first-line\">%@</span> \
  239. <span class=\"second-line\">%@ - %0.2f MB</span> \
  240. </div> \
  241. </a> \
  242. </div>",
  243. file.objectID.URIRepresentation,
  244. [[file url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
  245. file.title,
  246. duration, (float)([file fileSizeInBytes] / 1e6)]];
  247. if (shouldReturnLibVLCXML) {
  248. NSString *pathSub = [self _checkSubtitleFound:[file url]];
  249. if (![pathSub isEqualToString:@""])
  250. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  251. [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/download/%@/Thumbnails/File/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", file.title, hostName, pathLibrary, [[NSString stringWithFormat:@"%@", file.objectID.URIRepresentation] lastPathComponent], duration, [file fileSizeInBytes], hostName, [[file url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], pathSub]];
  252. }
  253. }
  254. [mediaInHtml addObject:@"</div></div>"];
  255. } else if ([mo isKindOfClass:[MLAlbum class]]) {
  256. NSArray *albumTracks = [(MLAlbum *)mo sortedTracks];
  257. [mediaInHtml addObject:[NSString stringWithFormat:
  258. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  259. <a href=\"#\" class=\"inner folder\"> \
  260. <div class=\"open icon\"></div> \
  261. <div class=\"infos\"> \
  262. <span class=\"first-line\">%@</span> \
  263. <span class=\"second-line\">%lu items</span> \
  264. </div> \
  265. </a> \
  266. <div class=\"content\">",
  267. mo.objectID.URIRepresentation,
  268. [(MLAlbum *)mo name],
  269. (unsigned long)[albumTracks count]]];
  270. for (MLAlbumTrack *track in albumTracks) {
  271. duration = [[VLCTime timeWithNumber:[(MLFile *)[[track files] anyObject] duration]] stringValue];
  272. [mediaInHtml addObject:[NSString stringWithFormat:
  273. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  274. <a href=\"download/%@\" class=\"inner\"> \
  275. <div class=\"down icon\"></div> \
  276. <div class=\"infos\"> \
  277. <span class=\"first-line\">%@</span> \
  278. <span class=\"second-line\">%@ - %0.2f MB</span> \
  279. </div> \
  280. </a> \
  281. </div>",
  282. track.objectID.URIRepresentation,
  283. [[(MLFile *)[[track files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
  284. track.title,
  285. duration, (float)([(MLFile *)[[track files] anyObject] fileSizeInBytes] / 1e6)]];
  286. if (shouldReturnLibVLCXML)
  287. [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/download/%@/Thumbnails/File/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"\"/>", track.title, hostName, pathLibrary, [[NSString stringWithFormat:@"%@", track.objectID.URIRepresentation] lastPathComponent], duration, [(MLFile *)[[track files] anyObject] fileSizeInBytes], hostName, [[(MLFile *)[[track files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""]]];
  288. }
  289. [mediaInHtml addObject:@"</div></div>"];
  290. }
  291. }
  292. NSString *deviceModel = [[UIDevice currentDevice] model];
  293. NSDictionary *replacementDict;
  294. HTTPDynamicFileResponse *fileResponse;
  295. if (shouldReturnLibVLCXML) {
  296. replacementDict = @{@"FILES" : [mediaInXml componentsJoinedByString:@" "],
  297. @"NB_FILE" : [NSString stringWithFormat:@"%li", (unsigned long)mediaInXml.count],
  298. @"LIB_TITLE" : [[UIDevice currentDevice] name]};
  299. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  300. forConnection:self
  301. separator:@"%%"
  302. replacementDictionary:replacementDict];
  303. fileResponse.contentType = @"application/xml";
  304. } else {
  305. replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
  306. @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
  307. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  308. @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil), deviceModel],
  309. @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
  310. @"WEBINTF_DOWNLOADFILES_LONG" : [NSString stringWithFormat: NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil), deviceModel]};
  311. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  312. forConnection:self
  313. separator:@"%%"
  314. replacementDictionary:replacementDict];
  315. fileResponse.contentType = @"text/html";
  316. }
  317. return fileResponse;
  318. } else if ([relativePath isEqualToString:@"/style.css"]) {
  319. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
  320. HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  321. forConnection:self
  322. separator:@"%%"
  323. replacementDictionary:replacementDict];
  324. fileResponse.contentType = @"text/css";
  325. return fileResponse;
  326. }
  327. return [super httpResponseForMethod:method URI:path];
  328. }
  329. - (void)prepareForBodyWithSize:(UInt64)contentLength
  330. {
  331. // set up mime parser
  332. NSString* boundary = [request headerField:@"boundary"];
  333. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  334. _parser.delegate = self;
  335. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  336. _contentLength = contentLength;
  337. }
  338. - (void)processBodyData:(NSData *)postDataChunk
  339. {
  340. /* append data to the parser. It will invoke callbacks to let us handle
  341. * parsed data. */
  342. [_parser appendData:postDataChunk];
  343. _receivedContent += postDataChunk.length;
  344. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  345. }
  346. //-----------------------------------------------------------------
  347. #pragma mark multipart form data parser delegate
  348. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  349. {
  350. /* in this sample, we are not interested in parts, other then file parts.
  351. * check content disposition to find out filename */
  352. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  353. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  354. if ((nil == filename) || [filename isEqualToString: @""]) {
  355. // it's either not a file part, or
  356. // an empty form sent. we won't handle it.
  357. return;
  358. }
  359. // create the path where to store the media temporarily
  360. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  361. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  362. NSFileManager *fileManager = [NSFileManager defaultManager];
  363. BOOL isDir = YES;
  364. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ])
  365. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  366. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  367. NSNumber *freeSpace = [[UIDevice currentDevice] freeDiskspace];
  368. if (_contentLength >= freeSpace.longLongValue) {
  369. /* avoid deadlock since we are on a background thread */
  370. [self performSelectorOnMainThread:@selector(notifyUserAboutEndOfFreeStorage:) withObject:filename waitUntilDone:NO];
  371. [self handleResourceNotFound];
  372. [self stop];
  373. return;
  374. }
  375. APLog(@"Saving file to %@", _filepath);
  376. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  377. APLog(@"Could not create directory at path: %@", _filepath);
  378. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  379. APLog(@"Could not create file at path: %@", _filepath);
  380. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  381. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  382. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  383. }
  384. - (void)notifyUserAboutEndOfFreeStorage:(NSString *)filename
  385. {
  386. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  387. message:[NSString stringWithFormat:
  388. NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  389. filename,
  390. [[UIDevice currentDevice] model]]
  391. delegate:self
  392. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  393. otherButtonTitles:nil];
  394. [alert show];
  395. }
  396. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  397. {
  398. // here we just write the output from parser to the file.
  399. if (_storeFile) {
  400. @try {
  401. [_storeFile writeData:data];
  402. }
  403. @catch (NSException *exception) {
  404. APLog(@"File to write further data because storage is full.");
  405. [_storeFile closeFile];
  406. _storeFile = nil;
  407. /* don't block */
  408. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  409. }
  410. }
  411. }
  412. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  413. {
  414. // as the file part is over, we close the file.
  415. APLog(@"closing file");
  416. [_storeFile closeFile];
  417. _storeFile = nil;
  418. }
  419. - (BOOL)shouldDie
  420. {
  421. if (_filepath) {
  422. if (_filepath.length > 0)
  423. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
  424. }
  425. return [super shouldDie];
  426. }
  427. #pragma mark subtitle
  428. - (NSMutableArray *)_listOfSubtitle
  429. {
  430. NSMutableArray *listOfSubtitle = [[NSMutableArray alloc] init];
  431. NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  432. NSArray *allfiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
  433. NSString *filePath;
  434. for (int count = 0; count < allfiles.count; count++) {
  435. filePath = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, allfiles[count]] stringByReplacingOccurrencesOfString:@"file://"withString:@""];
  436. if ([filePath isSupportedSubtitleFormat])
  437. [listOfSubtitle addObject:filePath];
  438. }
  439. return listOfSubtitle;
  440. }
  441. - (NSString *)_checkSubtitleFound:(NSString *)fileURL
  442. {
  443. NSString *subtitlePath = @"";
  444. NSString *fileName = [[fileURL lastPathComponent] stringByDeletingPathExtension];
  445. NSMutableArray *listOfSubtitle = [self _listOfSubtitle];
  446. NSString *fileSub;
  447. for (int count = 0; count < listOfSubtitle.count; count++) {
  448. fileSub = [NSString stringWithFormat:@"%@", listOfSubtitle[count]];
  449. if ([fileSub rangeOfString:fileName].location != NSNotFound)
  450. subtitlePath = [listOfSubtitle objectAtIndex:count];
  451. }
  452. return subtitlePath;
  453. }
  454. @end