VLCOneDriveController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. [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. #if TARGET_OS_IOS
  313. if (!_fileDownloader) {
  314. _fileDownloader = [[VLCHTTPFileDownloader alloc] init];
  315. _fileDownloader.delegate = self;
  316. }
  317. [_fileDownloader downloadFileFromURL:[NSURL URLWithString:item.dictionaryFromItem[@"@content.downloadUrl"]]
  318. withFileName:item.name];
  319. #endif
  320. }
  321. - (void)_triggerNextDownload
  322. {
  323. if (_pendingDownloads.count > 0 && !_downloadInProgress) {
  324. _downloadInProgress = YES;
  325. [self downloadODItem:_pendingDownloads.firstObject];
  326. [_pendingDownloads removeObjectAtIndex:0];
  327. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  328. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  329. }
  330. }
  331. - (void)downloadStarted
  332. {
  333. _startDL = [NSDate timeIntervalSinceReferenceDate];
  334. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  335. [self.delegate operationWithProgressInformationStarted];
  336. }
  337. - (void)downloadEnded
  338. {
  339. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  340. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  341. [self.delegate operationWithProgressInformationStopped];
  342. #if TARGET_OS_IOS
  343. // FIXME: Replace notifications by cleaner observers
  344. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  345. object:self];
  346. #endif
  347. _downloadInProgress = NO;
  348. [self _triggerNextDownload];
  349. }
  350. - (void)downloadFailedWithErrorDescription:(NSString *)description
  351. {
  352. APLog(@"VLCOneDriveController: Download failed (%@)", description);
  353. }
  354. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  355. {
  356. [self progressUpdated:percentage];
  357. [self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize];
  358. }
  359. - (void)progressUpdated:(CGFloat)progress
  360. {
  361. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  362. [self.delegate currentProgressInformation:progress];
  363. }
  364. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  365. {
  366. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  367. CGFloat smoothingFactor = 0.005;
  368. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  369. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  370. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  371. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  372. [formatter setDateFormat:@"HH:mm:ss"];
  373. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  374. NSString *remaingTime = [formatter stringFromDate:date];
  375. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  376. [self.delegate updateRemainingTime:remaingTime];
  377. }
  378. @end