VLCHTTPConnection.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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. NSMutableArray *_receivedFiles;
  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. return [[HTTPErrorResponse alloc] initWithErrorCode:404];
  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. return [[HTTPErrorResponse alloc] initWithErrorCode:404];
  135. }
  136. - (NSObject<HTTPResponse> *)_httpGETLibraryForPath:(NSString *)path
  137. {
  138. NSString *filePath = [self filePathForURI:path];
  139. NSString *documentRoot = [config documentRoot];
  140. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  141. BOOL shouldReturnLibVLCXML = [relativePath isEqualToString:@"/libMediaVLC.xml"];
  142. NSMutableArray *allMedia = [[NSMutableArray alloc] init];
  143. /* add all albums */
  144. NSArray *allAlbums = [MLAlbum allAlbums];
  145. for (MLAlbum *album in allAlbums) {
  146. if (album.name.length > 0 && album.tracks.count > 1)
  147. [allMedia addObject:album];
  148. }
  149. /* add all shows */
  150. NSArray *allShows = [MLShow allShows];
  151. for (MLShow *show in allShows) {
  152. if (show.name.length > 0 && show.episodes.count > 1)
  153. [allMedia addObject:show];
  154. }
  155. /* add all folders*/
  156. NSArray *allFolders = [MLLabel allLabels];
  157. for (MLLabel *folder in allFolders)
  158. [allMedia addObject:folder];
  159. /* add all remaining files */
  160. NSArray *allFiles = [MLFile allFiles];
  161. for (MLFile *file in allFiles) {
  162. if (file.labels.count > 0) continue;
  163. if (!file.isShowEpisode && !file.isAlbumTrack)
  164. [allMedia addObject:file];
  165. else if (file.isShowEpisode) {
  166. if (file.showEpisode.show.episodes.count < 2)
  167. [allMedia addObject:file];
  168. } else if (file.isAlbumTrack) {
  169. if (file.albumTrack.album.tracks.count < 2)
  170. [allMedia addObject:file];
  171. }
  172. }
  173. NSUInteger mediaCount = allMedia.count;
  174. NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
  175. NSMutableArray *mediaInXml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
  176. NSString *hostName = [[VLCHTTPUploaderController sharedInstance] hostname];
  177. NSString *duration;
  178. for (NSManagedObject *mo in allMedia) {
  179. if ([mo isKindOfClass:[MLFile class]]) {
  180. MLFile *file = (MLFile *)mo;
  181. duration = [[VLCTime timeWithNumber:file.duration] stringValue];
  182. [mediaInHtml addObject:[NSString stringWithFormat:
  183. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  184. <a href=\"download/%@\" class=\"inner\"> \
  185. <div class=\"down icon\"></div> \
  186. <div class=\"infos\"> \
  187. <span class=\"first-line\">%@</span> \
  188. <span class=\"second-line\">%@ - %0.2f MB</span> \
  189. </div> \
  190. </a> \
  191. </div>",
  192. file.objectID.URIRepresentation,
  193. [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  194. file.title,
  195. duration, (float)(file.fileSizeInBytes / 1e6)]];
  196. if (shouldReturnLibVLCXML) {
  197. NSString *pathSub = [self _checkIfSubtitleWasFound:file.path];
  198. if (pathSub)
  199. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  200. [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]];
  201. }
  202. }
  203. else if ([mo isKindOfClass:[MLShow class]]) {
  204. MLShow *show = (MLShow *)mo;
  205. NSArray *episodes = [show sortedEpisodes];
  206. [mediaInHtml addObject:[NSString stringWithFormat:
  207. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  208. <a href=\"#\" class=\"inner folder\"> \
  209. <div class=\"open icon\"></div> \
  210. <div class=\"infos\"> \
  211. <span class=\"first-line\">%@</span> \
  212. <span class=\"second-line\">%lu items</span> \
  213. </div> \
  214. </a> \
  215. <div class=\"content\">",
  216. mo.objectID.URIRepresentation,
  217. show.name,
  218. (unsigned long)[episodes count]]];
  219. for (MLShowEpisode *showEp in episodes) {
  220. MLFile *anyFileFromEpisode = (MLFile *)[[showEp files] anyObject];
  221. duration = [[VLCTime timeWithNumber:[anyFileFromEpisode duration]] stringValue];
  222. [mediaInHtml addObject:[NSString stringWithFormat:
  223. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  224. <a href=\"download/%@\" class=\"inner\"> \
  225. <div class=\"down icon\"></div> \
  226. <div class=\"infos\"> \
  227. <span class=\"first-line\">S%@E%@ - %@</span> \
  228. <span class=\"second-line\">%@ - %0.2f MB</span> \
  229. </div> \
  230. </a> \
  231. </div>",
  232. showEp.objectID.URIRepresentation,
  233. [anyFileFromEpisode.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  234. showEp.seasonNumber,
  235. showEp.episodeNumber,
  236. showEp.name,
  237. duration, (float)([anyFileFromEpisode fileSizeInBytes] / 1e6)]];
  238. if (shouldReturnLibVLCXML) {
  239. NSString *pathSub = [self _checkIfSubtitleWasFound:[anyFileFromEpisode path]];
  240. if (![pathSub isEqualToString:@""])
  241. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  242. [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]];
  243. }
  244. }
  245. [mediaInHtml addObject:@"</div></div>"];
  246. } else if ([mo isKindOfClass:[MLLabel class]]) {
  247. MLLabel *label = (MLLabel *)mo;
  248. NSArray *folderItems = [label sortedFolderItems];
  249. [mediaInHtml addObject:[NSString stringWithFormat:
  250. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  251. <a href=\"#\" class=\"inner folder\"> \
  252. <div class=\"open icon\"></div> \
  253. <div class=\"infos\"> \
  254. <span class=\"first-line\">%@</span> \
  255. <span class=\"second-line\">%lu items</span> \
  256. </div> \
  257. </a> \
  258. <div class=\"content\">",
  259. label.objectID.URIRepresentation,
  260. label.name,
  261. (unsigned long)folderItems.count]];
  262. for (MLFile *file in folderItems) {
  263. duration = [[VLCTime timeWithNumber:[file duration]] stringValue];
  264. [mediaInHtml addObject:[NSString stringWithFormat:
  265. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  266. <a href=\"download/%@\" class=\"inner\"> \
  267. <div class=\"down icon\"></div> \
  268. <div class=\"infos\"> \
  269. <span class=\"first-line\">%@</span> \
  270. <span class=\"second-line\">%@ - %0.2f MB</span> \
  271. </div> \
  272. </a> \
  273. </div>",
  274. file.objectID.URIRepresentation,
  275. [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  276. file.title,
  277. duration, (float)(file.fileSizeInBytes / 1e6)]];
  278. if (shouldReturnLibVLCXML) {
  279. NSString *pathSub = [self _checkIfSubtitleWasFound:file.path];
  280. if (pathSub)
  281. pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
  282. [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]];
  283. }
  284. }
  285. [mediaInHtml addObject:@"</div></div>"];
  286. } else if ([mo isKindOfClass:[MLAlbum class]]) {
  287. MLAlbum *album = (MLAlbum *)mo;
  288. NSArray *albumTracks = [album sortedTracks];
  289. [mediaInHtml addObject:[NSString stringWithFormat:
  290. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  291. <a href=\"#\" class=\"inner folder\"> \
  292. <div class=\"open icon\"></div> \
  293. <div class=\"infos\"> \
  294. <span class=\"first-line\">%@</span> \
  295. <span class=\"second-line\">%lu items</span> \
  296. </div> \
  297. </a> \
  298. <div class=\"content\">",
  299. album.objectID.URIRepresentation,
  300. album.name,
  301. (unsigned long)albumTracks.count]];
  302. for (MLAlbumTrack *track in albumTracks) {
  303. MLFile *anyFileFromTrack = [track anyFileFromTrack];
  304. duration = [[VLCTime timeWithNumber:[anyFileFromTrack duration]] stringValue];
  305. [mediaInHtml addObject:[NSString stringWithFormat:
  306. @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
  307. <a href=\"download/%@\" class=\"inner\"> \
  308. <div class=\"down icon\"></div> \
  309. <div class=\"infos\"> \
  310. <span class=\"first-line\">%@</span> \
  311. <span class=\"second-line\">%@ - %0.2f MB</span> \
  312. </div> \
  313. </a> \
  314. </div>",
  315. track.objectID.URIRepresentation,
  316. [anyFileFromTrack.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
  317. track.title,
  318. duration, (float)([anyFileFromTrack fileSizeInBytes] / 1e6)]];
  319. if (shouldReturnLibVLCXML)
  320. [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]]];
  321. }
  322. [mediaInHtml addObject:@"</div></div>"];
  323. }
  324. }
  325. UIDevice *currentDevice = [UIDevice currentDevice];
  326. NSString *deviceModel = [currentDevice model];
  327. NSDictionary *replacementDict;
  328. HTTPDynamicFileResponse *fileResponse;
  329. if (shouldReturnLibVLCXML) {
  330. replacementDict = @{@"FILES" : [mediaInXml componentsJoinedByString:@" "],
  331. @"NB_FILE" : [NSString stringWithFormat:@"%li", (unsigned long)mediaInXml.count],
  332. @"LIB_TITLE" : [currentDevice name]};
  333. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  334. forConnection:self
  335. separator:@"%%"
  336. replacementDictionary:replacementDict];
  337. fileResponse.contentType = @"application/xml";
  338. } else {
  339. replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
  340. @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
  341. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  342. @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil), deviceModel],
  343. @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
  344. @"WEBINTF_DOWNLOADFILES_LONG" : [NSString stringWithFormat: NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil), deviceModel]};
  345. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  346. forConnection:self
  347. separator:@"%%"
  348. replacementDictionary:replacementDict];
  349. fileResponse.contentType = @"text/html";
  350. }
  351. return fileResponse;
  352. }
  353. #else
  354. - (NSObject<HTTPResponse> *)_httpGETLibraryForPath:(NSString *)path
  355. {
  356. UIDevice *currentDevice = [UIDevice currentDevice];
  357. NSString *deviceModel = [currentDevice model];
  358. NSString *filePath = [self filePathForURI:path];
  359. NSString *documentRoot = [config documentRoot];
  360. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  361. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE_ATV", nil),
  362. @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
  363. @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG_ATV", nil), deviceModel],
  364. @"WEBINTF_OPEN_URL" : NSLocalizedString(@"ENTER_URL", nil)};
  365. HTTPDynamicFileResponse *fileResponse;
  366. if ([relativePath isEqualToString:@"/index.html"]) {
  367. fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  368. forConnection:self
  369. separator:@"%%"
  370. replacementDictionary:replacementDict];
  371. fileResponse.contentType = @"text/html";
  372. }
  373. return fileResponse;
  374. }
  375. #endif
  376. - (NSObject<HTTPResponse> *)_httpGETCSSForPath:(NSString *)path
  377. {
  378. #if TARGET_OS_IOS
  379. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
  380. #else
  381. NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE_ATV", nil)};
  382. #endif
  383. HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  384. forConnection:self
  385. separator:@"%%"
  386. replacementDictionary:replacementDict];
  387. fileResponse.contentType = @"text/css";
  388. return fileResponse;
  389. }
  390. #if TARGET_OS_TV
  391. - (NSObject <HTTPResponse> *)_HTTPGETPlaying
  392. {
  393. /* JSON response:
  394. {
  395. "currentTime": 42,
  396. "media": {
  397. "id": "some id",
  398. "title": "some title",
  399. "duration": 120000
  400. }
  401. }
  402. */
  403. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  404. if (!vpc.activePlaybackSession) {
  405. return [[HTTPErrorResponse alloc] initWithErrorCode:404];
  406. }
  407. VLCMediaPlayer *player = vpc.mediaPlayer;
  408. VLCMedia *media = player.media;
  409. if (!media) {
  410. return [[HTTPErrorResponse alloc] initWithErrorCode:404];
  411. }
  412. NSString *mediaTitle = vpc.mediaTitle;
  413. if (!mediaTitle)
  414. mediaTitle = @"";
  415. NSDictionary *mediaDict = @{ @"id" : media.url.absoluteString,
  416. @"title" : mediaTitle,
  417. @"duration" : @(media.length.intValue)};
  418. NSDictionary *returnDict = @{ @"currentTime" : @(player.time.intValue),
  419. @"media" : mediaDict };
  420. NSError *error;
  421. NSData *returnData = [NSJSONSerialization dataWithJSONObject:returnDict options:0 error:&error];
  422. if (error != nil) {
  423. APLog(@"JSON serialization failed %@", error);
  424. return [[HTTPErrorResponse alloc] initWithErrorCode:500];
  425. }
  426. return [[HTTPDataResponse alloc] initWithData:returnData];
  427. }
  428. - (NSObject <HTTPResponse> *)_HTTPGETwebResources
  429. {
  430. /* JS response
  431. {
  432. "WEBINTF_URL_SENT" : "URL sent successfully.",
  433. "WEBINTF_URL_EMPTY" :"'URL cannot be empty.",
  434. "WEBINTF_URL_INVALID" : "Not a valid URL."
  435. }
  436. */
  437. NSString *returnString = [NSString stringWithFormat:
  438. @"var LOCALES = {\n" \
  439. "PLAYER_CONTROL: {\n" \
  440. "URL: {\n" \
  441. "EMPTY: \"%@\",\n" \
  442. "NOT_VALID: \"%@\",\n" \
  443. "SENT_SUCCESSFULLY: \"%@\"\n" \
  444. "}\n" \
  445. "}\n" \
  446. "}",
  447. NSLocalizedString(@"WEBINTF_URL_EMPTY", nil),
  448. NSLocalizedString(@"WEBINTF_URL_INVALID", nil),
  449. NSLocalizedString(@"WEBINTF_URL_SENT", nil)];
  450. NSData *returnData = [returnString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
  451. return [[HTTPDataResponse alloc] initWithData:returnData];
  452. }
  453. - (NSObject <HTTPResponse> *)_HTTPGETPlaylist
  454. {
  455. /* JSON response:
  456. [
  457. {
  458. "media": {
  459. "id": "some id 1",
  460. "title": "some title 1",
  461. "duration": 120000
  462. }
  463. },
  464. ...]
  465. */
  466. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  467. if (!vpc.activePlaybackSession || !vpc.mediaList) {
  468. return [[HTTPErrorResponse alloc] initWithErrorCode:404];
  469. }
  470. VLCMediaList *mediaList = vpc.mediaList;
  471. [mediaList lock];
  472. NSUInteger mediaCount = mediaList.count;
  473. NSMutableArray *retArray = [NSMutableArray array];
  474. for (NSUInteger x = 0; x < mediaCount; x++) {
  475. VLCMedia *media = [mediaList mediaAtIndex:x];
  476. NSString *mediaTitle;
  477. if (media.isParsed) {
  478. mediaTitle = [media metadataForKey:VLCMetaInformationTitle];
  479. } else {
  480. mediaTitle = media.url.lastPathComponent;
  481. }
  482. NSDictionary *mediaDict = @{ @"id" : media.url.absoluteString,
  483. @"title" : mediaTitle,
  484. @"duration" : @(media.length.intValue) };
  485. [retArray addObject:@{ @"media" : mediaDict }];
  486. }
  487. [mediaList unlock];
  488. NSError *error;
  489. NSData *returnData = [NSJSONSerialization dataWithJSONObject:retArray options:0 error:&error];
  490. if (error != nil) {
  491. APLog(@"JSON serialization failed %@", error);
  492. return [[HTTPErrorResponse alloc] initWithErrorCode:500];
  493. }
  494. return [[HTTPDataResponse alloc] initWithData:returnData];
  495. }
  496. #endif
  497. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  498. {
  499. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
  500. return [self _httpPOSTresponseUploadJSON];
  501. #if TARGET_OS_IOS
  502. if ([path hasPrefix:@"/download/"]) {
  503. return [self _httpGETDownloadForPath:path];
  504. }
  505. if ([path hasPrefix:@"/thumbnail"]) {
  506. return [self _httpGETThumbnailForPath:path];
  507. }
  508. #else
  509. if ([path hasPrefix:@"/playing"]) {
  510. return [self _HTTPGETPlaying];
  511. }
  512. if ([path hasPrefix:@"/playlist"]) {
  513. return [self _HTTPGETPlaylist];
  514. }
  515. if ([path hasPrefix:@"/web_resources.js"]) {
  516. return [self _HTTPGETwebResources];
  517. }
  518. #endif
  519. NSString *filePath = [self filePathForURI:path];
  520. NSString *documentRoot = [config documentRoot];
  521. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  522. if ([relativePath isEqualToString:@"/index.html"] || [relativePath isEqualToString:@"/libMediaVLC.xml"]) {
  523. return [self _httpGETLibraryForPath:path];
  524. } else if ([relativePath isEqualToString:@"/style.css"]) {
  525. return [self _httpGETCSSForPath:path];
  526. }
  527. return [super httpResponseForMethod:method URI:path];
  528. }
  529. #if TARGET_OS_TV
  530. - (WebSocket *)webSocketForURI:(NSString *)path
  531. {
  532. return [[VLCPlayerControlWebSocket alloc] initWithRequest:request socket:asyncSocket];
  533. }
  534. #endif
  535. - (void)prepareForBodyWithSize:(UInt64)contentLength
  536. {
  537. // set up mime parser
  538. NSString* boundary = [request headerField:@"boundary"];
  539. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  540. _parser.delegate = self;
  541. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  542. _contentLength = contentLength;
  543. }
  544. - (void)processBodyData:(NSData *)postDataChunk
  545. {
  546. /* append data to the parser. It will invoke callbacks to let us handle
  547. * parsed data. */
  548. [_parser appendData:postDataChunk];
  549. _receivedContent += postDataChunk.length;
  550. long long percentage = ((_receivedContent * 100) / _contentLength);
  551. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, percentage);
  552. #if TARGET_OS_TV
  553. if (percentage >= 10) {
  554. [self performSelectorOnMainThread:@selector(startPlaybackOfPath:) withObject:_filepath waitUntilDone:NO];
  555. }
  556. #endif
  557. }
  558. #if TARGET_OS_TV
  559. - (void)startPlaybackOfPath:(NSString *)path
  560. {
  561. APLog(@"Starting playback of %@", path);
  562. if (_receivedFiles == nil)
  563. _receivedFiles = [[NSMutableArray alloc] init];
  564. if ([_receivedFiles containsObject:path])
  565. return;
  566. [_receivedFiles addObject:path];
  567. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  568. BOOL needsMediaList;
  569. VLCMediaList *mediaList = vpc.mediaList;
  570. if (!mediaList) {
  571. mediaList = [[VLCMediaList alloc] init];
  572. needsMediaList = YES;
  573. }
  574. [mediaList addMedia:[VLCMedia mediaWithURL:[NSURL fileURLWithPath:path]]];
  575. if (needsMediaList) {
  576. [vpc playMediaList:mediaList firstIndex:0];
  577. }
  578. VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  579. if (![movieVC isBeingPresented]) {
  580. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:movieVC
  581. animated:YES
  582. completion:nil];
  583. }
  584. }
  585. #endif
  586. //-----------------------------------------------------------------
  587. #pragma mark multipart form data parser delegate
  588. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  589. {
  590. /* in this sample, we are not interested in parts, other then file parts.
  591. * check content disposition to find out filename */
  592. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  593. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  594. if ((nil == filename) || [filename isEqualToString: @""]) {
  595. // it's either not a file part, or
  596. // an empty form sent. we won't handle it.
  597. return;
  598. }
  599. // create the path where to store the media temporarily
  600. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  601. NSString *uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  602. NSFileManager *fileManager = [NSFileManager defaultManager];
  603. BOOL isDir = YES;
  604. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir])
  605. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  606. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  607. NSNumber *freeSpace = [[UIDevice currentDevice] freeDiskspace];
  608. if (_contentLength >= freeSpace.longLongValue) {
  609. /* avoid deadlock since we are on a background thread */
  610. [self performSelectorOnMainThread:@selector(notifyUserAboutEndOfFreeStorage:) withObject:filename waitUntilDone:NO];
  611. [self handleResourceNotFound];
  612. [self stop];
  613. return;
  614. }
  615. APLog(@"Saving file to %@", _filepath);
  616. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  617. APLog(@"Could not create directory at path: %@", _filepath);
  618. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  619. APLog(@"Could not create file at path: %@", _filepath);
  620. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  621. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  622. [activityManager networkActivityStarted];
  623. [activityManager disableIdleTimer];
  624. }
  625. - (void)notifyUserAboutEndOfFreeStorage:(NSString *)filename
  626. {
  627. #if TARGET_OS_IOS
  628. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  629. message:[NSString stringWithFormat:
  630. NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  631. filename,
  632. [[UIDevice currentDevice] model]]
  633. delegate:self
  634. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  635. otherButtonTitles:nil];
  636. [alert show];
  637. #else
  638. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  639. message:[NSString stringWithFormat:
  640. NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  641. filename,
  642. [[UIDevice currentDevice] model]]
  643. preferredStyle:UIAlertControllerStyleAlert];
  644. [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  645. style:UIAlertActionStyleCancel
  646. handler:nil]];
  647. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  648. #endif
  649. }
  650. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  651. {
  652. // here we just write the output from parser to the file.
  653. if (_storeFile) {
  654. @try {
  655. [_storeFile writeData:data];
  656. }
  657. @catch (NSException *exception) {
  658. APLog(@"File to write further data because storage is full.");
  659. [_storeFile closeFile];
  660. _storeFile = nil;
  661. /* don't block */
  662. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  663. }
  664. }
  665. }
  666. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  667. {
  668. // as the file part is over, we close the file.
  669. APLog(@"closing file");
  670. [_storeFile closeFile];
  671. _storeFile = nil;
  672. }
  673. - (BOOL)shouldDie
  674. {
  675. if (_filepath) {
  676. if (_filepath.length > 0) {
  677. [[VLCHTTPUploaderController sharedInstance] moveFileFrom:_filepath];
  678. #if TARGET_OS_TV
  679. [_receivedFiles removeObject:_filepath];
  680. #endif
  681. }
  682. }
  683. return [super shouldDie];
  684. }
  685. #pragma mark subtitle
  686. - (NSMutableArray *)_listOfSubtitles
  687. {
  688. NSMutableArray *listOfSubtitles = [[NSMutableArray alloc] init];
  689. NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  690. NSArray *allFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
  691. NSString *filePath;
  692. NSUInteger count = allFiles.count;
  693. for (NSUInteger i = 0; i < count; i++) {
  694. filePath = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, allFiles[i]] stringByReplacingOccurrencesOfString:@"file://"withString:@""];
  695. if ([filePath isSupportedSubtitleFormat])
  696. [listOfSubtitles addObject:filePath];
  697. }
  698. return listOfSubtitles;
  699. }
  700. - (NSString *)_checkIfSubtitleWasFound:(NSString *)filePath
  701. {
  702. NSString *subtitlePath;
  703. NSString *fileSub;
  704. NSString *currentPath;
  705. NSString *fileName = [[filePath lastPathComponent] stringByDeletingPathExtension];
  706. if (fileName == nil)
  707. return nil;
  708. NSMutableArray *listOfSubtitles = [self _listOfSubtitles];
  709. NSUInteger count = listOfSubtitles.count;
  710. for (NSUInteger i = 0; i < count; i++) {
  711. currentPath = listOfSubtitles[i];
  712. fileSub = [NSString stringWithFormat:@"%@", currentPath];
  713. if ([fileSub rangeOfString:fileName].location != NSNotFound)
  714. subtitlePath = currentPath;
  715. }
  716. return subtitlePath;
  717. }
  718. @end