VLCPlexWebAPI.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*****************************************************************************
  2. * VLCPlexWebAPI.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 "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 kPlexURLdeviceInfo @"https://plex.tv/devices.xml"
  17. @implementation VLCPlexWebAPI
  18. #pragma mark - Authentification
  19. - (NSArray *)PlexBasicAuthentification:(NSString *)username password:(NSString *)password
  20. {
  21. NSArray *authToken = nil;
  22. NSURL *url = [NSURL URLWithString:kPlexMediaServerSignIn];
  23. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
  24. if ([cookies count])
  25. return cookies;
  26. NSString *authString = [NSString stringWithFormat:@"%@:%@", username, password];
  27. NSData *authData = [authString dataUsingEncoding:NSASCIIStringEncoding];
  28. NSString *authBase64 = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];
  29. NSString *timeString = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  30. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  31. [request setHTTPMethod:@"POST"];
  32. [request setValue:authBase64 forHTTPHeaderField:@"Authorization"];
  33. [request setValue:timeString forHTTPHeaderField:@"X-Plex-Access-Time"];
  34. NSHTTPURLResponse *response = nil;
  35. NSError *error = nil;
  36. [self sendSynchronousRequest:request returningResponse:&response error:&error];
  37. authToken = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@""]];
  38. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:authToken forURL:url mainDocumentURL:nil];
  39. return authToken;
  40. }
  41. - (BOOL)PlexCreateIdentification:(NSString *)username password:(NSString *)password
  42. {
  43. NSURL *url = [NSURL URLWithString:kPlexMediaServerSignIn];
  44. NSString *authString = [NSString stringWithFormat:@"%@:%@", username, password];
  45. NSData *authData = [authString dataUsingEncoding:NSASCIIStringEncoding];
  46. NSString *authBase64 = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];
  47. NSString *appVersion = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
  48. NSString *timeString = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  49. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  50. [request setHTTPMethod:@"POST"];
  51. [request setValue:authBase64 forHTTPHeaderField:@"Authorization"];
  52. [request setValue:@"iOS" forHTTPHeaderField:@"X-Plex-Platform"];
  53. [request setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"X-Plex-Platform-Version"];
  54. [request setValue:@"client" forHTTPHeaderField:@"X-Plex-Provides"];
  55. [request setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forHTTPHeaderField:@"X-Plex-Client-Identifier"];
  56. [request setValue:@"PlexVLC" forHTTPHeaderField:@"X-Plex-Product"];
  57. [request setValue:appVersion forHTTPHeaderField:@"X-Plex-Version"];
  58. [request setValue:@"VLC for iOS" forHTTPHeaderField:@"X-Plex-Device-Name"];
  59. [request setValue:[[UIDevice currentDevice] model] forHTTPHeaderField:@"X-Plex-Device"];
  60. [request setValue:timeString forHTTPHeaderField:@"X-Plex-Access-Time"];
  61. NSHTTPURLResponse *response = nil;
  62. NSError *error = nil;
  63. [self sendSynchronousRequest:request returningResponse:&response error:&error];
  64. if ([response statusCode] == 201)
  65. return YES;
  66. else {
  67. APLog(@"Plex Create Identification Error : %@", [response allHeaderFields]);
  68. return NO;
  69. }
  70. }
  71. - (NSData *)HttpRequestWithCookie:(NSURL *)url cookies:(NSArray *)authToken HTTPMethod:(NSString *)method
  72. {
  73. NSString *timeString = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  74. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  75. NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:authToken];
  76. [request setHTTPMethod:method];
  77. [request setAllHTTPHeaderFields:headers];
  78. [request setValue:timeString forHTTPHeaderField:@"X-Plex-Access-Time"];
  79. NSHTTPURLResponse *response = nil;
  80. NSError *error = nil;
  81. NSData *urlData = [self sendSynchronousRequest:request returningResponse:&response error:&error];
  82. // for debug
  83. //NSString *debugStr = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
  84. //APLog(@"data : %@", debugStr);
  85. return urlData;
  86. }
  87. - (NSString *)PlexAuthentification:(NSString *)username password:(NSString *)password
  88. {
  89. NSString *authentification = @"";
  90. if ((![username isEqualToString:@""]) && (![password isEqualToString:@""])) {
  91. NSArray *deviceInfo;
  92. NSString *appVersion = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
  93. NSArray *authToken = [self PlexBasicAuthentification:username password:password];
  94. NSData *data = [self PlexDeviceInfo:authToken];
  95. VLCPlexParser *plexParser = [[VLCPlexParser alloc] init];
  96. deviceInfo = [plexParser PlexExtractDeviceInfo:data];
  97. NSDictionary *firstObject = [deviceInfo firstObject];
  98. if ((deviceInfo.count == 0) ||
  99. ((![firstObject[@"productVersion"] isEqualToString:appVersion]) ||
  100. (![firstObject[@"platformVersion"] isEqualToString:[[UIDevice currentDevice] systemVersion]]))) {
  101. [self PlexCreateIdentification:username password:password];
  102. data = [self PlexDeviceInfo:authToken];
  103. deviceInfo = [plexParser PlexExtractDeviceInfo:data];
  104. }
  105. if (deviceInfo.count != 0) {
  106. firstObject = [deviceInfo firstObject];
  107. UIDevice *currentDevice = [UIDevice currentDevice];
  108. authentification = [[NSString stringWithFormat:@"X-Plex-Product=%@&X-Plex-Version=%@&X-Plex-Client-Identifier=%@&X-Plex-Platform=iOS&X-Plex-Platform-Version=%@&X-Plex-Device=%@&X-Plex-Device-Name=%@&X-Plex-Token=%@&X-Plex-Username=%@",
  109. firstObject[@"product"],
  110. firstObject[@"productVersion"],
  111. firstObject[@"clientIdentifier"],
  112. [currentDevice systemVersion],
  113. [currentDevice model],
  114. firstObject[@"name"],
  115. firstObject[@"token"], username]
  116. stringByReplacingOccurrencesOfString:@" " withString:@"+"];
  117. }
  118. }
  119. return authentification;
  120. }
  121. - (NSString *)urlAuth:(NSString *)url authentification:(NSString *)auth {
  122. return [[self class] urlAuth:url authentification:auth];
  123. }
  124. + (NSString *)urlAuth:(NSString *)url authentification:(NSString *)auth
  125. {
  126. NSString *key = @"";
  127. if (![auth isEqualToString:@""]) {
  128. NSRange isRange = [url rangeOfString:@"?" options:NSCaseInsensitiveSearch];
  129. if(isRange.location != NSNotFound)
  130. key = @"&";
  131. else
  132. key = @"?";
  133. }
  134. return [NSString stringWithFormat:@"%@%@%@", url, key, auth];
  135. }
  136. #pragma mark - Unofficial API
  137. - (NSInteger)MarkWatchedUnwatchedMedia:(NSString *)adress port:(NSString *)port videoRatingKey:(NSString *)ratingKey state:(NSString *)state authentification:(NSString *)auth
  138. {
  139. NSString *url = nil;
  140. if ([state isEqualToString:@"watched"])
  141. url = [NSString stringWithFormat:@"http://%@%@/:/unscrobble?identifier=com.plexapp.plugins.library&key=%@", adress, port, ratingKey];
  142. else
  143. url = [NSString stringWithFormat:@"http://%@%@/:/scrobble?identifier=com.plexapp.plugins.library&key=%@", adress, port, ratingKey];
  144. NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[[[VLCPlexWebAPI alloc] init] urlAuth:url authentification:auth]] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:20];
  145. NSURLResponse *response = nil;
  146. NSError *error = nil;
  147. [self sendSynchronousRequest:request returningResponse:&response error:&error];
  148. NSInteger httpStatus = [(NSHTTPURLResponse *)response statusCode];
  149. if (httpStatus != 200)
  150. APLog(@"Mark Watched Unwatched Media Error status: %ld at URL : %@", (long)httpStatus, url);
  151. return httpStatus;
  152. }
  153. - (NSString *)getFileSubtitleFromPlexServer:(NSDictionary *)mediaObject modeStream:(BOOL)modeStream error:(NSError *__autoreleasing *)outError
  154. {
  155. if (!mediaObject)
  156. return @"";
  157. NSString *FileSubtitlePath = nil;
  158. NSString *fileName = [[mediaObject[@"namefile"] stringByDeletingPathExtension] stringByAppendingPathExtension:mediaObject[@"codecSubtitle"]];
  159. VLCPlexWebAPI *PlexWebAPI = [[VLCPlexWebAPI alloc] init];
  160. NSURL *url = [[NSURL alloc] initWithString:[PlexWebAPI urlAuth:mediaObject[@"keySubtitle"] authentification:mediaObject[@"authentification"]]];
  161. NSData *receivedSub = [NSData dataWithContentsOfURL:url];
  162. if (receivedSub.length < [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) {
  163. NSArray *searchPaths = nil;
  164. if (modeStream)
  165. searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  166. else
  167. searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  168. NSString *directoryPath = [searchPaths objectAtIndex:0];
  169. FileSubtitlePath = [directoryPath stringByAppendingPathComponent:fileName];
  170. NSFileManager *fileManager = [NSFileManager defaultManager];
  171. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  172. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  173. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  174. APLog(@"file creation failed, no data was saved");
  175. }
  176. [receivedSub writeToFile:FileSubtitlePath atomically:YES];
  177. } else {
  178. NSString *title = NSLocalizedString(@"DISK_FULL", nil);
  179. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), fileName, [[UIDevice currentDevice] model]];
  180. if (outError) {
  181. *outError = [NSError errorWithDomain:@"org.videolan.vlc-ios.plex"
  182. code:EX_CANTCREAT
  183. userInfo:@{NSLocalizedDescriptionKey : title,
  184. NSLocalizedFailureReasonErrorKey : message
  185. }];
  186. }
  187. }
  188. return FileSubtitlePath;
  189. }
  190. - (NSURL *)CreatePlexStreamingURL:(NSString *)address port:(NSString *)port videoKey:(NSString *)key username:(NSString *)username deviceInfo:(NSDictionary *)deviceInfo session:(NSString *)session
  191. {
  192. /* it starts video transcoding but without sound !!! why ? */
  193. UIDevice *currentDevice = [UIDevice currentDevice];
  194. NSString *authentification = [[NSString stringWithFormat:@"&X-Plex-Product=%@&X-Plex-Version=%@&X-Plex-Client-Identifier=%@&X-Plex-Platform=iOS&X-Plex-Platform-Version=%@&X-Plex-Device=%@&X-Plex-Device-Name=%@&X-Plex-Token=%@&X-Plex-Username=%@",
  195. deviceInfo[@"product"],
  196. deviceInfo[@"productVersion"],
  197. deviceInfo[@"clientIdentifier"],
  198. [currentDevice systemVersion],
  199. [currentDevice model],
  200. deviceInfo[@"name"],
  201. deviceInfo[@"token"], username]
  202. stringByReplacingOccurrencesOfString:@" " withString:@"+"];
  203. NSString *unescaped = [NSString stringWithFormat:@"http://127.0.0.1:32400%@", key];
  204. NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
  205. NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"http://%@%@/video/:/transcode/universal/start.m3u8?path=%@&mediaIndex=0&partIndex=0&protocol=hls&offset=0&fastSeek=1&directPlay=0&directStream=1&subtitleSize=100&audioBoost=100&session=%@&subtitles=burn",
  206. address,
  207. port,
  208. escapedString,
  209. session] stringByAppendingString:authentification]];
  210. return url;
  211. }
  212. - (void)stopSession:(NSString *)adress port:(NSString *)port session:(NSString *)session
  213. {
  214. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@/video/:/transcode/universal/stop?session=%@", adress, port, session]];
  215. NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  216. NSHTTPURLResponse *response = nil;
  217. NSError *error = nil;
  218. [self sendSynchronousRequest:request returningResponse:&response error:&error];
  219. if ([response statusCode] != 200)
  220. APLog(@"Plex stop Session %@ : %@", session, [response allHeaderFields]);
  221. }
  222. #pragma mark -
  223. - (NSString *)getSession
  224. {
  225. NSString *session = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  226. return session;
  227. }
  228. - (NSData *)PlexDeviceInfo:(NSArray *)cookies
  229. {
  230. NSURL *url = [NSURL URLWithString:kPlexURLdeviceInfo];
  231. NSData *data = [self HttpRequestWithCookie:url cookies:cookies HTTPMethod:@"GET"];
  232. return data;
  233. }
  234. - (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
  235. {
  236. NSError __block *erreur = NULL;
  237. NSData __block *data;
  238. BOOL __block reqProcessed = false;
  239. NSURLResponse __block *urlResponse;
  240. [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
  241. urlResponse = _response;
  242. erreur = _error;
  243. data = _data;
  244. reqProcessed = true;
  245. }] resume];
  246. while (!reqProcessed) {
  247. [NSThread sleepForTimeInterval:0];
  248. }
  249. *response = urlResponse;
  250. *error = erreur;
  251. return data;
  252. }
  253. @end