VLCPlexWebAPI.m 14 KB

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