VLCHTTPConnection.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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 "HTTPErrorResponse.h"
  24. #import "NSString+SupportedMedia.h"
  25. #import "UIDevice+VLC.h"
  26. #import "VLCHTTPUploaderController.h"
  27. #if TARGET_OS_IOS
  28. #import "VLCThumbnailsCache.h"
  29. #endif
  30. #if TARGET_OS_TV
  31. #import "VLCPlayerControlWebSocket.h"
  32. #endif
  33. @interface VLCHTTPConnection()
  34. {
  35. MultipartFormDataParser *_parser;
  36. NSFileHandle *_storeFile;
  37. NSString *_filepath;
  38. UInt64 _contentLength;
  39. UInt64 _receivedContent;
  40. #if TARGET_OS_TV
  41. BOOL _playbackStarted;
  42. #endif
  43. }
  44. @end
  45. @implementation VLCHTTPConnection
  46. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  47. {
  48. // Add support for POST
  49. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
  50. return YES;
  51. return [super supportsMethod:method atPath:path];
  52. }
  53. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  54. {
  55. // Inform HTTP server that we expect a body to accompany a POST request
  56. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  57. // here we need to make sure, boundary is set in header
  58. NSString* contentType = [request headerField:@"Content-Type"];
  59. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  60. if (NSNotFound == paramsSeparator)
  61. return NO;
  62. if (paramsSeparator >= contentType.length - 1)
  63. return NO;
  64. NSString* type = [contentType substringToIndex:paramsSeparator];
  65. if (![type isEqualToString:@"multipart/form-data"]) {
  66. // we expect multipart/form-data content type
  67. return NO;
  68. }
  69. // enumerate all params in content-type, and find boundary there
  70. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  71. NSUInteger count = params.count;
  72. for (NSUInteger i = 0; i < count; i++) {
  73. NSString *param = params[i];
  74. paramsSeparator = [param rangeOfString:@"="].location;
  75. if ((NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1)
  76. continue;
  77. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  78. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  79. if ([paramName isEqualToString: @"boundary"])
  80. // let's separate the boundary from content-type, to make it more handy to handle
  81. [request setHeaderField:@"boundary" value:paramValue];
  82. }
  83. // check if boundary specified
  84. if (nil == [request headerField:@"boundary"])
  85. return NO;
  86. return YES;
  87. }
  88. return [super expectsRequestBodyFromMethod:method atPath:path];
  89. }
  90. - (NSObject<HTTPResponse> *)_httpPOSTresponseUploadJSON
  91. {
  92. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  93. }
  94. #if TARGET_OS_IOS
  95. - (NSObject<HTTPResponse> *)_httpGETDownloadForPath:(NSString *)path
  96. {
  97. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/download/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  98. HTTPFileResponse *fileResponse = [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
  99. fileResponse.contentType = @"application/octet-stream";
  100. return fileResponse;
  101. }
  102. - (NSObject<HTTPResponse> *)_httpGETThumbnailForPath:(NSString *)path
  103. {
  104. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/thumbnail/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  105. filePath = [filePath stringByReplacingOccurrencesOfString:@".png" withString:@""];
  106. NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
  107. if (moc) {
  108. NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
  109. if (psc) {
  110. NSManagedObject *mo = nil;
  111. @try {
  112. mo = [moc existingObjectWithID:[psc managedObjectIDForURIRepresentation:[NSURL URLWithString:filePath]] error:nil];
  113. }@catch (NSException *exeption) {
  114. // somebody gave us a malformed or stale URIRepresentation
  115. }
  116. NSData *theData;
  117. NSString *contentType;
  118. /* devices category 3 and faster include HW accelerated JPEG encoding
  119. * so we can make our transfers faster by using waaay smaller images */
  120. if ([[UIDevice currentDevice] speedCategory] < 3) {
  121. theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForManagedObject:mo]);
  122. contentType = @"image/png";
  123. } else {
  124. theData = UIImageJPEGRepresentation([VLCThumbnailsCache thumbnailForManagedObject:mo], .9);
  125. contentType = @"image/jpg";
  126. }
  127. if (theData) {
  128. HTTPDataResponse *dataResponse = [[HTTPDataResponse alloc] initWithData:theData];
  129. dataResponse.contentType = contentType;
  130. return dataResponse;
  131. }
  132. }
  133. }
  134. }
  135. - (NSObject<HTTPResponse> *)_httpGETLibraryForPath:(NSString *)path
  136. {
  137. NSString *filePath = [self filePathForURI:path];
  138. NSString *documentRoot = [config documentRoot];
  139. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  140. BOOL shouldReturnLibVLCXML = [relativePath isEqualToString:@"/libMediaVLC.xml"];
  141. NSMutableArray *allMedia = [[NSMutableArray alloc] init];
  142. /* add all albums */
  143. NSArray *allAlbums = [MLAlbum allAlbums];
  144. for (MLAlbum *album in allAlbums) {
  145. if (album.name.length > 0 && album.tracks.count > 1)
  146. [allMedia addObject:album];
  147. }
  148. /* add all shows */
  149. NSArray *allShows = [MLShow allShows];
  150. for (MLShow *show in allShows) {
  151. if (show.name.length > 0 && show.episodes.count > 1)
  152. [allMedia addObject:show];
  153. }
  154. /* add all folders*/
  155. NSArray *allFolders = [MLLabel allLabels];
  156. for (MLLabel *folder in allFolders)
  157. [allMedia addObject:folder];
  158. /* add all remaining files */
  159. NSArray *allFiles = [MLFile allFiles];
  160. for (MLFile *file in allFiles) {
  161. if (file.labels.count > 0) continue;
  162. if (!file.isShowEpisode && !file.isAlbumTrack)
  163. [allMedia addObject:file];
  164. else if (file.isShowEpisode) {
  165. if (file.showEpisode.show.episodes.count < 2)
  166. [allMedia addObject:file];
  167. } else if (file.isAlbumTrack) {
  168. if (file.albumTrack.album.tracks.count < 2)
  169. [allMedia addObject:file];
  170. }
  171. }
  172. NSUInteger mediaCount = allMedia.count;
  173. NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
  174. NSMutableArray *mediaInXml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
  175. NSString *hostName = [[VLCHTTPUploaderController sharedInstance] hostname];
  176. NSString *duration;
  177. for (NSManagedObject *mo in allMedia) {
  178. if ([mo isKindOfClass:[MLFile class]]) {
  179. MLFile *file = (MLFile *)mo;
  180. duration = [[VLCTime timeWithNumber:file.duration] stringValue];
  181. [mediaInHtml addObject:[NSString stringWithFormat:
  182. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  183. <a href=\"download/%@\" class=\"inner\"> \
  184. <div class=\"down icon\"></div> \
  185. <div class=\"infos\"> \
  186. <span class=\"first-line\">%@</span> \
  187. <span class=\"second-line\">%@ - %0.2f MB</span> \
  188. </div> \
  189. </a> \
  190. </div>",
  191. file.objectID.URIRepresentation,
  192. [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  193. file.title,
  194. duration, (float)(file.fileSizeInBytes / 1e6)]];
  195. if (shouldReturnLibVLCXML) {
  196. NSString *pathSub = [self _checkIfSubtitleWasFound:file.path];
  197. if (pathSub)
  198. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  199. [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]];
  200. }
  201. }
  202. else if ([mo isKindOfClass:[MLShow class]]) {
  203. MLShow *show = (MLShow *)mo;
  204. NSArray *episodes = [show sortedEpisodes];
  205. [mediaInHtml addObject:[NSString stringWithFormat:
  206. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  207. <a href=\"#\" class=\"inner folder\"> \
  208. <div class=\"open icon\"></div> \
  209. <div class=\"infos\"> \
  210. <span class=\"first-line\">%@</span> \
  211. <span class=\"second-line\">%lu items</span> \
  212. </div> \
  213. </a> \
  214. <div class=\"content\">",
  215. mo.objectID.URIRepresentation,
  216. show.name,
  217. (unsigned long)[episodes count]]];
  218. for (MLShowEpisode *showEp in episodes) {
  219. MLFile *anyFileFromEpisode = (MLFile *)[[showEp files] anyObject];
  220. duration = [[VLCTime timeWithNumber:[anyFileFromEpisode duration]] stringValue];
  221. [mediaInHtml addObject:[NSString stringWithFormat:
  222. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  223. <a href=\"download/%@\" class=\"inner\"> \
  224. <div class=\"down icon\"></div> \
  225. <div class=\"infos\"> \
  226. <span class=\"first-line\">S%@E%@ - %@</span> \
  227. <span class=\"second-line\">%@ - %0.2f MB</span> \
  228. </div> \
  229. </a> \
  230. </div>",
  231. showEp.objectID.URIRepresentation,
  232. [anyFileFromEpisode.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  233. showEp.seasonNumber,
  234. showEp.episodeNumber,
  235. showEp.name,
  236. duration, (float)([anyFileFromEpisode fileSizeInBytes] / 1e6)]];
  237. if (shouldReturnLibVLCXML) {
  238. NSString *pathSub = [self _checkIfSubtitleWasFound:[anyFileFromEpisode path]];
  239. if (![pathSub isEqualToString:@""])
  240. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  241. [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]];
  242. }
  243. }
  244. [mediaInHtml addObject:@"</div></div>"];
  245. } else if ([mo isKindOfClass:[MLLabel class]]) {
  246. MLLabel *label = (MLLabel *)mo;
  247. NSArray *folderItems = [label sortedFolderItems];
  248. [mediaInHtml addObject:[NSString stringWithFormat:
  249. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  250. <a href=\"#\" class=\"inner folder\"> \
  251. <div class=\"open icon\"></div> \
  252. <div class=\"infos\"> \
  253. <span class=\"first-line\">%@</span> \
  254. <span class=\"second-line\">%lu items</span> \
  255. </div> \
  256. </a> \
  257. <div class=\"content\">",
  258. label.objectID.URIRepresentation,
  259. label.name,
  260. (unsigned long)folderItems.count]];
  261. for (MLFile *file in folderItems) {
  262. duration = [[VLCTime timeWithNumber:[file duration]] stringValue];
  263. [mediaInHtml addObject:[NSString stringWithFormat:
  264. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  265. <a href=\"download/%@\" class=\"inner\"> \
  266. <div class=\"down icon\"></div> \
  267. <div class=\"infos\"> \
  268. <span class=\"first-line\">%@</span> \
  269. <span class=\"second-line\">%@ - %0.2f MB</span> \
  270. </div> \
  271. </a> \
  272. </div>",
  273. file.objectID.URIRepresentation,
  274. [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  275. file.title,
  276. duration, (float)(file.fileSizeInBytes / 1e6)]];
  277. if (shouldReturnLibVLCXML) {
  278. NSString *pathSub = [self _checkIfSubtitleWasFound:file.path];
  279. if (pathSub)
  280. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  281. [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]];
  282. }
  283. }
  284. [mediaInHtml addObject:@"</div></div>"];
  285. } else if ([mo isKindOfClass:[MLAlbum class]]) {
  286. MLAlbum *album = (MLAlbum *)mo;
  287. NSArray *albumTracks = [album sortedTracks];
  288. [mediaInHtml addObject:[NSString stringWithFormat:
  289. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  290. <a href=\"#\" class=\"inner folder\"> \
  291. <div class=\"open icon\"></div> \
  292. <div class=\"infos\"> \
  293. <span class=\"first-line\">%@</span> \
  294. <span class=\"second-line\">%lu items</span> \
  295. </div> \
  296. </a> \
  297. <div class=\"content\">",
  298. album.objectID.URIRepresentation,
  299. album.name,
  300. (unsigned long)albumTracks.count]];
  301. for (MLAlbumTrack *track in albumTracks) {
  302. MLFile *anyFileFromTrack = [track anyFileFromTrack];
  303. duration = [[VLCTime timeWithNumber:[anyFileFromTrack duration]] stringValue];
  304. [mediaInHtml addObject:[NSString stringWithFormat:
  305. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  306. <a href=\"download/%@\" class=\"inner\"> \
  307. <div class=\"down icon\"></div> \
  308. <div class=\"infos\"> \
  309. <span class=\"first-line\">%@</span> \
  310. <span class=\"second-line\">%@ - %0.2f MB</span> \
  311. </div> \
  312. </a> \
  313. </div>",
  314. track.objectID.URIRepresentation,
  315. [anyFileFromTrack.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  316. track.title,
  317. duration, (float)([anyFileFromTrack fileSizeInBytes] / 1e6)]];
  318. if (shouldReturnLibVLCXML)
  319. [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]]];
  320. }
  321. [mediaInHtml addObject:@"</div></div>"];
  322. }
  323. }
  324. UIDevice *currentDevice = [UIDevice currentDevice];
  325. NSString *deviceModel = [currentDevice model];
  326. NSDictionary *replacementDict;
  327. HTTPDynamicFileResponse *fileResponse;
  328. if (shouldReturnLibVLCXML) {
  329. replacementDict = @{@"FILES" : [mediaInXml componentsJoinedByString:@" "],
  330. @"NB_FILE" : [NSString stringWithFormat:@"%li", (unsigned long)mediaInXml.count],
  331. @"LIB_TITLE" : [currentDevice name]};
  332. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  333. forConnection:self
  334. separator:@"%%"
  335. replacementDictionary:replacementDict];
  336. fileResponse.contentType = @"application/xml";
  337. } else {
  338. replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
  339. @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
  340. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  341. @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil), deviceModel],
  342. @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
  343. @"WEBINTF_DOWNLOADFILES_LONG" : [NSString stringWithFormat: NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil), deviceModel]};
  344. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  345. forConnection:self
  346. separator:@"%%"
  347. replacementDictionary:replacementDict];
  348. fileResponse.contentType = @"text/html";
  349. }
  350. return fileResponse;
  351. }
  352. #else
  353. - (NSObject<HTTPResponse> *)_httpGETLibraryForPath:(NSString *)path
  354. {
  355. UIDevice *currentDevice = [UIDevice currentDevice];
  356. NSString *deviceModel = [currentDevice model];
  357. NSString *filePath = [self filePathForURI:path];
  358. NSString *documentRoot = [config documentRoot];
  359. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  360. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE_ATV", nil),
  361. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  362. @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG_ATV", nil), deviceModel]};
  363. HTTPDynamicFileResponse *fileResponse;
  364. if ([relativePath isEqualToString:@"/index.html"]) {
  365. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  366. forConnection:self
  367. separator:@"%%"
  368. replacementDictionary:replacementDict];
  369. fileResponse.contentType = @"text/html";
  370. }
  371. return fileResponse;
  372. }
  373. #endif
  374. - (NSObject<HTTPResponse> *)_httpGETCSSForPath:(NSString *)path
  375. {
  376. #if TARGET_OS_IOS
  377. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
  378. #else
  379. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE_ATV", nil)};
  380. #endif
  381. HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  382. forConnection:self
  383. separator:@"%%"
  384. replacementDictionary:replacementDict];
  385. fileResponse.contentType = @"text/css";
  386. return fileResponse;
  387. }
  388. #if TARGET_OS_TV
  389. - (NSObject <HTTPResponse> *)_HTTPGETPlaying
  390. {
  391. /* JSON response:
  392. {
  393. "currentTime": 42,
  394. "media": {
  395. "id": "some id",
  396. "title": "some title",
  397. "duration": 120000
  398. }
  399. }
  400. */
  401. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  402. if (!vpc.activePlaybackSession) {
  403. return [[HTTPErrorResponse alloc] initWithErrorCode:404];
  404. }
  405. VLCMediaPlayer *player = vpc.mediaPlayer;
  406. VLCMedia *media = player.media;
  407. if (!media) {
  408. return [[HTTPErrorResponse alloc] initWithErrorCode:404];
  409. }
  410. NSString *mediaTitle = vpc.mediaTitle;
  411. if (!mediaTitle)
  412. mediaTitle = @"";
  413. NSDictionary *mediaDict = @{ @"id" : media.url.absoluteString,
  414. @"title" : mediaTitle,
  415. @"duration" : @(media.length.intValue)};
  416. NSDictionary *returnDict = @{ @"currentTime" : @(player.time.intValue),
  417. @"media" : mediaDict };
  418. NSError *error;
  419. NSData *returnData = [NSJSONSerialization dataWithJSONObject:returnDict options:0 error:&error];
  420. if (error != nil) {
  421. APLog(@"JSON serialization failed %@", error);
  422. return [[HTTPErrorResponse alloc] initWithErrorCode:500];
  423. }
  424. return [[HTTPDataResponse alloc] initWithData:returnData];
  425. }
  426. - (NSObject <HTTPResponse> *)_HTTPGETPlaylist
  427. {
  428. /* JSON response:
  429. [
  430. {
  431. "media": {
  432. "id": "some id 1",
  433. "title": "some title 1",
  434. "duration": 120000
  435. }
  436. },
  437. ...]
  438. */
  439. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  440. if (!vpc.activePlaybackSession || !vpc.mediaList) {
  441. return [[HTTPErrorResponse alloc] initWithErrorCode:404];
  442. }
  443. VLCMediaList *mediaList = vpc.mediaList;
  444. [mediaList lock];
  445. NSUInteger mediaCount = mediaList.count;
  446. NSMutableArray *retArray = [NSMutableArray array];
  447. for (NSUInteger x = 0; x < mediaCount; x++) {
  448. VLCMedia *media = [mediaList mediaAtIndex:x];
  449. NSString *mediaTitle;
  450. if (media.isParsed) {
  451. mediaTitle = [media metadataForKey:VLCMetaInformationTitle];
  452. } else {
  453. mediaTitle = media.url.lastPathComponent;
  454. }
  455. NSDictionary *mediaDict = @{ @"id" : media.url.absoluteString,
  456. @"title" : mediaTitle,
  457. @"duration" : @(media.length.intValue) };
  458. [retArray addObject:@{ @"media" : mediaDict }];
  459. }
  460. [mediaList unlock];
  461. NSError *error;
  462. NSData *returnData = [NSJSONSerialization dataWithJSONObject:retArray options:0 error:&error];
  463. if (error != nil) {
  464. APLog(@"JSON serialization failed %@", error);
  465. return [[HTTPErrorResponse alloc] initWithErrorCode:500];
  466. }
  467. return [[HTTPDataResponse alloc] initWithData:returnData];
  468. }
  469. #endif
  470. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  471. {
  472. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
  473. return [self _httpPOSTresponseUploadJSON];
  474. #if TARGET_OS_IOS
  475. if ([path hasPrefix:@"/download/"]) {
  476. return [self _httpGETDownloadForPath:path];
  477. }
  478. if ([path hasPrefix:@"/thumbnail"]) {
  479. return [self _httpGETThumbnailForPath:path];
  480. }
  481. #else
  482. if ([path hasPrefix:@"/playing"]) {
  483. return [self _HTTPGETPlaying];
  484. }
  485. if ([path hasPrefix:@"/playlist"]) {
  486. return [self _HTTPGETPlaylist];
  487. }
  488. #endif
  489. NSString *filePath = [self filePathForURI:path];
  490. NSString *documentRoot = [config documentRoot];
  491. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  492. if ([relativePath isEqualToString:@"/index.html"] || [relativePath isEqualToString:@"/libMediaVLC.xml"]) {
  493. return [self _httpGETLibraryForPath:path];
  494. } else if ([relativePath isEqualToString:@"/style.css"]) {
  495. return [self _httpGETCSSForPath:path];
  496. }
  497. return [super httpResponseForMethod:method URI:path];
  498. }
  499. #if TARGET_OS_TV
  500. - (WebSocket *)webSocketForURI:(NSString *)path
  501. {
  502. return [[VLCPlayerControlWebSocket alloc] initWithRequest:request socket:asyncSocket];
  503. }
  504. #endif
  505. - (void)prepareForBodyWithSize:(UInt64)contentLength
  506. {
  507. // set up mime parser
  508. NSString* boundary = [request headerField:@"boundary"];
  509. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  510. _parser.delegate = self;
  511. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  512. _contentLength = contentLength;
  513. }
  514. - (void)processBodyData:(NSData *)postDataChunk
  515. {
  516. /* append data to the parser. It will invoke callbacks to let us handle
  517. * parsed data. */
  518. [_parser appendData:postDataChunk];
  519. _receivedContent += postDataChunk.length;
  520. long long percentage = ((_receivedContent * 100) / _contentLength);
  521. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, percentage);
  522. #if TARGET_OS_TV
  523. if (!_playbackStarted) {
  524. if (percentage >= 10) {
  525. _playbackStarted = YES;
  526. APLog(@"Starting playback of %@", _filepath);
  527. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  528. [vpc playURL:[NSURL fileURLWithPath:_filepath] successCallback:nil errorCallback:nil];
  529. VLCFullscreenMovieTVViewController *moviewVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  530. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:moviewVC
  531. animated:YES
  532. completion:nil];
  533. }
  534. }
  535. #endif
  536. }
  537. //-----------------------------------------------------------------
  538. #pragma mark multipart form data parser delegate
  539. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  540. {
  541. /* in this sample, we are not interested in parts, other then file parts.
  542. * check content disposition to find out filename */
  543. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  544. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  545. if ((nil == filename) || [filename isEqualToString: @""]) {
  546. // it's either not a file part, or
  547. // an empty form sent. we won't handle it.
  548. return;
  549. }
  550. // create the path where to store the media temporarily
  551. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  552. NSString *uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  553. NSFileManager *fileManager = [NSFileManager defaultManager];
  554. BOOL isDir = YES;
  555. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir])
  556. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  557. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  558. NSNumber *freeSpace = [[UIDevice currentDevice] freeDiskspace];
  559. if (_contentLength >= freeSpace.longLongValue) {
  560. /* avoid deadlock since we are on a background thread */
  561. [self performSelectorOnMainThread:@selector(notifyUserAboutEndOfFreeStorage:) withObject:filename waitUntilDone:NO];
  562. [self handleResourceNotFound];
  563. [self stop];
  564. return;
  565. }
  566. APLog(@"Saving file to %@", _filepath);
  567. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  568. APLog(@"Could not create directory at path: %@", _filepath);
  569. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  570. APLog(@"Could not create file at path: %@", _filepath);
  571. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  572. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  573. [activityManager networkActivityStarted];
  574. [activityManager disableIdleTimer];
  575. }
  576. - (void)notifyUserAboutEndOfFreeStorage:(NSString *)filename
  577. {
  578. #if TARGET_OS_IOS
  579. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  580. message:[NSString stringWithFormat:
  581. NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  582. filename,
  583. [[UIDevice currentDevice] model]]
  584. delegate:self
  585. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  586. otherButtonTitles:nil];
  587. [alert show];
  588. #else
  589. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  590. message:[NSString stringWithFormat:
  591. NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  592. filename,
  593. [[UIDevice currentDevice] model]]
  594. preferredStyle:UIAlertControllerStyleAlert];
  595. [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  596. style:UIAlertActionStyleCancel
  597. handler:nil]];
  598. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  599. #endif
  600. }
  601. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  602. {
  603. // here we just write the output from parser to the file.
  604. if (_storeFile) {
  605. @try {
  606. [_storeFile writeData:data];
  607. }
  608. @catch (NSException *exception) {
  609. APLog(@"File to write further data because storage is full.");
  610. [_storeFile closeFile];
  611. _storeFile = nil;
  612. /* don't block */
  613. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  614. }
  615. }
  616. }
  617. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  618. {
  619. // as the file part is over, we close the file.
  620. APLog(@"closing file");
  621. [_storeFile closeFile];
  622. _storeFile = nil;
  623. }
  624. - (BOOL)shouldDie
  625. {
  626. if (_filepath) {
  627. if (_filepath.length > 0)
  628. [[VLCHTTPUploaderController sharedInstance] moveFileFrom:_filepath];
  629. }
  630. return [super shouldDie];
  631. }
  632. #pragma mark subtitle
  633. - (NSMutableArray *)_listOfSubtitles
  634. {
  635. NSMutableArray *listOfSubtitles = [[NSMutableArray alloc] init];
  636. NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  637. NSArray *allFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
  638. NSString *filePath;
  639. NSUInteger count = allFiles.count;
  640. for (NSUInteger i = 0; i < count; i++) {
  641. filePath = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, allFiles[i]] stringByReplacingOccurrencesOfString:@"file://"withString:@""];
  642. if ([filePath isSupportedSubtitleFormat])
  643. [listOfSubtitles addObject:filePath];
  644. }
  645. return listOfSubtitles;
  646. }
  647. - (NSString *)_checkIfSubtitleWasFound:(NSString *)filePath
  648. {
  649. NSString *subtitlePath;
  650. NSString *fileSub;
  651. NSString *currentPath;
  652. NSString *fileName = [[filePath lastPathComponent] stringByDeletingPathExtension];
  653. if (fileName == nil)
  654. return nil;
  655. NSMutableArray *listOfSubtitles = [self _listOfSubtitles];
  656. NSUInteger count = listOfSubtitles.count;
  657. for (NSUInteger i = 0; i < count; i++) {
  658. currentPath = listOfSubtitles[i];
  659. fileSub = [NSString stringWithFormat:@"%@", currentPath];
  660. if ([fileSub rangeOfString:fileName].location != NSNotFound)
  661. subtitlePath = currentPath;
  662. }
  663. return subtitlePath;
  664. }
  665. @end