VLCPlexParser.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /*****************************************************************************
  2. * VLCPlexParser.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2014-2017 VideoLAN. All rights reserved.
  6. *
  7. * Authors: Pierre Sagaspe <pierre.sagaspe # me.com>
  8. *
  9. * Refer to the COPYING file of the official project for license.
  10. *****************************************************************************/
  11. #import "VLCPlexParser.h"
  12. #import "VLCPlexWebAPI.h"
  13. #import <XKKeychain/XKKeychainGenericPasswordItem.h>
  14. static NSString *const kPlexMediaServerDirInit = @"/library/sections";
  15. static NSString *const kPlexVLCDeviceName = @"VLC for iOS";
  16. @interface VLCPlexParser () <NSXMLParserDelegate>
  17. {
  18. NSMutableArray *_containerInfo;
  19. NSMutableDictionary *_dicoInfo;
  20. NSString *_PlexMediaServerUrl;
  21. }
  22. @end
  23. @implementation VLCPlexParser
  24. - (NSArray *)PlexMediaServerParser:(NSString *)address port:(NSNumber *)port navigationPath:(NSString *)path authentification:(NSString *)auth error:(NSError *__autoreleasing *)outError
  25. {
  26. _containerInfo = [[NSMutableArray alloc] init];
  27. _dicoInfo = [[NSMutableDictionary alloc] init];
  28. NSURLComponents *urlComponents = [[NSURLComponents alloc] init];
  29. urlComponents.scheme = @"http";
  30. urlComponents.host = address;
  31. urlComponents.port = port;
  32. _PlexMediaServerUrl = [urlComponents URL].absoluteString;
  33. NSString *mediaServerUrl;
  34. if ([path length] == 0) {
  35. urlComponents.path = kPlexMediaServerDirInit;
  36. } else {
  37. if ([path rangeOfString:@"library"].location != NSNotFound) {
  38. urlComponents.path = [@"/" stringByAppendingPathComponent:path];
  39. } else {
  40. urlComponents.path = [kPlexMediaServerDirInit stringByAppendingPathComponent:path];
  41. }
  42. }
  43. mediaServerUrl = [[urlComponents URL].absoluteString stringByRemovingPercentEncoding];
  44. VLCPlexWebAPI *PlexWebAPI = [[VLCPlexWebAPI alloc] init];
  45. NSURL *url = [[NSURL alloc] initWithString:[PlexWebAPI urlAuth:mediaServerUrl authentification:auth]];
  46. NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  47. NSHTTPURLResponse *response = nil;
  48. NSError *error = nil;
  49. NSData *data = [self sendSynchronousRequest:request returningResponse:&response error:&error];
  50. if ([response statusCode] != 200) {
  51. NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  52. if([responseString rangeOfString:@"Unauthorized"].location != NSNotFound) {
  53. NSString *serviceString = [NSString stringWithFormat:@"plex://%@:%@", address, port];
  54. XKKeychainGenericPasswordItem *keychainItem = [XKKeychainGenericPasswordItem itemsForService:serviceString error:nil].firstObject;
  55. if (!keychainItem) {
  56. serviceString = [NSString stringWithFormat:@"plex://Account:%@", port];
  57. keychainItem = [XKKeychainGenericPasswordItem itemsForService:serviceString error:nil].firstObject;
  58. }
  59. if (keychainItem) {
  60. NSString *username = keychainItem.account;
  61. NSString *password = keychainItem.secret.stringValue;
  62. auth = [PlexWebAPI PlexAuthentification:username password:password];
  63. url = [NSURL URLWithString:[PlexWebAPI urlAuth:mediaServerUrl authentification:auth]];
  64. request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  65. response = nil;
  66. error = nil;
  67. data = [self sendSynchronousRequest:request returningResponse:&response error:&error];
  68. if ([response statusCode] != 200) {
  69. if (outError) {
  70. NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:
  71. @{
  72. NSLocalizedDescriptionKey : NSLocalizedString(@"PLEX_ERROR_ACCOUNT", nil),
  73. NSLocalizedFailureReasonErrorKey : NSLocalizedString(@"PLEX_CHECK_ACCOUNT", nil),
  74. }];
  75. if (error) {
  76. userInfo[NSUnderlyingErrorKey] = error;
  77. }
  78. *outError = [NSError errorWithDomain:@"org.videolan.vlc-ios.plexParser"
  79. code:response.statusCode
  80. userInfo:userInfo];
  81. }
  82. }
  83. [_containerInfo removeAllObjects];
  84. [_dicoInfo removeAllObjects];
  85. } else {
  86. if (outError) {
  87. NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:
  88. @{
  89. NSLocalizedDescriptionKey : NSLocalizedString(@"UNAUTHORIZED", nil),
  90. NSLocalizedFailureReasonErrorKey : NSLocalizedString(@"PLEX_CHECK_ACCOUNT", nil),
  91. }];
  92. if (error) {
  93. userInfo[NSUnderlyingErrorKey] = error;
  94. }
  95. *outError = [NSError errorWithDomain:@"org.videolan.vlc-ios.plexParser"
  96. code:response.statusCode
  97. userInfo:userInfo];
  98. }
  99. }
  100. } else
  101. APLog(@"PlexParser url Errors : %ld", (long)[response statusCode]);
  102. }
  103. if (error) {
  104. APLog(@"PlexParser url Error: %@", error);
  105. }
  106. NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithData:data];
  107. [xmlparser setDelegate:self];
  108. if (![xmlparser parse])
  109. APLog(@"PlexParser url Errors : %@", url);
  110. [_containerInfo setValue:auth forKey:@"authentification"];
  111. return [NSArray arrayWithArray:_containerInfo];
  112. }
  113. - (NSArray *)PlexExtractDeviceInfo:(NSData *)data
  114. {
  115. _containerInfo = [[NSMutableArray alloc] init];
  116. _dicoInfo = [[NSMutableDictionary alloc] init];
  117. NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithData:data];
  118. [xmlparser setDelegate:self];
  119. if (![xmlparser parse])
  120. APLog(@"PlexParser data Errors : %@", data);
  121. return [NSArray arrayWithArray:_containerInfo];
  122. }
  123. #pragma mark - Parser
  124. - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
  125. {
  126. if ([elementName isEqualToString:@"MediaContainer"]) {
  127. if ([attributeDict objectForKey:@"friendlyName"])
  128. [_dicoInfo setObject:[attributeDict objectForKey:@"friendlyName"] forKey:@"libTitle"];
  129. else if ([attributeDict objectForKey:@"title1"])
  130. [_dicoInfo setObject:[attributeDict objectForKey:@"title1"] forKey:@"libTitle"];
  131. if ([attributeDict objectForKey:@"title2"])
  132. [_dicoInfo setObject:[attributeDict objectForKey:@"title2"] forKey:@"libTitle"];
  133. if ([attributeDict objectForKey:@"grandparentTitle"])
  134. [_dicoInfo setObject:[attributeDict objectForKey:@"grandparentTitle"] forKey:@"grandparentTitle"];
  135. } else if ([elementName isEqualToString:@"Directory"]) {
  136. [_dicoInfo setObject:@"directory" forKey:@"container"];
  137. [_dicoInfo setObject:[attributeDict objectForKey:@"key"] forKey:@"key"];
  138. [_dicoInfo setObject:[attributeDict objectForKey:@"title"] forKey:@"title"];
  139. } else if ([elementName isEqualToString:@"Video"] || [elementName isEqualToString:@"Track"]) {
  140. [_dicoInfo setObject:@"item" forKey:@"container"];
  141. [_dicoInfo setObject:[attributeDict objectForKey:@"key"] forKey:@"key"];
  142. [_dicoInfo setObject:[attributeDict objectForKey:@"title"] forKey:@"title"];
  143. [_dicoInfo setObject:[attributeDict objectForKey:@"ratingKey"] forKey:@"ratingKey"];
  144. if ([attributeDict objectForKey:@"summary"])
  145. [_dicoInfo setObject:[attributeDict objectForKey:@"summary"] forKey:@"summary"];
  146. if ([attributeDict objectForKey:@"viewCount"])
  147. [_dicoInfo setObject:@"watched" forKey:@"state"];
  148. else
  149. [_dicoInfo setObject:@"unwatched" forKey:@"state"];
  150. } else if ([elementName isEqualToString:@"Media"]) {
  151. if ([attributeDict objectForKey:@"audioCodec"])
  152. [_dicoInfo setObject:[attributeDict objectForKey:@"audioCodec"] forKey:@"audioCodec"];
  153. if ([attributeDict objectForKey:@"videoCodec"])
  154. [_dicoInfo setObject:[attributeDict objectForKey:@"videoCodec"] forKey:@"videoCodec"];
  155. } else if ([elementName isEqualToString:@"Part"]) {
  156. [_dicoInfo setObject:[NSString stringWithFormat:@"%@%@",_PlexMediaServerUrl, [attributeDict objectForKey:@"key"]] forKey:@"keyMedia"];
  157. if([attributeDict objectForKey:@"file"])
  158. [_dicoInfo setObject:[[attributeDict objectForKey:@"file"] lastPathComponent] forKey:@"namefile"];
  159. NSString *duration = [[VLCTime timeWithNumber:[attributeDict objectForKey:@"duration"]] stringValue];
  160. [_dicoInfo setObject:duration forKey:@"duration"];
  161. NSString *sizeFile = (NSString *)[attributeDict objectForKey:@"size"];
  162. if (sizeFile)
  163. [_dicoInfo setObject:sizeFile forKey:@"size"];
  164. } else if ([elementName isEqualToString:@"Stream"]) {
  165. if ([attributeDict objectForKey:@"key"])
  166. [_dicoInfo setObject:[NSString stringWithFormat:@"%@%@",_PlexMediaServerUrl, [attributeDict objectForKey:@"key"]] forKey:@"keySubtitle"];
  167. if ([attributeDict objectForKey:@"codec"])
  168. [_dicoInfo setObject:[attributeDict objectForKey:@"codec"] forKey:@"codecSubtitle"];
  169. if ([attributeDict objectForKey:@"language"])
  170. [_dicoInfo setObject:[attributeDict objectForKey:@"language"] forKey:@"languageSubtitle"];
  171. if ([attributeDict objectForKey:@"languageCode"])
  172. [_dicoInfo setObject:[attributeDict objectForKey:@"languageCode"] forKey:@"languageCode"];
  173. } else if ([elementName isEqualToString:@"Device"] && [[attributeDict objectForKey:@"name"] isEqualToString:kPlexVLCDeviceName]) {
  174. if ([attributeDict objectForKey:@"name"])
  175. [_dicoInfo setObject:[attributeDict objectForKey:@"name"] forKey:@"name"];
  176. if ([attributeDict objectForKey:@"product"])
  177. [_dicoInfo setObject:[attributeDict objectForKey:@"product"] forKey:@"product"];
  178. if ([attributeDict objectForKey:@"productVersion"])
  179. [_dicoInfo setObject:[attributeDict objectForKey:@"productVersion"] forKey:@"productVersion"];
  180. if ([attributeDict objectForKey:@"platformVersion"])
  181. [_dicoInfo setObject:[attributeDict objectForKey:@"platformVersion"] forKey:@"platformVersion"];
  182. if ([attributeDict objectForKey:@"token"])
  183. [_dicoInfo setObject:[attributeDict objectForKey:@"token"] forKey:@"token"];
  184. if ([attributeDict objectForKey:@"clientIdentifier"])
  185. [_dicoInfo setObject:[attributeDict objectForKey:@"clientIdentifier"] forKey:@"clientIdentifier"];
  186. if ([attributeDict objectForKey:@"id"])
  187. [_dicoInfo setObject:[attributeDict objectForKey:@"id"] forKey:@"id"];
  188. }
  189. if ([attributeDict objectForKey:@"thumb"] && ([elementName isEqualToString:@"Video"] || [elementName isEqualToString:@"Directory"] || [elementName isEqualToString:@"Part"] || [elementName isEqualToString:@"Track"]))
  190. [_dicoInfo setObject:[NSString stringWithFormat:@"%@%@", _PlexMediaServerUrl, [attributeDict objectForKey:@"thumb"]] forKey:@"thumb"];
  191. }
  192. - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
  193. {
  194. if (([elementName isEqualToString:@"Video"] || [elementName isEqualToString:@"Track"] || [elementName isEqualToString:@"Directory"] || [elementName isEqualToString:@"MediaContainer"] || [elementName isEqualToString:@"Device"]) && [_dicoInfo count] > 0) {
  195. [_containerInfo addObject:_dicoInfo];
  196. _dicoInfo = [[NSMutableDictionary alloc] init];
  197. }
  198. }
  199. - (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
  200. {
  201. NSError __block *erreur = NULL;
  202. NSData __block *data;
  203. BOOL __block reqProcessed = false;
  204. NSURLResponse __block *urlResponse;
  205. [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
  206. urlResponse = _response;
  207. erreur = _error;
  208. data = _data;
  209. reqProcessed = true;
  210. }] resume];
  211. while (!reqProcessed) {
  212. [NSThread sleepForTimeInterval:0];
  213. }
  214. *response = urlResponse;
  215. *error = erreur;
  216. return data;
  217. }
  218. @end