VLCOneDriveController.m 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 restoreFromSharedCredentials];
  51. _liveScopes = @[@"wl.signin",@"wl.offline_access",@"wl.skydrive"];
  52. _liveClient = [[LiveConnectClient alloc] initWithClientId:kVLCOneDriveClientID
  53. scopes:_liveScopes
  54. delegate:self
  55. userState:@"init"];
  56. return self;
  57. }
  58. #pragma mark - authentication
  59. - (BOOL)activeSession
  60. {
  61. return _activeSession;
  62. }
  63. - (void)loginWithViewController:(UIViewController *)presentingViewController
  64. {
  65. [_liveClient login:presentingViewController
  66. scopes:_liveScopes
  67. delegate:self
  68. userState:@"login"];
  69. #if TARGET_OS_IOS
  70. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
  71. #endif
  72. }
  73. - (void)logout
  74. {
  75. [_liveClient logoutWithDelegate:self userState:@"logout"];
  76. _activeSession = NO;
  77. _userAuthenticated = NO;
  78. _currentFolder = nil;
  79. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  80. [self.delegate mediaListUpdated];
  81. }
  82. - (NSArray *)currentListFiles
  83. {
  84. return _currentFolder.items;
  85. }
  86. - (BOOL)isAuthorized
  87. {
  88. return _liveClient.session != NULL;
  89. }
  90. - (void)authCompleted:(LiveConnectSessionStatus)status session:(LiveConnectSession *)session userState:(id)userState
  91. {
  92. #if TARGET_OS_IOS
  93. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
  94. #endif
  95. APLog(@"OneDrive: authCompleted, status %i, state %@", status, userState);
  96. if (session != NULL && [userState isEqualToString:@"init"] && status == 1)
  97. _activeSession = YES;
  98. if (session != NULL && [userState isEqualToString:@"login"] && status == 1)
  99. _userAuthenticated = YES;
  100. if (status == 0) {
  101. _activeSession = NO;
  102. _userAuthenticated = NO;
  103. }
  104. if (self.delegate) {
  105. if ([self.delegate respondsToSelector:@selector(sessionWasUpdated)])
  106. [self.delegate performSelector:@selector(sessionWasUpdated)];
  107. }
  108. [[NSNotificationCenter defaultCenter] postNotificationName:VLCOneDriveControllerSessionUpdated object:self];
  109. [self shareCredentials];
  110. }
  111. - (void)authFailed:(NSError *)error userState:(id)userState
  112. {
  113. #if TARGET_OS_IOS
  114. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
  115. #endif
  116. APLog(@"OneDrive auth failed: %@, %@", error, userState);
  117. _activeSession = NO;
  118. if (self.delegate) {
  119. if ([self.delegate respondsToSelector:@selector(sessionWasUpdated)])
  120. [self.delegate performSelector:@selector(sessionWasUpdated)];
  121. }
  122. [[NSNotificationCenter defaultCenter] postNotificationName:VLCOneDriveControllerSessionUpdated object:self];
  123. }
  124. - (void)shareCredentials
  125. {
  126. /* share our credentials */
  127. LiveAuthStorage *authStorage = [[LiveAuthStorage alloc] initWithClientId:kVLCOneDriveClientID];
  128. NSString *credentials = [authStorage refreshToken];
  129. if (credentials == nil)
  130. return;
  131. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  132. [ubiquitousStore setString:credentials forKey:kVLCStoreOneDriveCredentials];
  133. [ubiquitousStore synchronize];
  134. }
  135. - (BOOL)restoreFromSharedCredentials
  136. {
  137. LiveAuthStorage *authStorage = [[LiveAuthStorage alloc] initWithClientId:kVLCOneDriveClientID];
  138. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  139. [ubiquitousStore synchronize];
  140. NSString *credentials = [ubiquitousStore stringForKey:kVLCStoreOneDriveCredentials];
  141. if (!credentials)
  142. return NO;
  143. [authStorage setRefreshToken:credentials];
  144. return YES;
  145. }
  146. - (void)liveOperationSucceeded:(LiveDownloadOperation *)operation
  147. {
  148. APLog(@"ODC: liveOperationSucceeded (%@)", operation.userState);
  149. }
  150. - (void)liveOperationFailed:(NSError *)error operation:(LiveDownloadOperation *)operation
  151. {
  152. APLog(@"ODC: liveOperationFailed %@ (%@)", error, operation.userState);
  153. }
  154. #pragma mark - listing
  155. - (void)requestDirectoryListingAtPath:(NSString *)path
  156. {
  157. [self loadCurrentFolder];
  158. }
  159. - (void)loadTopLevelFolder
  160. {
  161. _rootFolder = [[VLCOneDriveObject alloc] init];
  162. _rootFolder.objectId = @"me/skydrive";
  163. _rootFolder.name = @"OneDrive";
  164. _rootFolder.type = @"folder";
  165. _rootFolder.liveClient = _liveClient;
  166. _rootFolder.delegate = self;
  167. _currentFolder = _rootFolder;
  168. [_rootFolder loadFolderContent];
  169. }
  170. - (void)loadCurrentFolder
  171. {
  172. if (_currentFolder == nil)
  173. [self loadTopLevelFolder];
  174. else {
  175. _currentFolder.delegate = self;
  176. [_currentFolder loadFolderContent];
  177. }
  178. }
  179. #pragma mark - file handling
  180. - (void)downloadObject:(VLCOneDriveObject *)object
  181. {
  182. if (object == nil)
  183. return;
  184. if (object.isFolder)
  185. return;
  186. object.downloadDelegate = self;
  187. if (!_pendingDownloads)
  188. _pendingDownloads = [[NSMutableArray alloc] init];
  189. [_pendingDownloads addObject:object];
  190. [self _triggerNextDownload];
  191. }
  192. - (void)_triggerNextDownload
  193. {
  194. if (_pendingDownloads.count > 0 && !_downloadInProgress) {
  195. _downloadInProgress = YES;
  196. [_pendingDownloads[0] saveObjectToDocuments];
  197. [_pendingDownloads removeObjectAtIndex:0];
  198. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  199. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  200. }
  201. }
  202. - (void)downloadStarted:(VLCOneDriveObject *)object
  203. {
  204. _startDL = [NSDate timeIntervalSinceReferenceDate];
  205. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  206. [self.delegate operationWithProgressInformationStarted];
  207. }
  208. - (void)downloadEnded:(VLCOneDriveObject *)object
  209. {
  210. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  211. [self.delegate operationWithProgressInformationStopped];
  212. _downloadInProgress = NO;
  213. [self _triggerNextDownload];
  214. }
  215. - (void)progressUpdated:(CGFloat)progress
  216. {
  217. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  218. [self.delegate currentProgressInformation:progress];
  219. }
  220. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  221. {
  222. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  223. CGFloat smoothingFactor = 0.005;
  224. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  225. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  226. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  227. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  228. [formatter setDateFormat:@"HH:mm:ss"];
  229. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  230. NSString *remaingTime = [formatter stringFromDate:date];
  231. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  232. [self.delegate updateRemainingTime:remaingTime];
  233. }
  234. #pragma mark - onedrive object delegation
  235. - (void)folderContentLoaded:(VLCOneDriveObject *)sender
  236. {
  237. if (self.delegate)
  238. [self.delegate performSelector:@selector(mediaListUpdated)];
  239. }
  240. - (void)folderContentLoadingFailed:(NSError *)error sender:(VLCOneDriveObject *)sender
  241. {
  242. APLog(@"folder content loading failed %@", error);
  243. }
  244. - (void)fullFolderTreeLoaded:(VLCOneDriveObject *)sender
  245. {
  246. if (self.delegate)
  247. [self.delegate performSelector:@selector(mediaListUpdated)];
  248. }
  249. @end