VLCOneDriveController.m 9.1 KB

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