VLCOneDriveController.m 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 delete: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. NSLog(@"%s", __PRETTY_FUNCTION__);
  145. LiveAuthStorage *authStorage = [[LiveAuthStorage alloc] initWithClientId:kVLCOneDriveClientID];
  146. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  147. [ubiquitousStore synchronize];
  148. NSString *credentials = [ubiquitousStore stringForKey:kVLCStoreOneDriveCredentials];
  149. NSLog(@"have credentials %@", credentials);
  150. if (!credentials)
  151. return NO;
  152. [authStorage setRefreshToken:credentials];
  153. return YES;
  154. }
  155. - (void)liveOperationSucceeded:(LiveDownloadOperation *)operation
  156. {
  157. APLog(@"ODC: liveOperationSucceeded (%@)", operation.userState);
  158. }
  159. - (void)liveOperationFailed:(NSError *)error operation:(LiveDownloadOperation *)operation
  160. {
  161. APLog(@"ODC: liveOperationFailed %@ (%@)", error, operation.userState);
  162. }
  163. #pragma mark - listing
  164. - (void)requestDirectoryListingAtPath:(NSString *)path
  165. {
  166. [self loadCurrentFolder];
  167. }
  168. - (void)loadTopLevelFolder
  169. {
  170. _rootFolder = [[VLCOneDriveObject alloc] init];
  171. _rootFolder.objectId = @"me/skydrive";
  172. _rootFolder.name = @"OneDrive";
  173. _rootFolder.type = @"folder";
  174. _rootFolder.liveClient = _liveClient;
  175. _rootFolder.delegate = self;
  176. _currentFolder = _rootFolder;
  177. [_rootFolder loadFolderContent];
  178. }
  179. - (void)loadCurrentFolder
  180. {
  181. if (_currentFolder == nil)
  182. [self loadTopLevelFolder];
  183. else {
  184. _currentFolder.delegate = self;
  185. [_currentFolder loadFolderContent];
  186. }
  187. }
  188. #pragma mark - file handling
  189. - (void)downloadObject:(VLCOneDriveObject *)object
  190. {
  191. if (object == nil)
  192. return;
  193. if (object.isFolder)
  194. return;
  195. object.downloadDelegate = self;
  196. if (!_pendingDownloads)
  197. _pendingDownloads = [[NSMutableArray alloc] init];
  198. [_pendingDownloads addObject:object];
  199. [self _triggerNextDownload];
  200. }
  201. - (void)_triggerNextDownload
  202. {
  203. if (_pendingDownloads.count > 0 && !_downloadInProgress) {
  204. _downloadInProgress = YES;
  205. [_pendingDownloads[0] saveObjectToDocuments];
  206. [_pendingDownloads removeObjectAtIndex:0];
  207. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  208. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  209. }
  210. }
  211. - (void)downloadStarted:(VLCOneDriveObject *)object
  212. {
  213. _startDL = [NSDate timeIntervalSinceReferenceDate];
  214. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  215. [self.delegate operationWithProgressInformationStarted];
  216. }
  217. - (void)downloadEnded:(VLCOneDriveObject *)object
  218. {
  219. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  220. [self.delegate operationWithProgressInformationStopped];
  221. _downloadInProgress = NO;
  222. [self _triggerNextDownload];
  223. }
  224. - (void)progressUpdated:(CGFloat)progress
  225. {
  226. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  227. [self.delegate currentProgressInformation:progress];
  228. }
  229. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  230. {
  231. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  232. CGFloat smoothingFactor = 0.005;
  233. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  234. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  235. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  236. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  237. [formatter setDateFormat:@"HH:mm:ss"];
  238. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  239. NSString *remaingTime = [formatter stringFromDate:date];
  240. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  241. [self.delegate updateRemainingTime:remaingTime];
  242. }
  243. #pragma mark - onedrive object delegation
  244. - (void)folderContentLoaded:(VLCOneDriveObject *)sender
  245. {
  246. if (self.delegate)
  247. [self.delegate performSelector:@selector(mediaListUpdated)];
  248. }
  249. - (void)folderContentLoadingFailed:(NSError *)error sender:(VLCOneDriveObject *)sender
  250. {
  251. APLog(@"folder content loading failed %@", error);
  252. }
  253. - (void)fullFolderTreeLoaded:(VLCOneDriveObject *)sender
  254. {
  255. if (self.delegate)
  256. [self.delegate performSelector:@selector(mediaListUpdated)];
  257. }
  258. @end