VLCPlexWebAPI.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 authentification:(NSString *)auth {
  117. return [[self class] urlAuth:url authentification:auth];
  118. }
  119. + (NSString *)urlAuth:(NSString *)url authentification:(NSString *)auth
  120. {
  121. NSString *key = @"";
  122. if (![auth isEqualToString:@""]) {
  123. NSRange isRange = [url rangeOfString:@"?" options:NSCaseInsensitiveSearch];
  124. if(isRange.location != NSNotFound)
  125. key = @"&";
  126. else
  127. key = @"?";
  128. }
  129. return [NSString stringWithFormat:@"%@%@%@", url, key, auth];
  130. }
  131. #pragma mark - Unofficial API
  132. - (NSInteger)MarkWatchedUnwatchedMedia:(NSString *)adress port:(NSString *)port videoRatingKey:(NSString *)ratingKey state:(NSString *)state authentification:(NSString *)auth
  133. {
  134. NSString *url = nil;
  135. if ([state isEqualToString:@"watched"])
  136. url = [NSString stringWithFormat:@"http://%@%@/:/unscrobble?identifier=com.plexapp.plugins.library&key=%@", adress, port, ratingKey];
  137. else
  138. url = [NSString stringWithFormat:@"http://%@%@/:/scrobble?identifier=com.plexapp.plugins.library&key=%@", adress, port, ratingKey];
  139. NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[[[VLCPlexWebAPI alloc] init] urlAuth:url authentification:auth]] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:20];
  140. NSURLResponse *response = nil;
  141. NSError *error = nil;
  142. [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  143. NSInteger httpStatus = [(NSHTTPURLResponse *)response statusCode];
  144. if (httpStatus != 200)
  145. APLog(@"Mark Watched Unwatched Media Error status: %ld at URL : %@", (long)httpStatus, url);
  146. return httpStatus;
  147. }
  148. - (NSString *)getFileSubtitleFromPlexServer:(NSDictionary *)mediaObject modeStream:(BOOL)modeStream
  149. {
  150. if (!mediaObject)
  151. return @"";
  152. NSString *FileSubtitlePath = nil;
  153. NSString *fileName = [[mediaObject[@"namefile"] stringByDeletingPathExtension] stringByAppendingPathExtension:mediaObject[@"codecSubtitle"]];
  154. VLCPlexWebAPI *PlexWebAPI = [[VLCPlexWebAPI alloc] init];
  155. NSURL *url = [[NSURL alloc] initWithString:[PlexWebAPI urlAuth:mediaObject[@"keySubtitle"] authentification:mediaObject[@"authentification"]]];
  156. NSData *receivedSub = [NSData dataWithContentsOfURL:url];
  157. if (receivedSub.length < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  158. NSArray *searchPaths = nil;
  159. if (modeStream)
  160. searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  161. else
  162. searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  163. NSString *directoryPath = [searchPaths objectAtIndex:0];
  164. FileSubtitlePath = [directoryPath stringByAppendingPathComponent:fileName];
  165. NSFileManager *fileManager = [NSFileManager defaultManager];
  166. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  167. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  168. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  169. APLog(@"file creation failed, no data was saved");
  170. }
  171. [receivedSub writeToFile:FileSubtitlePath atomically:YES];
  172. } else {
  173. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  174. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), fileName, [[UIDevice currentDevice] model]]
  175. delegate:self
  176. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  177. otherButtonTitles:nil];
  178. [alert show];
  179. }
  180. return FileSubtitlePath;
  181. }
  182. - (NSURL *)CreatePlexStreamingURL:(NSString *)address port:(NSString *)port videoKey:(NSString *)key username:(NSString *)username deviceInfo:(NSDictionary *)deviceInfo session:(NSString *)session
  183. {
  184. /* it starts video transcoding but without sound !!! why ? */
  185. UIDevice *currentDevice = [UIDevice currentDevice];
  186. 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=%@",
  187. deviceInfo[@"product"],
  188. deviceInfo[@"productVersion"],
  189. deviceInfo[@"clientIdentifier"],
  190. [currentDevice systemVersion],
  191. [currentDevice model],
  192. deviceInfo[@"name"],
  193. deviceInfo[@"token"], username]
  194. stringByReplacingOccurrencesOfString:@" " withString:@"+"];
  195. NSString *unescaped = [NSString stringWithFormat:@"http://127.0.0.1:32400%@", key];
  196. NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
  197. 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",
  198. address,
  199. port,
  200. escapedString,
  201. session] stringByAppendingString:authentification]];
  202. return url;
  203. }
  204. - (void)stopSession:(NSString *)adress port:(NSString *)port session:(NSString *)session
  205. {
  206. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@/video/:/transcode/universal/stop?session=%@", adress, port, session]];
  207. NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
  208. NSHTTPURLResponse *response = nil;
  209. NSError *error = nil;
  210. [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  211. if ([response statusCode] != 200)
  212. APLog(@"Plex stop Session %@ : %@", session, [response allHeaderFields]);
  213. }
  214. #pragma mark -
  215. - (NSString *)getSession
  216. {
  217. NSString *session = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
  218. return session;
  219. }
  220. - (NSData *)PlexDeviceInfo:(NSArray *)cookies
  221. {
  222. NSURL *url = [NSURL URLWithString:kPlexURLdeviceInfo];
  223. NSData *data = [self HttpRequestWithCookie:url cookies:cookies HTTPMethod:@"GET"];
  224. return data;
  225. }
  226. @end