VLCHTTPConnection.m 28 KB

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