VLCPlexParser.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*****************************************************************************
  2. * VLCPlexParser.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2014-2019 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. - (NSString *)PlexExtractToken:(NSData *)data
  124. {
  125. NSString *token = @"";
  126. _containerInfo = [[NSMutableArray alloc] init];
  127. _dicoInfo = [[NSMutableDictionary alloc] init];
  128. NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithData:data];
  129. [xmlparser setDelegate:self];
  130. if (![xmlparser parse]) {
  131. NSLog(@"PlexParser data Errors : %@", data);
  132. } else {
  133. token = [[NSArray arrayWithArray:_containerInfo] firstObject][@"token"];
  134. }
  135. return token ? token : @"";
  136. }
  137. #pragma mark - Parser
  138. - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
  139. {
  140. if ([elementName isEqualToString:@"MediaContainer"]) {
  141. if ([attributeDict objectForKey:@"friendlyName"])
  142. [_dicoInfo setObject:[attributeDict objectForKey:@"friendlyName"] forKey:@"libTitle"];
  143. else if ([attributeDict objectForKey:@"title1"])
  144. [_dicoInfo setObject:[attributeDict objectForKey:@"title1"] forKey:@"libTitle"];
  145. if ([attributeDict objectForKey:@"title2"])
  146. [_dicoInfo setObject:[attributeDict objectForKey:@"title2"] forKey:@"libTitle"];
  147. if ([attributeDict objectForKey:@"grandparentTitle"])
  148. [_dicoInfo setObject:[attributeDict objectForKey:@"grandparentTitle"] forKey:@"grandparentTitle"];
  149. } else if ([elementName isEqualToString:@"Directory"]) {
  150. [_dicoInfo setObject:@"directory" forKey:@"container"];
  151. [_dicoInfo setObject:[attributeDict objectForKey:@"key"] forKey:@"key"];
  152. [_dicoInfo setObject:[attributeDict objectForKey:@"title"] forKey:@"title"];
  153. } else if ([elementName isEqualToString:@"Video"] || [elementName isEqualToString:@"Track"]) {
  154. [_dicoInfo setObject:@"item" forKey:@"container"];
  155. [_dicoInfo setObject:[attributeDict objectForKey:@"key"] forKey:@"key"];
  156. [_dicoInfo setObject:[attributeDict objectForKey:@"title"] forKey:@"title"];
  157. [_dicoInfo setObject:[attributeDict objectForKey:@"ratingKey"] forKey:@"ratingKey"];
  158. if ([attributeDict objectForKey:@"summary"])
  159. [_dicoInfo setObject:[attributeDict objectForKey:@"summary"] forKey:@"summary"];
  160. if ([attributeDict objectForKey:@"viewCount"])
  161. [_dicoInfo setObject:@"watched" forKey:@"state"];
  162. else
  163. [_dicoInfo setObject:@"unwatched" forKey:@"state"];
  164. } else if ([elementName isEqualToString:@"Media"]) {
  165. if ([attributeDict objectForKey:@"audioCodec"])
  166. [_dicoInfo setObject:[attributeDict objectForKey:@"audioCodec"] forKey:@"audioCodec"];
  167. if ([attributeDict objectForKey:@"videoCodec"])
  168. [_dicoInfo setObject:[attributeDict objectForKey:@"videoCodec"] forKey:@"videoCodec"];
  169. } else if ([elementName isEqualToString:@"Part"]) {
  170. [_dicoInfo setObject:[NSString stringWithFormat:@"%@%@",_PlexMediaServerUrl, [attributeDict objectForKey:@"key"]] forKey:@"keyMedia"];
  171. if([attributeDict objectForKey:@"file"])
  172. [_dicoInfo setObject:[[attributeDict objectForKey:@"file"] lastPathComponent] forKey:@"namefile"];
  173. NSString *duration = [[VLCTime timeWithNumber:[attributeDict objectForKey:@"duration"]] stringValue];
  174. [_dicoInfo setObject:duration forKey:@"duration"];
  175. NSString *sizeFile = (NSString *)[attributeDict objectForKey:@"size"];
  176. if (sizeFile)
  177. [_dicoInfo setObject:sizeFile forKey:@"size"];
  178. } else if ([elementName isEqualToString:@"Stream"]) {
  179. if ([attributeDict objectForKey:@"key"])
  180. [_dicoInfo setObject:[NSString stringWithFormat:@"%@%@",_PlexMediaServerUrl, [attributeDict objectForKey:@"key"]] forKey:@"keySubtitle"];
  181. if ([attributeDict objectForKey:@"codec"])
  182. [_dicoInfo setObject:[attributeDict objectForKey:@"codec"] forKey:@"codecSubtitle"];
  183. if ([attributeDict objectForKey:@"language"])
  184. [_dicoInfo setObject:[attributeDict objectForKey:@"language"] forKey:@"languageSubtitle"];
  185. if ([attributeDict objectForKey:@"languageCode"])
  186. [_dicoInfo setObject:[attributeDict objectForKey:@"languageCode"] forKey:@"languageCode"];
  187. } else if ([elementName isEqualToString:@"Device"] && [[attributeDict objectForKey:@"name"] isEqualToString:kPlexVLCDeviceName]) {
  188. if ([attributeDict objectForKey:@"name"])
  189. [_dicoInfo setObject:[attributeDict objectForKey:@"name"] forKey:@"name"];
  190. if ([attributeDict objectForKey:@"product"])
  191. [_dicoInfo setObject:[attributeDict objectForKey:@"product"] forKey:@"product"];
  192. if ([attributeDict objectForKey:@"productVersion"])
  193. [_dicoInfo setObject:[attributeDict objectForKey:@"productVersion"] forKey:@"productVersion"];
  194. if ([attributeDict objectForKey:@"platformVersion"])
  195. [_dicoInfo setObject:[attributeDict objectForKey:@"platformVersion"] forKey:@"platformVersion"];
  196. if ([attributeDict objectForKey:@"token"])
  197. [_dicoInfo setObject:[attributeDict objectForKey:@"token"] forKey:@"token"];
  198. if ([attributeDict objectForKey:@"clientIdentifier"])
  199. [_dicoInfo setObject:[attributeDict objectForKey:@"clientIdentifier"] forKey:@"clientIdentifier"];
  200. if ([attributeDict objectForKey:@"id"])
  201. [_dicoInfo setObject:[attributeDict objectForKey:@"id"] forKey:@"id"];
  202. } else if ([elementName isEqualToString:@"user"]) {
  203. if ([attributeDict objectForKey:@"authToken"])
  204. [_dicoInfo setObject:[attributeDict objectForKey:@"authToken"] forKey:@"token"];
  205. if ([attributeDict objectForKey:@"authenticationToken"])
  206. [_dicoInfo setObject:[attributeDict objectForKey:@"authenticationToken"] forKey:@"token"];
  207. }
  208. if ([attributeDict objectForKey:@"thumb"] && ([elementName isEqualToString:@"Video"] || [elementName isEqualToString:@"Directory"] || [elementName isEqualToString:@"Part"] || [elementName isEqualToString:@"Track"]))
  209. [_dicoInfo setObject:[NSString stringWithFormat:@"%@%@", _PlexMediaServerUrl, [attributeDict objectForKey:@"thumb"]] forKey:@"thumb"];
  210. }
  211. - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
  212. {
  213. if (([elementName isEqualToString:@"Video"] || [elementName isEqualToString:@"Track"] || [elementName isEqualToString:@"Directory"] || [elementName isEqualToString:@"MediaContainer"] || [elementName isEqualToString:@"Device"] || [elementName isEqualToString:@"user"]) && [_dicoInfo count] > 0) {
  214. [_containerInfo addObject:_dicoInfo];
  215. _dicoInfo = [[NSMutableDictionary alloc] init];
  216. }
  217. }
  218. - (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
  219. {
  220. NSError __block *erreur = NULL;
  221. NSData __block *data;
  222. BOOL __block reqProcessed = false;
  223. NSURLResponse __block *urlResponse;
  224. [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
  225. urlResponse = _response;
  226. erreur = _error;
  227. data = _data;
  228. reqProcessed = true;
  229. }] resume];
  230. while (!reqProcessed) {
  231. [NSThread sleepForTimeInterval:0];
  232. }
  233. *response = urlResponse;
  234. *error = erreur;
  235. return data;
  236. }
  237. @end