VLCOneDriveController.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 <OneDriveSDK.h>
  17. #if TARGET_OS_IOS
  18. # import "VLC-Swift.h"
  19. #endif
  20. @interface VLCOneDriveController ()
  21. {
  22. NSMutableArray *_pendingDownloads;
  23. BOOL _downloadInProgress;
  24. NSProgress *_progress;
  25. CGFloat _averageSpeed;
  26. CGFloat _fileSize;
  27. NSTimeInterval _startDL;
  28. NSTimeInterval _lastStatsUpdate;
  29. ODClient *_oneDriveClient;
  30. NSMutableArray *_currentItems;
  31. }
  32. @end
  33. static void *ProgressObserverContext = &ProgressObserverContext;
  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. [weakSelf handleLoadODItemErrorWithError:error itemID:itemID];
  184. }
  185. }];
  186. }
  187. - (void)handleLoadODItemErrorWithError:(NSError *)error itemID:(NSString *)itemID
  188. {
  189. __weak typeof(self) weakSelf = self;
  190. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[error localizedFailureReason]
  191. message:[error localizedDescription]
  192. preferredStyle:UIAlertControllerStyleAlert];
  193. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OK", nil)
  194. style:UIAlertActionStyleCancel
  195. handler:^(UIAlertAction *alertAction) {
  196. if (weakSelf.presentingViewController && [itemID isEqualToString:@"root"]) {
  197. [weakSelf.presentingViewController.navigationController popViewControllerAnimated:YES];
  198. }
  199. }];
  200. [alertController addAction:okAction];
  201. if (weakSelf.presentingViewController) {
  202. dispatch_async(dispatch_get_main_queue(), ^{
  203. [weakSelf.presentingViewController presentViewController:alertController animated:YES completion:nil];
  204. });
  205. }
  206. }
  207. - (void)loadODParentItem
  208. {
  209. NSString *parentID = _parentItem.id ? _parentItem.id : @"root";
  210. ODItemRequest *request = [[[_oneDriveClient drive] items:parentID] request];
  211. __weak typeof(self) weakSelf = self;
  212. [request getWithCompletion:^(ODItem *response, NSError *error) {
  213. if (!error) {
  214. weakSelf.parentItem = response;
  215. } else {
  216. [weakSelf handleLoadODItemErrorWithError:error itemID:parentID];
  217. }
  218. }];
  219. }
  220. - (void)loadODItems
  221. {
  222. [self loadODItemsWithCompletionHandler:nil];
  223. }
  224. - (void)loadThumbnails:(NSArray<ODItem *> *)items
  225. {
  226. for (ODItem *item in items) {
  227. if ([item thumbnails:0]) {
  228. [[[[[_oneDriveClient.drive items:item.id] thumbnails:@"0"] small] contentRequest]
  229. downloadWithCompletion:^(NSURL *location, NSURLResponse *response, NSError *error) {
  230. if (!error) {
  231. }
  232. }];
  233. }
  234. }
  235. dispatch_async(dispatch_get_main_queue(), ^{
  236. if (self.delegate) {
  237. [self.delegate performSelector:@selector(mediaListUpdated)];
  238. }
  239. });
  240. }
  241. #pragma - subtitle
  242. - (NSString *)configureSubtitleWithFileName:(NSString *)fileName folderItems:(NSArray *)folderItems
  243. {
  244. return [self _getFileSubtitleFromServer:[self _searchSubtitle:fileName folderItems:folderItems]];
  245. }
  246. - (NSMutableDictionary *)_searchSubtitle:(NSString *)fileName folderItems:(NSArray *)folderItems
  247. {
  248. NSMutableDictionary *itemSubtitle = [[NSMutableDictionary alloc] init];
  249. NSString *urlTemp = [[fileName lastPathComponent] stringByDeletingPathExtension];
  250. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", urlTemp];
  251. NSArray *results = [folderItems filteredArrayUsingPredicate:predicate];
  252. for (ODItem *item in results) {
  253. if ([item.name isSupportedSubtitleFormat]) {
  254. [itemSubtitle setObject:item.name forKey:@"filename"];
  255. [itemSubtitle setObject:[NSURL URLWithString:item.dictionaryFromItem[@"@content.downloadUrl"]] forKey:@"url"];
  256. }
  257. }
  258. return itemSubtitle;
  259. }
  260. - (NSString *)_getFileSubtitleFromServer:(NSMutableDictionary *)itemSubtitle
  261. {
  262. NSString *fileSubtitlePath = nil;
  263. if (itemSubtitle[@"filename"]) {
  264. NSData *receivedSub = [NSData dataWithContentsOfURL:[itemSubtitle objectForKey:@"url"]]; // TODO: fix synchronous load
  265. if (receivedSub.length < [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) {
  266. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  267. NSString *directoryPath = searchPaths.firstObject;
  268. fileSubtitlePath = [directoryPath stringByAppendingPathComponent:[itemSubtitle objectForKey:@"filename"]];
  269. NSFileManager *fileManager = [NSFileManager defaultManager];
  270. if (![fileManager fileExistsAtPath:fileSubtitlePath]) {
  271. //create local subtitle file
  272. [fileManager createFileAtPath:fileSubtitlePath contents:nil attributes:nil];
  273. if (![fileManager fileExistsAtPath:fileSubtitlePath]) {
  274. APLog(@"file creation failed, no data was saved");
  275. return nil;
  276. }
  277. }
  278. [receivedSub writeToFile:fileSubtitlePath atomically:YES];
  279. } else {
  280. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  281. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil),
  282. [itemSubtitle objectForKey:@"filename"],
  283. [[UIDevice currentDevice] model]]
  284. preferredStyle:UIAlertControllerStyleAlert];
  285. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OK", nil)
  286. style:UIAlertActionStyleCancel
  287. handler:nil];
  288. [alertController addAction:okAction];
  289. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  290. }
  291. }
  292. return fileSubtitlePath;
  293. }
  294. #pragma mark - file handling
  295. - (BOOL)canPlayAll
  296. {
  297. return YES;
  298. }
  299. - (void)startDownloadingODItem:(ODItem *)item
  300. {
  301. if (item == nil)
  302. return;
  303. if (item.folder)
  304. return;
  305. if (!_pendingDownloads)
  306. _pendingDownloads = [[NSMutableArray alloc] init];
  307. [_pendingDownloads addObject:item];
  308. [self _triggerNextDownload];
  309. }
  310. - (void)downloadODItem:(ODItem *)item
  311. {
  312. [self downloadStarted];
  313. ODURLSessionDownloadTask *task = [[[_oneDriveClient.drive items:item.id] contentRequest]
  314. downloadWithCompletion:^(NSURL *filePath, NSURLResponse *response, NSError *error) {
  315. if (error) {
  316. [self downloadFailedWithErrorDescription: error.localizedDescription];
  317. } else {
  318. NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
  319. NSUserDomainMask, YES).firstObject;
  320. NSString *newFilePath = [self createPotentialPathFrom:[documentPath
  321. stringByAppendingPathComponent:item.name]];
  322. NSError *movingError;
  323. [[NSFileManager defaultManager] moveItemAtURL:filePath
  324. toURL:[NSURL fileURLWithPath:newFilePath] error:&movingError];
  325. if (movingError) {
  326. [self downloadFailedWithErrorDescription: movingError.localizedDescription];
  327. }
  328. }
  329. dispatch_async(dispatch_get_main_queue(), ^{
  330. [self downloadEnded];
  331. });
  332. }];
  333. task.progress.totalUnitCount = item.size;
  334. [self showProgress:task.progress];
  335. }
  336. - (void)_triggerNextDownload
  337. {
  338. if (_pendingDownloads.count > 0 && !_downloadInProgress) {
  339. _downloadInProgress = YES;
  340. [self downloadODItem:_pendingDownloads.firstObject];
  341. [_pendingDownloads removeObjectAtIndex:0];
  342. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  343. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  344. }
  345. }
  346. - (void)downloadStarted
  347. {
  348. _startDL = [NSDate timeIntervalSinceReferenceDate];
  349. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  350. [self.delegate operationWithProgressInformationStarted];
  351. }
  352. - (void)downloadEnded
  353. {
  354. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  355. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  356. [self.delegate operationWithProgressInformationStopped];
  357. #if TARGET_OS_IOS
  358. // FIXME: Replace notifications by cleaner observers
  359. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  360. object:self];
  361. #endif
  362. [self hideProgress];
  363. _downloadInProgress = NO;
  364. [self _triggerNextDownload];
  365. }
  366. - (void)downloadFailedWithErrorDescription:(NSString *)description
  367. {
  368. APLog(@"VLCOneDriveController: Download failed (%@)", description);
  369. }
  370. - (void)showProgress:(NSProgress *)progress
  371. {
  372. _progress = progress;
  373. [progress addObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) options:0 context:ProgressObserverContext];
  374. }
  375. - (void)hideProgress
  376. {
  377. if (_progress) {
  378. [_progress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) context:ProgressObserverContext];
  379. _progress = nil;
  380. }
  381. }
  382. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  383. {
  384. [self progressUpdated:percentage];
  385. [self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize];
  386. }
  387. - (void)progressUpdated:(CGFloat)progress
  388. {
  389. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  390. [self.delegate currentProgressInformation:progress];
  391. }
  392. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  393. {
  394. if (context == ProgressObserverContext) {
  395. dispatch_async(dispatch_get_main_queue(), ^{
  396. NSProgress *progress = object;
  397. [self progressUpdatedTo:progress.fractionCompleted receivedDataSize:progress.completedUnitCount expectedDownloadSize:progress.totalUnitCount];
  398. });
  399. } else {
  400. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  401. }
  402. }
  403. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  404. {
  405. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  406. CGFloat smoothingFactor = 0.005;
  407. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  408. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  409. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  410. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  411. [formatter setDateFormat:@"HH:mm:ss"];
  412. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  413. NSString *remaingTime = [formatter stringFromDate:date];
  414. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  415. [self.delegate updateRemainingTime:remaingTime];
  416. }
  417. @end