VLCPlexWebAPI.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /*****************************************************************************
  2. * VLCPlexWebAPI.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2014-2015 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. #define kPlexMediaServerSignIn @"https://plex.tv/users/sign_in.xml"
  15. #define kPlexURLdeviceInfo @"https://plex.tv/devices.xml"
  16. @interface VLCPlexWebAPI ()
  17. {
  18. }
  19. @end
  20. @implementation VLCPlexWebAPI
  21. #pragma mark - Authentification
  22. - (NSArray *)PlexBasicAuthentification:(NSString *)username password:(NSString *)password
  23. {
  24. NSArray *authToken = nil;
  25. NSURL *url = [NSURL URLWithString:kPlexMediaServerSignIn];
  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. [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  37. authToken = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@""]];
  38. return authToken;
  39. }
  40. - (BOOL)PlexCreateIdentification:(NSString *)username password:(NSString *)password
  41. {
  42. NSURL *url = [NSURL URLWithString:kPlexMediaServerSignIn];
  43. NSString *authString = [NSString stringWithFormat:@"%@:%@", username, password];
  44. NSData *authData = [authString dataUsingEncoding:NSASCIIStringEncoding];
  45. NSString *authBase64 = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];
  46. NSString *appVersion = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
  47. NSString *timeString = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  48. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  49. [request setHTTPMethod:@"POST"];
  50. [request setValue:authBase64 forHTTPHeaderField:@"Authorization"];
  51. [request setValue:@"iOS" forHTTPHeaderField:@"X-Plex-Platform"];
  52. [request setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"X-Plex-Platform-Version"];
  53. [request setValue:@"client" forHTTPHeaderField:@"X-Plex-Provides"];
  54. [request setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forHTTPHeaderField:@"X-Plex-Client-Identifier"];
  55. [request setValue:@"PlexVLC" forHTTPHeaderField:@"X-Plex-Product"];
  56. [request setValue:appVersion forHTTPHeaderField:@"X-Plex-Version"];
  57. [request setValue:@"VLC for iOS" forHTTPHeaderField:@"X-Plex-Device-Name"];
  58. [request setValue:[[UIDevice currentDevice] model] forHTTPHeaderField:@"X-Plex-Device"];
  59. [request setValue:timeString forHTTPHeaderField:@"X-Plex-Access-Time"];
  60. NSHTTPURLResponse *response = nil;
  61. NSError *error = nil;
  62. [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  63. if ([response statusCode] == 201)
  64. return YES;
  65. else {
  66. APLog(@"Plex Create Identification Error : %@", [response allHeaderFields]);
  67. return NO;
  68. }
  69. }
  70. - (NSData *)HttpRequestWithCookie:(NSURL *)url cookies:(NSArray *)authToken HTTPMethod:(NSString *)method
  71. {
  72. NSString *timeString = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  73. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  74. NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:authToken];
  75. [request setHTTPMethod:method];
  76. [request setAllHTTPHeaderFields:headers];
  77. [request setValue:timeString forHTTPHeaderField:@"X-Plex-Access-Time"];
  78. NSHTTPURLResponse *response = nil;
  79. NSError *error = nil;
  80. NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  81. // for debug
  82. //NSString *debugStr = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
  83. //APLog(@"data : %@", debugStr);
  84. return urlData;
  85. }
  86. - (NSString *)PlexAuthentification:(NSString *)username password:(NSString *)password
  87. {
  88. NSString *authentification = @"";
  89. if ((![username isEqualToString:@""]) && (![password isEqualToString:@""])) {
  90. NSMutableArray *deviceInfo = [[NSMutableArray alloc] init];
  91. NSString *appVersion = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
  92. NSArray *authToken = [self PlexBasicAuthentification:username password:password];
  93. NSData *data = [self PlexDeviceInfo:authToken];
  94. VLCPlexParser *plexParser = [[VLCPlexParser alloc] init];
  95. deviceInfo = [plexParser PlexExtractDeviceInfo:data];
  96. if ((deviceInfo.count == 0) || ((![[[deviceInfo objectAtIndex:0] objectForKey:@"productVersion"] isEqualToString:appVersion]) || (![[[deviceInfo objectAtIndex:0] objectForKey:@"platformVersion"] isEqualToString:[[UIDevice currentDevice] systemVersion]]))) {
  97. [deviceInfo removeAllObjects];
  98. [self PlexCreateIdentification:username password:password];
  99. data = [self PlexDeviceInfo:authToken];
  100. deviceInfo = [plexParser PlexExtractDeviceInfo:data];
  101. }
  102. if (deviceInfo.count != 0)
  103. 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=%@", [[deviceInfo objectAtIndex:0] objectForKey:@"product"], [[deviceInfo objectAtIndex:0] objectForKey:@"productVersion"], [[deviceInfo objectAtIndex:0] objectForKey:@"clientIdentifier"], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] model], [[deviceInfo objectAtIndex:0] objectForKey:@"name"], [[deviceInfo objectAtIndex:0] objectForKey:@"token"], username] stringByReplacingOccurrencesOfString:@" " withString:@"+"];
  104. }
  105. return authentification;
  106. }
  107. - (NSString *)urlAuth:(NSString *)url autentification:(NSString *)auth
  108. {
  109. NSString *key = @"";
  110. if (![auth isEqualToString:@""]) {
  111. NSRange isRange = [url rangeOfString:@"?" options:NSCaseInsensitiveSearch];
  112. if(isRange.location != NSNotFound)
  113. key = @"&";
  114. else
  115. key = @"?";
  116. }
  117. return [NSString stringWithFormat:@"%@%@%@", url, key, auth];
  118. }
  119. #pragma mark - Unofficial API
  120. - (NSInteger)MarkWatchedUnwatchedMedia:(NSString *)adress port:(NSString *)port videoRatingKey:(NSString *)ratingKey state:(NSString *)state authentification:(NSString *)auth
  121. {
  122. NSString *url = nil;
  123. if ([state isEqualToString:@"watched"])
  124. url = [NSString stringWithFormat:@"http://%@%@/:/unscrobble?identifier=com.plexapp.plugins.library&key=%@", adress, port, ratingKey];
  125. else
  126. url = [NSString stringWithFormat:@"http://%@%@/:/scrobble?identifier=com.plexapp.plugins.library&key=%@", adress, port, ratingKey];
  127. NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[[[VLCPlexWebAPI alloc] init] urlAuth:url autentification:auth]] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:20];
  128. NSURLResponse *response = nil;
  129. NSError *error = nil;
  130. [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  131. NSInteger httpStatus = [(NSHTTPURLResponse *)response statusCode];
  132. if (httpStatus != 200)
  133. APLog(@"Mark Watched Unwatched Media Error status: %ld at URL : %@", (long)httpStatus, url);
  134. return httpStatus;
  135. }
  136. - (NSString *)getFileSubtitleFromPlexServer:(NSMutableArray *)mutableMediaObject modeStream:(BOOL)modeStream
  137. {
  138. NSString *FileSubtitlePath = nil;
  139. NSString *fileName = [[[[mutableMediaObject objectAtIndex:0] objectForKey:@"namefile"] stringByDeletingPathExtension] stringByAppendingPathExtension:[[mutableMediaObject objectAtIndex:0] objectForKey:@"codecSubtitle"]];
  140. VLCPlexWebAPI *PlexWebAPI = [[VLCPlexWebAPI alloc] init];
  141. NSURL *url = [[NSURL alloc] initWithString:[PlexWebAPI urlAuth:[[mutableMediaObject objectAtIndex:0] objectForKey:@"keySubtitle"] autentification:[[mutableMediaObject objectAtIndex:0] objectForKey:@"authentification"]]];
  142. NSData *receivedSub = [NSData dataWithContentsOfURL:url];
  143. if (receivedSub.length < [[UIDevice currentDevice] freeDiskspace].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. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  160. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), fileName, [[UIDevice currentDevice] model]]
  161. delegate:self
  162. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  163. otherButtonTitles:nil];
  164. [alert show];
  165. }
  166. return FileSubtitlePath;
  167. }
  168. - (NSURL *)CreatePlexStreamingURL:(NSString *)adress port:(NSString *)port videoKey:(NSString *)key username:(NSString *)username deviceInfo:(NSMutableArray *)deviceInfo session:(NSString *)session
  169. {
  170. /* it starts video transcoding but without sound !!! why ? */
  171. 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=%@", [[deviceInfo objectAtIndex:0] objectForKey:@"product"], [[deviceInfo objectAtIndex:0] objectForKey:@"productVersion"], [[deviceInfo objectAtIndex:0] objectForKey:@"clientIdentifier"], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] model], [[deviceInfo objectAtIndex:0] objectForKey:@"name"], [[deviceInfo objectAtIndex:0] objectForKey:@"token"], username] stringByReplacingOccurrencesOfString:@" " withString:@"+"];
  172. NSString *unescaped = [NSString stringWithFormat:@"http://127.0.0.1:32400%@", key];
  173. NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
  174. 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", adress, port, escapedString, session] stringByAppendingString:authentification]];
  175. return url;
  176. }
  177. - (void)stopSession:(NSString *)adress port:(NSString *)port session:(NSString *)session
  178. {
  179. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@/video/:/transcode/universal/stop?session=%@", adress, port, session]];
  180. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  181. NSHTTPURLResponse *response = nil;
  182. NSError *error = nil;
  183. [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  184. if ([response statusCode] != 200)
  185. APLog(@"Plex stop Session %@ : %@", session, [response allHeaderFields]);
  186. }
  187. #pragma mark -
  188. - (NSString *)getSession
  189. {
  190. NSString *session = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  191. return session;
  192. }
  193. - (NSData *)PlexDeviceInfo:(NSArray *)cookies
  194. {
  195. NSURL *url = [NSURL URLWithString:kPlexURLdeviceInfo];
  196. NSData *data = [self HttpRequestWithCookie:url cookies:cookies HTTPMethod:@"GET"];
  197. return data;
  198. }
  199. @end