VLCPlexWebAPI.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. /*****************************************************************************
  2. * VLCPlexWebAPI.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 "VLCPlexWebAPI.h"
  12. #import "VLCPlexParser.h"
  13. #import "UIDevice+VLC.h"
  14. #import "sysexits.h"
  15. #define kPlexMediaServerSignIn @"https://plex.tv/users/sign_in.xml"
  16. //#define kPlexMediaServerSignIn @"https://plex.tv/users/sign_in.json"
  17. #define kPlexURLdeviceInfo @"https://plex.tv/devices.xml"
  18. @implementation VLCPlexWebAPI
  19. #pragma mark - Authentification
  20. - (NSMutableDictionary *)PlexBasicAuthentification:(NSString *)username password:(NSString *)password
  21. {
  22. NSURL *url = [NSURL URLWithString:kPlexMediaServerSignIn];
  23. NSString *appVersion = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
  24. NSMutableDictionary *authDict = [NSMutableDictionary dictionary];
  25. NSString *clientIdentifier = [NSString stringWithFormat:@"PlexVLC-%@", [[UIDevice currentDevice] model]];
  26. [authDict setObject:clientIdentifier forKey:@"clientIdentifier"];
  27. [authDict setObject:@"PlexVLC" forKey:@"product"];
  28. [authDict setObject:appVersion forKey:@"productVersion"];
  29. [authDict setObject:[[UIDevice currentDevice] model] forKey:@"device"];
  30. [authDict setObject:@"" forKey:@"token"];
  31. [authDict setObject:@"VLC for iOS" forKey:@"name"];
  32. [authDict setObject:username forKey:@"username"];
  33. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
  34. if ([cookies count]) {
  35. for (NSHTTPCookie *cookie in cookies) {
  36. if ([cookie.name isEqualToString:@"plexToken"]) {
  37. [authDict setObject:cookie.value forKey:@"token"];
  38. return authDict;
  39. }
  40. }
  41. }
  42. NSString *authString = [NSString stringWithFormat:@"%@:%@", username, password];
  43. NSData *authData = [authString dataUsingEncoding:NSASCIIStringEncoding];
  44. NSString *authBase64 = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];
  45. NSString *timeString = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  46. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  47. [request setHTTPMethod:@"POST"];
  48. [request setValue:authBase64 forHTTPHeaderField:@"Authorization"];
  49. [request setValue:[authDict objectForKey:@"device"] forHTTPHeaderField:@"X-Plex-Device"];
  50. [request setValue:[authDict objectForKey:@"name"] forHTTPHeaderField:@"X-Plex-Device-Name"];
  51. [request setValue:[authDict objectForKey:@"clientIdentifier"] forHTTPHeaderField:@"X-Plex-Client-Identifier"];
  52. [request setValue:[authDict objectForKey:@"product"] forHTTPHeaderField:@"X-Plex-Product"];
  53. [request setValue:appVersion forHTTPHeaderField:@"X-Plex-Version"];
  54. [request setValue:timeString forHTTPHeaderField:@"X-Plex-Access-Time"];
  55. NSHTTPURLResponse *response = nil;
  56. NSError *error = nil;
  57. NSData *data = [self sendSynchronousRequest:request returningResponse:&response error:&error];
  58. // for debug
  59. /*if ([response statusCode] == 201) {
  60. NSLog(@"Plex token : %@", [response allHeaderFields]);
  61. NSLog(@"Plex token : %@", [NSString stringWithUTF8String:[data bytes]]);
  62. } else {
  63. NSLog(@"%ld", (long)response.statusCode);
  64. NSLog(@"Plex Create Identification Error : %@", [response allHeaderFields]);
  65. NSLog(@"Plex token error : %@", [NSString stringWithUTF8String:[data bytes]]);
  66. }*/
  67. VLCPlexParser *plexParser = [[VLCPlexParser alloc] init];
  68. NSString *token = [plexParser PlexExtractToken:data];
  69. if (![token isEqualToString:@""]) {
  70. [authDict setObject:token forKey:@"token"];
  71. NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
  72. [cookieProperties setObject:@"plexToken" forKey:NSHTTPCookieName];
  73. [cookieProperties setObject:[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]] forKey:NSHTTPCookieValue];
  74. [cookieProperties setObject:@"plex.tv" forKey:NSHTTPCookieDomain];
  75. [cookieProperties setObject:kPlexMediaServerSignIn forKey:NSHTTPCookieOriginURL];
  76. [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
  77. [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
  78. [cookieProperties setObject:token forKey:NSHTTPCookieValue];
  79. NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
  80. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
  81. }
  82. return authDict;
  83. }
  84. - (NSString *)PlexAuthentification:(NSString *)username password:(NSString *)password
  85. {
  86. NSString *authentification = @"";
  87. if ((![username isEqualToString:@""]) && (![password isEqualToString:@""])) {
  88. NSDictionary *authDict = [self PlexBasicAuthentification:username password:password];
  89. if (![[authDict objectForKey:@"token"] isEqualToString:@""]) {
  90. authentification = [[NSString stringWithFormat:@"X-Plex-Product=%@&X-Plex-Version=%@&X-Plex-Client-Identifier=%@&X-Plex-Device=%@&X-Plex-Token=%@&X-Plex-Username=%@",
  91. [authDict objectForKey:@"product"],
  92. [authDict objectForKey:@"productVersion"],
  93. [authDict objectForKey:@"clientIdentifier"],
  94. [authDict objectForKey:@"device"],
  95. [authDict objectForKey:@"token"], username]
  96. stringByReplacingOccurrencesOfString:@" " withString:@"+"];
  97. }
  98. }
  99. return authentification;
  100. }
  101. - (NSString *)urlAuth:(NSString *)url authentification:(NSString *)auth
  102. {
  103. return [[self class] urlAuth:url authentification:auth];
  104. }
  105. + (NSString *)urlAuth:(NSString *)url authentification:(NSString *)auth
  106. {
  107. NSString *key = @"";
  108. if ((![auth isEqualToString:@""]) && (auth)) {
  109. NSRange isRange = [url rangeOfString:@"?" options:NSCaseInsensitiveSearch];
  110. if(isRange.location != NSNotFound)
  111. key = @"&";
  112. else
  113. key = @"?";
  114. }
  115. return [NSString stringWithFormat:@"%@%@%@", url, key, auth];
  116. }
  117. #pragma mark - Unofficial API
  118. - (NSInteger)MarkWatchedUnwatchedMedia:(NSString *)adress port:(NSString *)port videoRatingKey:(NSString *)ratingKey state:(NSString *)state authentification:(NSString *)auth
  119. {
  120. NSString *url = nil;
  121. if ([state isEqualToString:@"watched"])
  122. url = [NSString stringWithFormat:@"http://%@%@/:/unscrobble?identifier=com.plexapp.plugins.library&key=%@", adress, port, ratingKey];
  123. else
  124. url = [NSString stringWithFormat:@"http://%@%@/:/scrobble?identifier=com.plexapp.plugins.library&key=%@", adress, port, ratingKey];
  125. NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[[[VLCPlexWebAPI alloc] init] urlAuth:url authentification:auth]] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:20];
  126. NSURLResponse *response = nil;
  127. NSError *error = nil;
  128. [self sendSynchronousRequest:request returningResponse:&response error:&error];
  129. NSInteger httpStatus = [(NSHTTPURLResponse *)response statusCode];
  130. if (httpStatus != 200)
  131. APLog(@"Mark Watched Unwatched Media Error status: %ld at URL : %@", (long)httpStatus, url);
  132. return httpStatus;
  133. }
  134. - (NSString *)getFileSubtitleFromPlexServer:(NSDictionary *)mediaObject modeStream:(BOOL)modeStream error:(NSError *__autoreleasing *)outError
  135. {
  136. if (!mediaObject)
  137. return @"";
  138. NSString *FileSubtitlePath = nil;
  139. NSString *fileName = [[mediaObject[@"namefile"] stringByDeletingPathExtension] stringByAppendingPathExtension:mediaObject[@"codecSubtitle"]];
  140. VLCPlexWebAPI *PlexWebAPI = [[VLCPlexWebAPI alloc] init];
  141. NSURL *url = [[NSURL alloc] initWithString:[PlexWebAPI urlAuth:mediaObject[@"keySubtitle"] authentification:mediaObject[@"authentification"]]];
  142. NSData *receivedSub = [NSData dataWithContentsOfURL:url];
  143. if (receivedSub.length < [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) {
  144. NSArray *searchPaths = nil;
  145. if (modeStream)
  146. searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  147. else
  148. searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  149. NSString *directoryPath = [searchPaths objectAtIndex:0];
  150. FileSubtitlePath = [directoryPath stringByAppendingPathComponent:fileName];
  151. NSFileManager *fileManager = [NSFileManager defaultManager];
  152. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  153. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  154. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  155. APLog(@"file creation failed, no data was saved");
  156. }
  157. [receivedSub writeToFile:FileSubtitlePath atomically:YES];
  158. } else {
  159. NSString *title = NSLocalizedString(@"DISK_FULL", nil);
  160. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), fileName, [[UIDevice currentDevice] model]];
  161. if (outError) {
  162. *outError = [NSError errorWithDomain:@"org.videolan.vlc-ios.plex"
  163. code:EX_CANTCREAT
  164. userInfo:@{NSLocalizedDescriptionKey : title,
  165. NSLocalizedFailureReasonErrorKey : message
  166. }];
  167. }
  168. }
  169. return FileSubtitlePath;
  170. }
  171. - (void)stopSession:(NSString *)adress port:(NSString *)port session:(NSString *)session
  172. {
  173. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@/video/:/transcode/universal/stop?session=%@", adress, port, session]];
  174. NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  175. NSHTTPURLResponse *response = nil;
  176. NSError *error = nil;
  177. [self sendSynchronousRequest:request returningResponse:&response error:&error];
  178. if ([response statusCode] != 200)
  179. APLog(@"Plex stop Session %@ : %@", session, [response allHeaderFields]);
  180. }
  181. #pragma mark -
  182. - (NSString *)getSession
  183. {
  184. NSString *session = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  185. return session;
  186. }
  187. - (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
  188. {
  189. NSError __block *erreur = NULL;
  190. NSData __block *data;
  191. BOOL __block reqProcessed = false;
  192. NSURLResponse __block *urlResponse;
  193. [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
  194. urlResponse = _response;
  195. erreur = _error;
  196. data = _data;
  197. reqProcessed = true;
  198. }] resume];
  199. while (!reqProcessed) {
  200. [NSThread sleepForTimeInterval:0];
  201. }
  202. *response = urlResponse;
  203. *error = erreur;
  204. return data;
  205. }
  206. @end