VLCPlexWebAPI.m 13 KB

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