VLCHTTPConnection.m 28 KB

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