VLCOneDriveController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /*****************************************************************************
  2. * VLCOneDriveController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2014-2019 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. *
  10. * Refer to the COPYING file of the official project for license.
  11. *****************************************************************************/
  12. #import "VLCOneDriveController.h"
  13. #import "VLCOneDriveConstants.h"
  14. #import "UIDevice+VLC.h"
  15. #import "NSString+SupportedMedia.h"
  16. #import "VLCHTTPFileDownloader.h"
  17. #import <OneDriveSDK.h>
  18. #if TARGET_OS_IOS
  19. # import "VLC-Swift.h"
  20. #endif
  21. @interface VLCOneDriveController ()
  22. {
  23. NSMutableArray *_pendingDownloads;
  24. BOOL _downloadInProgress;
  25. CGFloat _averageSpeed;
  26. CGFloat _fileSize;
  27. NSTimeInterval _startDL;
  28. NSTimeInterval _lastStatsUpdate;
  29. ODClient *_oneDriveClient;
  30. NSMutableArray *_currentItems;
  31. VLCHTTPFileDownloader *_fileDownloader;
  32. }
  33. @end
  34. @implementation VLCOneDriveController
  35. + (VLCCloudStorageController *)sharedInstance
  36. {
  37. static VLCOneDriveController *sharedInstance = nil;
  38. static dispatch_once_t pred;
  39. dispatch_once(&pred, ^{
  40. sharedInstance = [[VLCOneDriveController alloc] init];
  41. });
  42. return sharedInstance;
  43. }
  44. - (instancetype)init
  45. {
  46. self = [super init];
  47. if (!self)
  48. return self;
  49. // [self restoreFromSharedCredentials];
  50. _oneDriveClient = [ODClient loadCurrentClient];
  51. [self setupSession];
  52. return self;
  53. }
  54. - (void)setupSession
  55. {
  56. _parentItem = nil;
  57. _currentItem = nil;
  58. _rootItemID = nil;
  59. _currentItems = [[NSMutableArray alloc] init];
  60. }
  61. #pragma mark - authentication
  62. - (BOOL)activeSession
  63. {
  64. return _oneDriveClient != nil;
  65. }
  66. - (void)loginWithViewController:(UIViewController *)presentingViewController
  67. {
  68. _presentingViewController = presentingViewController;
  69. [ODClient authenticatedClientWithCompletion:^(ODClient *client, NSError *error) {
  70. if (error) {
  71. [self authFailed:error];
  72. return;
  73. }
  74. self->_oneDriveClient = client;
  75. [self authSuccess];
  76. }];
  77. }
  78. - (void)logout
  79. {
  80. [_oneDriveClient signOutWithCompletion:^(NSError *error) {
  81. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  82. [ubiquitousStore removeObjectForKey:kVLCStoreOneDriveCredentials];
  83. [ubiquitousStore synchronize];
  84. self->_oneDriveClient = nil;
  85. self->_currentItem = nil;
  86. self->_currentItems = nil;
  87. self->_rootItemID = nil;
  88. self->_parentItem = nil;
  89. dispatch_async(dispatch_get_main_queue(), ^{
  90. if (self->_presentingViewController) {
  91. [self->_presentingViewController.navigationController popViewControllerAnimated:YES];
  92. }
  93. });
  94. }];
  95. }
  96. - (NSArray *)currentListFiles
  97. {
  98. return [_currentItems copy];
  99. }
  100. - (BOOL)isAuthorized
  101. {
  102. return _oneDriveClient != nil;
  103. }
  104. - (void)authSuccess
  105. {
  106. APLog(@"VLCOneDriveController: Authentication complete.");
  107. [self setupSession];
  108. [[NSNotificationCenter defaultCenter] postNotificationName:VLCOneDriveControllerSessionUpdated object:self];
  109. // [self shareCredentials];
  110. }
  111. - (void)authFailed:(NSError *)error
  112. {
  113. APLog(@"VLCOneDriveController: Authentication failure.");
  114. if (self.delegate) {
  115. if ([self.delegate respondsToSelector:@selector(sessionWasUpdated)])
  116. [self.delegate performSelector:@selector(sessionWasUpdated)];
  117. }
  118. [[NSNotificationCenter defaultCenter] postNotificationName:VLCOneDriveControllerSessionUpdated object:self];
  119. }
  120. - (void)shareCredentials
  121. {
  122. // FIXME: https://github.com/OneDrive/onedrive-sdk-ios/issues/187
  123. /* share our credentials */
  124. // LiveAuthStorage *authStorage = [[LiveAuthStorage alloc] initWithClientId:kVLCOneDriveClientID];
  125. // _oneDriveClient = [[ODClient alloc] ]
  126. // _oneDriveClient.authProvider.accountSession.refreshToken;
  127. //NSString *credentials = [authStorage refreshToken];
  128. // NSString *credentials = [_oneDriveClient token]
  129. // if (credentials == nil)
  130. // return;
  131. //
  132. // NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  133. // [ubiquitousStore setString:credentials forKey:kVLCStoreOneDriveCredentials];
  134. // [ubiquitousStore synchronize];
  135. }
  136. - (BOOL)restoreFromSharedCredentials
  137. {
  138. // LiveAuthStorage *authStorage = [[LiveAuthStorage alloc] initWithClientId:kVLCOneDriveClientID];
  139. // NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  140. // [ubiquitousStore synchronize];
  141. // NSString *credentials = [ubiquitousStore stringForKey:kVLCStoreOneDriveCredentials];
  142. // if (!credentials)
  143. // return NO;
  144. //
  145. // [authStorage setRefreshToken:credentials];
  146. return YES;
  147. }
  148. #pragma mark - listing
  149. - (void)requestDirectoryListingAtPath:(NSString *)path
  150. {
  151. [self loadODItems];
  152. }
  153. - (void)prepareODItems:(NSArray<ODItem *> *)items
  154. {
  155. for (ODItem *item in items) {
  156. if (!_rootItemID) {
  157. _rootItemID = item.parentReference.id;
  158. }
  159. if (![_currentItems containsObject:item.id] && ([item.name isSupportedFormat] || item.folder)) {
  160. [_currentItems addObject:item];
  161. }
  162. }
  163. dispatch_async(dispatch_get_main_queue(), ^{
  164. if (self.delegate) {
  165. [self.delegate performSelector:@selector(mediaListUpdated)];
  166. }
  167. });
  168. }
  169. - (void)loadODItemsWithCompletionHandler:(void (^)(void))completionHandler
  170. {
  171. NSString *itemID = _currentItem ? _currentItem.id : @"root";
  172. ODChildrenCollectionRequest * request = [[[[_oneDriveClient drive] items:itemID] children] request];
  173. // Clear all current
  174. [_currentItems removeAllObjects];
  175. __weak typeof(self) weakSelf = self;
  176. [request getWithCompletion:^(ODCollection *response, ODChildrenCollectionRequest *nextRequest, NSError *error) {
  177. if (!error) {
  178. [self prepareODItems:response.value];
  179. if (completionHandler) {
  180. completionHandler();
  181. }
  182. } else {
  183. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[error localizedFailureReason]
  184. message:[error localizedDescription]
  185. preferredStyle:UIAlertControllerStyleAlert];
  186. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OK", nil)
  187. style:UIAlertActionStyleCancel
  188. handler:^(UIAlertAction *alertAction) {
  189. if (weakSelf.presentingViewController && [itemID isEqualToString:@"root"]) {
  190. [weakSelf.presentingViewController.navigationController popViewControllerAnimated:YES];
  191. }
  192. }];
  193. [alertController addAction:okAction];
  194. if (weakSelf.presentingViewController) {
  195. dispatch_async(dispatch_get_main_queue(), ^{
  196. [weakSelf.presentingViewController presentViewController:alertController animated:YES completion:nil];
  197. });
  198. }
  199. }
  200. }];
  201. }
  202. - (void)loadODItems
  203. {
  204. [self loadODItemsWithCompletionHandler:nil];
  205. }
  206. - (void)loadThumbnails:(NSArray<ODItem *> *)items
  207. {
  208. for (ODItem *item in items) {
  209. if ([item thumbnails:0]) {
  210. [[[[[_oneDriveClient.drive items:item.id] thumbnails:@"0"] small] contentRequest]
  211. downloadWithCompletion:^(NSURL *location, NSURLResponse *response, NSError *error) {
  212. if (!error) {
  213. }
  214. }];
  215. }
  216. }
  217. dispatch_async(dispatch_get_main_queue(), ^{
  218. if (self.delegate) {
  219. [self.delegate performSelector:@selector(mediaListUpdated)];
  220. }
  221. });
  222. }
  223. #pragma - subtitle
  224. - (NSString *)configureSubtitleWithFileName:(NSString *)fileName folderItems:(NSArray *)folderItems
  225. {
  226. return [self _getFileSubtitleFromServer:[self _searchSubtitle:fileName folderItems:folderItems]];
  227. }
  228. - (NSMutableDictionary *)_searchSubtitle:(NSString *)fileName folderItems:(NSArray *)folderItems
  229. {
  230. NSMutableDictionary *itemSubtitle = [[NSMutableDictionary alloc] init];
  231. NSString *urlTemp = [[fileName lastPathComponent] stringByDeletingPathExtension];
  232. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", urlTemp];
  233. NSArray *results = [folderItems filteredArrayUsingPredicate:predicate];
  234. for (ODItem *item in results) {
  235. if ([item.name isSupportedSubtitleFormat]) {
  236. [itemSubtitle setObject:item.name forKey:@"filename"];
  237. [itemSubtitle setObject:[NSURL URLWithString:item.dictionaryFromItem[@"@content.downloadUrl"]] forKey:@"url"];
  238. }
  239. }
  240. return itemSubtitle;
  241. }
  242. - (NSString *)_getFileSubtitleFromServer:(NSMutableDictionary *)itemSubtitle
  243. {
  244. NSString *fileSubtitlePath = nil;
  245. if (itemSubtitle[@"filename"]) {
  246. NSData *receivedSub = [NSData dataWithContentsOfURL:[itemSubtitle objectForKey:@"url"]]; // TODO: fix synchronous load
  247. if (receivedSub.length < [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) {
  248. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  249. NSString *directoryPath = searchPaths.firstObject;
  250. fileSubtitlePath = [directoryPath stringByAppendingPathComponent:[itemSubtitle objectForKey:@"filename"]];
  251. NSFileManager *fileManager = [NSFileManager defaultManager];
  252. if (![fileManager fileExistsAtPath:fileSubtitlePath]) {
  253. //create local subtitle file
  254. [fileManager createFileAtPath:fileSubtitlePath contents:nil attributes:nil];
  255. if (![fileManager fileExistsAtPath:fileSubtitlePath]) {
  256. APLog(@"file creation failed, no data was saved");
  257. return nil;
  258. }
  259. }
  260. [receivedSub writeToFile:fileSubtitlePath atomically:YES];
  261. } else {
  262. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  263. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  264. [itemSubtitle objectForKey:@"filename"],
  265. [[UIDevice currentDevice] model]]
  266. preferredStyle:UIAlertControllerStyleAlert];
  267. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OK", nil)
  268. style:UIAlertActionStyleCancel
  269. handler:nil];
  270. [alertController addAction:okAction];
  271. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  272. }
  273. }
  274. return fileSubtitlePath;
  275. }
  276. #pragma mark - file handling
  277. - (BOOL)canPlayAll
  278. {
  279. return YES;
  280. }
  281. - (void)startDownloadingODItem:(ODItem *)item
  282. {
  283. if (item == nil)
  284. return;
  285. if (item.folder)
  286. return;
  287. if (!_pendingDownloads)
  288. _pendingDownloads = [[NSMutableArray alloc] init];
  289. [_pendingDownloads addObject:item];
  290. [self _triggerNextDownload];
  291. }
  292. - (void)downloadODItem:(ODItem *)item
  293. {
  294. #if TARGET_OS_IOS
  295. if (!_fileDownloader) {
  296. _fileDownloader = [[VLCHTTPFileDownloader alloc] init];
  297. _fileDownloader.delegate = self;
  298. }
  299. [_fileDownloader downloadFileFromURL:[NSURL URLWithString:item.dictionaryFromItem[@"@content.downloadUrl"]]
  300. withFileName:item.name];
  301. #endif
  302. }
  303. - (void)_triggerNextDownload
  304. {
  305. if (_pendingDownloads.count > 0 && !_downloadInProgress) {
  306. _downloadInProgress = YES;
  307. [self downloadODItem:_pendingDownloads.firstObject];
  308. [_pendingDownloads removeObjectAtIndex:0];
  309. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  310. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  311. }
  312. }
  313. - (void)downloadStarted
  314. {
  315. _startDL = [NSDate timeIntervalSinceReferenceDate];
  316. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  317. [self.delegate operationWithProgressInformationStarted];
  318. }
  319. - (void)downloadEnded
  320. {
  321. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  322. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  323. [self.delegate operationWithProgressInformationStopped];
  324. #if TARGET_OS_IOS
  325. // FIXME: Replace notifications by cleaner observers
  326. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  327. object:self];
  328. #endif
  329. _downloadInProgress = NO;
  330. [self _triggerNextDownload];
  331. }
  332. - (void)downloadFailedWithErrorDescription:(NSString *)description
  333. {
  334. APLog(@"VLCOneDriveController: Download failed (%@)", description);
  335. }
  336. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  337. {
  338. [self progressUpdated:percentage];
  339. [self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize];
  340. }
  341. - (void)progressUpdated:(CGFloat)progress
  342. {
  343. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  344. [self.delegate currentProgressInformation:progress];
  345. }
  346. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  347. {
  348. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  349. CGFloat smoothingFactor = 0.005;
  350. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  351. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  352. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  353. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  354. [formatter setDateFormat:@"HH:mm:ss"];
  355. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  356. NSString *remaingTime = [formatter stringFromDate:date];
  357. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  358. [self.delegate updateRemainingTime:remaingTime];
  359. }
  360. @end