VLCOneDriveController.m 16 KB

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