VLCOneDriveController.m 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*****************************************************************************
  2. * VLCOneDriveController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2014-2015 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 "VLCOneDriveObject.h"
  15. /* the Live SDK doesn't have an umbrella header so we need to import what we need */
  16. #import "LiveConnectClient.h"
  17. /* include private API headers */
  18. #import "LiveApiHelper.h"
  19. #import "LiveAuthStorage.h"
  20. @interface VLCOneDriveController () <LiveAuthDelegate, VLCOneDriveObjectDelegate, VLCOneDriveObjectDownloadDelegate>
  21. {
  22. LiveConnectClient *_liveClient;
  23. NSString *_folderId;
  24. NSArray *_liveScopes;
  25. BOOL _activeSession;
  26. BOOL _userAuthenticated;
  27. NSMutableArray *_pendingDownloads;
  28. BOOL _downloadInProgress;
  29. CGFloat _averageSpeed;
  30. CGFloat _fileSize;
  31. NSTimeInterval _startDL;
  32. NSTimeInterval _lastStatsUpdate;
  33. }
  34. @end
  35. @implementation VLCOneDriveController
  36. + (VLCCloudStorageController *)sharedInstance
  37. {
  38. static VLCOneDriveController *sharedInstance = nil;
  39. static dispatch_once_t pred;
  40. dispatch_once(&pred, ^{
  41. sharedInstance = [[VLCOneDriveController alloc] init];
  42. });
  43. return sharedInstance;
  44. }
  45. - (instancetype)init
  46. {
  47. self = [super init];
  48. if (!self)
  49. return self;
  50. [self setupSession];
  51. return self;
  52. }
  53. - (void)setupSession
  54. {
  55. [self restoreFromSharedCredentials];
  56. _liveScopes = @[@"wl.signin",@"wl.offline_access",@"wl.skydrive"];
  57. _liveClient = [[LiveConnectClient alloc] initWithClientId:kVLCOneDriveClientID
  58. scopes:_liveScopes
  59. delegate:self
  60. userState:@"init"];
  61. }
  62. #pragma mark - authentication
  63. - (BOOL)activeSession
  64. {
  65. return _activeSession;
  66. }
  67. - (void)loginWithViewController:(UIViewController *)presentingViewController
  68. {
  69. [_liveClient login:presentingViewController
  70. scopes:_liveScopes
  71. delegate:self
  72. userState:@"login"];
  73. #if TARGET_OS_IOS
  74. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
  75. #endif
  76. }
  77. - (void)logout
  78. {
  79. [_liveClient logoutWithDelegate:self userState:@"logout"];
  80. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  81. [ubiquitousStore removeObjectForKey:kVLCStoreOneDriveCredentials];
  82. [ubiquitousStore synchronize];
  83. _activeSession = NO;
  84. _userAuthenticated = NO;
  85. _currentFolder = nil;
  86. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  87. [self.delegate mediaListUpdated];
  88. }
  89. - (NSArray *)currentListFiles
  90. {
  91. return _currentFolder.items;
  92. }
  93. - (BOOL)isAuthorized
  94. {
  95. return _liveClient.session != NULL;
  96. }
  97. - (void)authCompleted:(LiveConnectSessionStatus)status session:(LiveConnectSession *)session userState:(id)userState
  98. {
  99. #if TARGET_OS_IOS
  100. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
  101. #endif
  102. APLog(@"OneDrive: authCompleted, status %i, state %@", status, userState);
  103. if (session != NULL && [userState isEqualToString:@"init"] && status == 1)
  104. _activeSession = YES;
  105. if (session != NULL && [userState isEqualToString:@"login"] && status == 1)
  106. _userAuthenticated = YES;
  107. if (status == 0) {
  108. _activeSession = NO;
  109. _userAuthenticated = NO;
  110. }
  111. if (self.delegate) {
  112. if ([self.delegate respondsToSelector:@selector(sessionWasUpdated)])
  113. [self.delegate performSelector:@selector(sessionWasUpdated)];
  114. }
  115. [[NSNotificationCenter defaultCenter] postNotificationName:VLCOneDriveControllerSessionUpdated object:self];
  116. [self shareCredentials];
  117. }
  118. - (void)authFailed:(NSError *)error userState:(id)userState
  119. {
  120. #if TARGET_OS_IOS
  121. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
  122. #endif
  123. APLog(@"OneDrive auth failed: %@, %@", error, userState);
  124. _activeSession = NO;
  125. if (self.delegate) {
  126. if ([self.delegate respondsToSelector:@selector(sessionWasUpdated)])
  127. [self.delegate performSelector:@selector(sessionWasUpdated)];
  128. }
  129. [[NSNotificationCenter defaultCenter] postNotificationName:VLCOneDriveControllerSessionUpdated object:self];
  130. }
  131. - (void)shareCredentials
  132. {
  133. /* share our credentials */
  134. LiveAuthStorage *authStorage = [[LiveAuthStorage alloc] initWithClientId:kVLCOneDriveClientID];
  135. NSString *credentials = [authStorage refreshToken];
  136. if (credentials == nil)
  137. return;
  138. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  139. [ubiquitousStore setString:credentials forKey:kVLCStoreOneDriveCredentials];
  140. [ubiquitousStore synchronize];
  141. }
  142. - (BOOL)restoreFromSharedCredentials
  143. {
  144. LiveAuthStorage *authStorage = [[LiveAuthStorage alloc] initWithClientId:kVLCOneDriveClientID];
  145. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  146. [ubiquitousStore synchronize];
  147. NSString *credentials = [ubiquitousStore stringForKey:kVLCStoreOneDriveCredentials];
  148. if (!credentials)
  149. return NO;
  150. [authStorage setRefreshToken:credentials];
  151. return YES;
  152. }
  153. - (void)liveOperationSucceeded:(LiveDownloadOperation *)operation
  154. {
  155. APLog(@"ODC: liveOperationSucceeded (%@)", operation.userState);
  156. }
  157. - (void)liveOperationFailed:(NSError *)error operation:(LiveDownloadOperation *)operation
  158. {
  159. APLog(@"ODC: liveOperationFailed %@ (%@)", error, operation.userState);
  160. }
  161. #pragma mark - listing
  162. - (void)requestDirectoryListingAtPath:(NSString *)path
  163. {
  164. [self loadCurrentFolder];
  165. }
  166. - (void)loadTopLevelFolder
  167. {
  168. _rootFolder = [[VLCOneDriveObject alloc] init];
  169. _rootFolder.objectId = @"me/skydrive";
  170. _rootFolder.name = @"OneDrive";
  171. _rootFolder.type = @"folder";
  172. _rootFolder.liveClient = _liveClient;
  173. _rootFolder.delegate = self;
  174. _currentFolder = _rootFolder;
  175. [_rootFolder loadFolderContent];
  176. }
  177. - (void)loadCurrentFolder
  178. {
  179. if (_currentFolder == nil)
  180. [self loadTopLevelFolder];
  181. else {
  182. _currentFolder.delegate = self;
  183. [_currentFolder loadFolderContent];
  184. }
  185. }
  186. #pragma mark - file handling
  187. - (BOOL)canPlayAll
  188. {
  189. return YES;
  190. }
  191. - (void)downloadObject:(VLCOneDriveObject *)object
  192. {
  193. if (object == nil)
  194. return;
  195. if (object.isFolder)
  196. return;
  197. object.downloadDelegate = self;
  198. if (!_pendingDownloads)
  199. _pendingDownloads = [[NSMutableArray alloc] init];
  200. [_pendingDownloads addObject:object];
  201. [self _triggerNextDownload];
  202. }
  203. - (void)_triggerNextDownload
  204. {
  205. if (_pendingDownloads.count > 0 && !_downloadInProgress) {
  206. _downloadInProgress = YES;
  207. [_pendingDownloads[0] saveObjectToDocuments];
  208. [_pendingDownloads removeObjectAtIndex:0];
  209. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  210. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  211. }
  212. }
  213. - (void)downloadStarted:(VLCOneDriveObject *)object
  214. {
  215. _startDL = [NSDate timeIntervalSinceReferenceDate];
  216. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  217. [self.delegate operationWithProgressInformationStarted];
  218. }
  219. - (void)downloadEnded:(VLCOneDriveObject *)object
  220. {
  221. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  222. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  223. [self.delegate operationWithProgressInformationStopped];
  224. _downloadInProgress = NO;
  225. [self _triggerNextDownload];
  226. }
  227. - (void)progressUpdated:(CGFloat)progress
  228. {
  229. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  230. [self.delegate currentProgressInformation:progress];
  231. }
  232. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  233. {
  234. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  235. CGFloat smoothingFactor = 0.005;
  236. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  237. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  238. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  239. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  240. [formatter setDateFormat:@"HH:mm:ss"];
  241. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  242. NSString *remaingTime = [formatter stringFromDate:date];
  243. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  244. [self.delegate updateRemainingTime:remaingTime];
  245. }
  246. #pragma mark - onedrive object delegation
  247. - (void)folderContentLoaded:(VLCOneDriveObject *)sender
  248. {
  249. if (self.delegate)
  250. [self.delegate performSelector:@selector(mediaListUpdated)];
  251. }
  252. - (void)folderContentLoadingFailed:(NSError *)error sender:(VLCOneDriveObject *)sender
  253. {
  254. APLog(@"folder content loading failed %@", error);
  255. }
  256. - (void)fullFolderTreeLoaded:(VLCOneDriveObject *)sender
  257. {
  258. if (self.delegate)
  259. [self.delegate performSelector:@selector(mediaListUpdated)];
  260. }
  261. @end