VLCHTTPConnection.m 28 KB

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