VLCOneDriveController.m 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. #if TARGET_OS_IOS
  21. # import "VLC-Swift.h"
  22. #endif
  23. @interface VLCOneDriveController () <LiveAuthDelegate, VLCOneDriveObjectDelegate, VLCOneDriveObjectDownloadDelegate>
  24. {
  25. LiveConnectClient *_liveClient;
  26. NSString *_folderId;
  27. NSArray *_liveScopes;
  28. BOOL _activeSession;
  29. BOOL _userAuthenticated;
  30. NSMutableArray *_pendingDownloads;
  31. BOOL _downloadInProgress;
  32. CGFloat _averageSpeed;
  33. CGFloat _fileSize;
  34. NSTimeInterval _startDL;
  35. NSTimeInterval _lastStatsUpdate;
  36. }
  37. @end
  38. @implementation VLCOneDriveController
  39. + (VLCCloudStorageController *)sharedInstance
  40. {
  41. static VLCOneDriveController *sharedInstance = nil;
  42. static dispatch_once_t pred;
  43. dispatch_once(&pred, ^{
  44. sharedInstance = [[VLCOneDriveController alloc] init];
  45. });
  46. return sharedInstance;
  47. }
  48. - (instancetype)init
  49. {
  50. self = [super init];
  51. if (!self)
  52. return self;
  53. [self setupSession];
  54. return self;
  55. }
  56. - (void)setupSession
  57. {
  58. [self restoreFromSharedCredentials];
  59. _liveScopes = @[@"wl.signin",@"wl.offline_access",@"wl.skydrive"];
  60. _liveClient = [[LiveConnectClient alloc] initWithClientId:kVLCOneDriveClientID
  61. scopes:_liveScopes
  62. delegate:self
  63. userState:@"init"];
  64. }
  65. #pragma mark - authentication
  66. - (BOOL)activeSession
  67. {
  68. return _activeSession;
  69. }
  70. - (void)loginWithViewController:(UIViewController *)presentingViewController
  71. {
  72. [_liveClient login:presentingViewController
  73. scopes:_liveScopes
  74. delegate:self
  75. userState:@"login"];
  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. APLog(@"OneDrive: authCompleted, status %i, state %@", status, userState);
  100. if (session != NULL && [userState isEqualToString:@"init"] && status == 1)
  101. _activeSession = YES;
  102. if (session != NULL && [userState isEqualToString:@"login"] && status == 1)
  103. _userAuthenticated = YES;
  104. if (status == 0) {
  105. _activeSession = NO;
  106. _userAuthenticated = NO;
  107. }
  108. if (self.delegate) {
  109. if ([self.delegate respondsToSelector:@selector(sessionWasUpdated)])
  110. [self.delegate performSelector:@selector(sessionWasUpdated)];
  111. }
  112. [[NSNotificationCenter defaultCenter] postNotificationName:VLCOneDriveControllerSessionUpdated object:self];
  113. [self shareCredentials];
  114. }
  115. - (void)authFailed:(NSError *)error userState:(id)userState
  116. {
  117. APLog(@"OneDrive auth failed: %@, %@", error, userState);
  118. _activeSession = NO;
  119. if (self.delegate) {
  120. if ([self.delegate respondsToSelector:@selector(sessionWasUpdated)])
  121. [self.delegate performSelector:@selector(sessionWasUpdated)];
  122. }
  123. [[NSNotificationCenter defaultCenter] postNotificationName:VLCOneDriveControllerSessionUpdated object:self];
  124. }
  125. - (void)shareCredentials
  126. {
  127. /* share our credentials */
  128. LiveAuthStorage *authStorage = [[LiveAuthStorage alloc] initWithClientId:kVLCOneDriveClientID];
  129. NSString *credentials = [authStorage refreshToken];
  130. if (credentials == nil)
  131. return;
  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. [authStorage setRefreshToken:credentials];
  145. return YES;
  146. }
  147. - (void)liveOperationSucceeded:(LiveDownloadOperation *)operation
  148. {
  149. APLog(@"ODC: liveOperationSucceeded (%@)", operation.userState);
  150. }
  151. - (void)liveOperationFailed:(NSError *)error operation:(LiveDownloadOperation *)operation
  152. {
  153. APLog(@"ODC: liveOperationFailed %@ (%@)", error, operation.userState);
  154. }
  155. #pragma mark - listing
  156. - (void)requestDirectoryListingAtPath:(NSString *)path
  157. {
  158. [self loadCurrentFolder];
  159. }
  160. - (void)loadTopLevelFolder
  161. {
  162. _rootFolder = [[VLCOneDriveObject alloc] init];
  163. _rootFolder.objectId = @"me/skydrive";
  164. _rootFolder.name = @"OneDrive";
  165. _rootFolder.type = @"folder";
  166. _rootFolder.liveClient = _liveClient;
  167. _rootFolder.delegate = self;
  168. _currentFolder = _rootFolder;
  169. [_rootFolder loadFolderContent];
  170. }
  171. - (void)loadCurrentFolder
  172. {
  173. if (_currentFolder == nil)
  174. [self loadTopLevelFolder];
  175. else {
  176. _currentFolder.delegate = self;
  177. [_currentFolder loadFolderContent];
  178. }
  179. }
  180. #pragma mark - file handling
  181. - (BOOL)canPlayAll
  182. {
  183. return YES;
  184. }
  185. - (void)downloadObject:(VLCOneDriveObject *)object
  186. {
  187. if (object == nil)
  188. return;
  189. if (object.isFolder)
  190. return;
  191. object.downloadDelegate = self;
  192. if (!_pendingDownloads)
  193. _pendingDownloads = [[NSMutableArray alloc] init];
  194. [_pendingDownloads addObject:object];
  195. [self _triggerNextDownload];
  196. }
  197. - (void)_triggerNextDownload
  198. {
  199. if (_pendingDownloads.count > 0 && !_downloadInProgress) {
  200. _downloadInProgress = YES;
  201. [_pendingDownloads[0] saveObjectToDocuments];
  202. [_pendingDownloads removeObjectAtIndex:0];
  203. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  204. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  205. }
  206. }
  207. - (void)downloadStarted:(VLCOneDriveObject *)object
  208. {
  209. _startDL = [NSDate timeIntervalSinceReferenceDate];
  210. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  211. [self.delegate operationWithProgressInformationStarted];
  212. }
  213. - (void)downloadEnded:(VLCOneDriveObject *)object
  214. {
  215. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  216. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  217. [self.delegate operationWithProgressInformationStopped];
  218. #if TARGET_OS_IOS
  219. // FIXME: Replace notifications by cleaner observers
  220. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  221. object:self];
  222. #endif
  223. _downloadInProgress = NO;
  224. [self _triggerNextDownload];
  225. }
  226. - (void)progressUpdated:(CGFloat)progress
  227. {
  228. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  229. [self.delegate currentProgressInformation:progress];
  230. }
  231. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  232. {
  233. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  234. CGFloat smoothingFactor = 0.005;
  235. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  236. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  237. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  238. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  239. [formatter setDateFormat:@"HH:mm:ss"];
  240. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  241. NSString *remaingTime = [formatter stringFromDate:date];
  242. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  243. [self.delegate updateRemainingTime:remaingTime];
  244. }
  245. #pragma mark - onedrive object delegation
  246. - (void)folderContentLoaded:(VLCOneDriveObject *)sender
  247. {
  248. if (self.delegate)
  249. [self.delegate performSelector:@selector(mediaListUpdated)];
  250. }
  251. - (void)folderContentLoadingFailed:(NSError *)error sender:(VLCOneDriveObject *)sender
  252. {
  253. APLog(@"folder content loading failed %@", error);
  254. }
  255. - (void)fullFolderTreeLoaded:(VLCOneDriveObject *)sender
  256. {
  257. if (self.delegate)
  258. [self.delegate performSelector:@selector(mediaListUpdated)];
  259. }
  260. @end