VLCOneDriveController.m 9.4 KB

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