VLCHTTPConnection.m 29 KB

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