123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521 |
- #import "KMDropboxManager.h"
- #import <ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>
- #import "KMCloudUploadOperationQueue.h"
- #import "KMCloudDownloadOperationQueue.h"
- #import "DropboxModel.h"
- @interface KMDropboxManager ()
- @property (nonatomic, copy) NSString *appKey;
- @property (nonatomic, retain) NSMutableArray<KMServicesCloudFile *> *localFileList;
- @property (nonatomic, retain) KMServicesCloudFile *localRootFolder;
- @property (nonatomic, retain) NSMutableDictionary *cloudFilesCache;
- @property (nonatomic, copy) CloudDeleteFileCallBack deleteFileBlock;
- @property (nonatomic, copy) CreateFolderCallBack createFolderBlock;
- @property (nonatomic, copy) GetFileListCallBack getFileListBlock;
- @property (nonatomic, copy) CloudLoginCallBack cloudLoginBlock;
- @property (nonatomic, copy) CloudLogoutCallBack cloudLogoutBlock;
- @end
- @implementation KMDropboxManager
- @synthesize appKey = _appKey;
- static KMDropboxManager *_instance;
- - (void)dealloc {}
- + (instancetype)allocWithZone:(struct _NSZone *)zone {
- @synchronized(self) {
- if (nil == _instance) {
- _instance = [super allocWithZone:zone];
- }
- return _instance;
- }
- }
- + (instancetype)shareInstance {
- @synchronized(self) {
- if (nil == _instance) {
- _instance = [[self alloc] init];
- }
- return _instance;
- }
- }
- - (id)copyWithZone:(NSZone *)zone
- {
- return _instance;
- }
- - (id)mutableCopyWithZone:(NSZone *)zone
- {
- return _instance;
- }
- - (id)init {
- self = [super init];
- if (self) {
- _cloudFilesCache = [[NSMutableDictionary alloc] init];
- #if VERSION_FREE
- self.appKey = @"ksw72buyettl2d4";
- #else
- #endif
-
- #if VERSION_PRO
- self.appKey = @"4tcmyravvap2dmu";
- #else
- self.appKey = @"4tcmyravvap2dmu";
- #endif
-
- NSString *registeredUrlToHandle = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"][0][@"CFBundleURLSchemes"][0];
- if (!self.appKey ||
- [registeredUrlToHandle rangeOfString:@"<"].location != NSNotFound) {
- NSString *message = @"You need to set `appKey` variable in `AppDelegate.m`, as well as add to `Info.plist`, before you can use DBRoulette.";
- NSLog(@"%@", message);
- exit(1);
- }
-
- [self getList:@""];
- [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
- andSelector:@selector(handleAppleEvent:withReplyEvent:)
- forEventClass:kInternetEventClass
- andEventID:kAEGetURL];
- }
- return self;
- }
- - (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
- NSURL *url = [NSURL URLWithString:[[event paramDescriptorForKeyword:keyDirectObject] stringValue]];
- [DBClientsManager handleRedirectURL:url completion:^(DBOAuthResult * _Nullable authResult) {
- [[DropboxModel shared] handleAuthResult:authResult];
- if (authResult != nil) {
- if ([authResult isSuccess]) {
- if ([self isSignedIn]) {
- DBUserClient *client = [DBClientsManager authorizedClient];
- [[client.usersRoutes getCurrentAccount] setResponseBlock:^(DBUSERSFullAccount * _Nullable result, DBNilObject * _Nullable routeError, DBRequestError * _Nullable networkError) {
- KMDropboxUserMetadata *model = [[KMDropboxUserMetadata alloc] init];
- model.accountId = result.accountId;
- model.givenName = result.name.givenName;
- model.surname = result.name.surname;
- model.email = result.email;
- model.emailVerified = result.emailVerified;
- model.disabled = result.disabled;
- model.country = result.country;
- model.locale = result.locale;
- model.referralLink = result.locale;
- [self setValue:result.accountId forKey:NSStringFromSelector(@selector(accountId))];
- [self setValue:[NSString stringWithFormat:@"%@%@",result.name.surname,result.name.givenName] forKey:NSStringFromSelector(@selector(name))];
-
- if (_cloudLoginBlock) {
- _cloudLoginBlock(model ,YES);
- }
- }];
- }
- [self getList:@""];
- } else if ([authResult isCancel]) {
- NSLog(@"Authorization flow was manually canceled by user!");
- } else if ([authResult isError]) {
- if (_cloudLoginBlock) {
- _cloudLoginBlock(nil, NO);
- }
- }
- [[NSRunningApplication currentApplication] activateWithOptions:(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)];
- }
- }];
-
- }
- - (KMServicesCloudFile *)cloudFolderCacheForDisPath:(NSString *)path
- {
- if (!path) {
- return self.localRootFolder;
- } else {
- return [self.cloudFilesCache objectForKey:path];
- }
- }
- - (BOOL)isSignedIn
- {
- return ([DBClientsManager authorizedClient] ? YES : NO);
- }
- - (NSString *)email {
- return [DropboxModel shared].userEmail;
- }
- #pragma mark - 授权登陆
- - (void)authorizedLoginCompletion:(CloudLoginCallBack)completion {
- self.cloudLoginBlock = completion;
- if (![self isSignedIn]) {
- [self dropboxLogin];
- } else {
- NSLog(@"已登陆");
- }
- }
- - (void)dropboxLogin {
-
- NSWindow *window = [NSApplication sharedApplication].mainWindow;
- NSViewController *viewC = window.contentViewController;
- [DBClientsManager authorizeFromControllerDesktop:[NSWorkspace sharedWorkspace] controller:viewC openURL:^(NSURL * _Nonnull url) {
- [[NSWorkspace sharedWorkspace] openURL:url];
- }];
-
- }
- #pragma mark - 取消授权
- - (void)authorizedLogoutCompletion:(CloudLogoutCallBack)completion {
- self.cloudLogoutBlock = completion;
- if ([DBClientsManager authorizedClient])
- {
- [DBClientsManager unlinkAndResetClients];
-
- if (_cloudLogoutBlock) {
- _cloudLogoutBlock(YES);
- }
- }
- }
- #pragma mark - 文件上传
- - (KMCloudOperation *)uploadCloudPath:(KMServicesCloudFile *)cloudPath
- localPath:(NSURL *)localPath
- currentConvetProgress:(CurrentProgressCallBack)currentProgress
- completion:(CompletionCallBack)completion
- {
- KMCloudUploadOperationQueue *queue = [KMCloudUploadOperationQueue sharedInstance];
- queue.maxConcurrentOperationCount = 4;
- queue.name = [localPath path];
-
- KMCloudOperation *op = [[KMCloudOperation alloc] initWithLoadCloudPath:cloudPath serverType:KMDropbox localPath:localPath loadState:KMCloudLoadState_Upload currentConvetProgress:currentProgress completion:completion];
-
- if (![self isSignedIn]) {
- [self dropboxLogin];
- } else {
- if (![self isLoadOperationExisting:op]) {
- [queue addUploadOperation:op];
- }
- }
- return op;
- }
- - (void)uploadCancel:(KMCloudOperation *)operation {
- if ([self isLoadOperationExisting:operation]) {
- [operation cancel];
- KMCloudUploadOperationQueue *queue = [KMCloudUploadOperationQueue sharedInstance];
- [queue cancel:operation.filePath];
- [self removeUploadOperation:operation];
- } else {
- return;
- }
- }
- #pragma mark - 文件下载
- - (KMCloudOperation *)downloadCloudPath:(KMServicesCloudFile *)cloudPath
- localPath:(NSURL *)localPath
- currentConvetProgress:(CurrentProgressCallBack)currentProgress
- completion:(CompletionCallBack)completion
- {
- KMCloudDownloadOperationQueue *queue = [KMCloudDownloadOperationQueue sharedInstance];
- queue.maxConcurrentOperationCount = 4;
- queue.name = cloudPath.displayName;
- KMCloudOperation *op = [[KMCloudOperation alloc] initWithLoadCloudPath:cloudPath
- serverType:KMDropbox
- localPath:localPath
- loadState:KMCloudLoadState_Download
- currentConvetProgress:currentProgress
- completion:completion];
- if (![self isSignedIn]) {
- [self dropboxLogin];
- } else {
- if (![self isLoadOperationExisting:op]) {
- [queue addDownloadOperation:op];
- }
- }
- return op;
- }
- - (void)downloadCancel:(KMCloudOperation *)operation {
- if ([self isLoadOperationExisting:operation]) {
- [operation cancel];
- KMCloudDownloadOperationQueue *queue = [KMCloudDownloadOperationQueue sharedInstance];
- [queue cancel:operation.filePath];
- [self removeDownloadOperation:operation];
- } else {
- return;
- }
- }
- #pragma mark - 文件删除
- - (void)deleteFileWithPath:(KMServicesCloudFile *)fileData
- completion:(CloudDeleteFileCallBack)completion
- {
- self.deleteFileBlock = completion;
- if (![self isSignedIn]) {
- [self dropboxLogin];
- } else {
- DBUserClient *client = [DBClientsManager authorizedClient];
- }
- }
- #pragma mark - 文件夹创建
- - (void)createFolderWithPath:(KMServicesCloudFile *)fileData
- folderName:(NSString *)folderName
- completion:(CreateFolderCallBack)completion
- {
- self.createFolderBlock = completion;
- NSString *pathUrl = [self getFolderPathWithFileData:fileData];
- if (![self isSignedIn]) {
- [self dropboxLogin];
- } else {
- DBUserClient *client = [DBClientsManager authorizedClient];
- }
- }
- #pragma mark - 文件列表信息
- - (void) getListWithFilePath:(KMServicesCloudFile *)fileData
- setResponseBlock:(GetFileListCallBack)responseBlock
- {
- self.getFileListBlock = responseBlock;
- NSString *pathUrl = [self getFolderPathWithFileData:fileData];
- if (fileData.displayName) {
- [self.cloudFilesCache setValue:fileData forKey:fileData.displayName];
- }
- if (![self isSignedIn]) {
- [self dropboxLogin];
- } else if ([pathUrl isEqualToString:@""] || pathUrl == nil) {
- [self getList:pathUrl];
- } else {
- _localFileList = [[NSMutableArray alloc] init];
- DBUserClient *client = [DBClientsManager authorizedClient];
- [[client.filesRoutes listFolder:pathUrl]
- setResponseBlock:^(DBFILESListFolderResult *response, DBFILESListFolderError *routeError, DBRequestError *networkError) {
- if (response) {
- NSArray<DBFILESMetadata *> *entries = response.entries;
- [self printEntries:entries];
- if (![response.hasMore boolValue]) {
- if (_getFileListBlock) {
- _getFileListBlock(_localFileList,KMDropbox,nil);
- [_localFileList removeAllObjects];
- }
- }
- } else {
- KMDropboxErrorMetadata *errorModel = [[KMDropboxErrorMetadata alloc] init];
- errorModel.routeError = [NSNumber numberWithInteger:routeError.tag];
- errorModel.networkError = [NSNumber numberWithInteger:networkError.statusCode.integerValue];
-
- if (_getFileListBlock) {
- _getFileListBlock(nil,KMDropbox,nil);
- }
- }
- }];
- }
- }
- - (void)getList:(NSString *)filePath {
- _localFileList = [[NSMutableArray alloc] init];
- DBUserClient *client = [DBClientsManager authorizedClient];
- [[client.filesRoutes listFolder:filePath.length < 1 ? @"" :filePath]
- setResponseBlock:^(DBFILESListFolderResult *response, DBFILESListFolderError *routeError, DBRequestError *networkError) {
- if (response) {
- NSArray<DBFILESMetadata *> *entries = response.entries;
- BOOL hasMore = [response.hasMore boolValue];
- [self printEntries:entries];
- if (hasMore) {
-
- } else {
- NSLog(@"List folder complete.");
- }
- if (_getFileListBlock) {
- _getFileListBlock(_localFileList,KMDropbox,nil);
- [_localFileList removeAllObjects];
- }
- } else {
- KMDropboxErrorMetadata *errorModel = [[KMDropboxErrorMetadata alloc] init];
- errorModel.routeError = [NSNumber numberWithInteger:routeError.tag];
- errorModel.networkError = [NSNumber numberWithInteger:networkError.statusCode.integerValue];
-
- if (_getFileListBlock) {
- _getFileListBlock(nil,KMDropbox,nil);
- }
- }
- }];
- }
- - (void)printEntries:(NSArray<DBFILESMetadata *> *)entries {
- for (DBFILESMetadata *entry in entries) {
- KMServicesCloudFile *fileModel = [[KMServicesCloudFile alloc] init];
- if ([entry isKindOfClass:[DBFILESFileMetadata class]]) {
- DBFILESFileMetadata *fileMetadata = (DBFILESFileMetadata *)entry;
- fileModel.client_modified = fileMetadata.clientModified;
- fileModel.content_hash = fileMetadata.contentHash;
- fileModel.fileId = fileMetadata.id_;
- fileModel.displayName = fileMetadata.pathDisplay;
- fileModel.path_lower = fileMetadata.pathLower;
- fileModel.rev = fileMetadata.rev;
- fileModel.fileModiDate = fileMetadata.serverModified;
- fileModel.fileSize = fileMetadata.size.integerValue;
- fileModel.filetype = KMCloudServiceFileType_File;
- fileModel.fileName = fileMetadata.name;
- [_localFileList addObject:fileModel];
- } else if ([entry isKindOfClass:[DBFILESFolderMetadata class]]) {
- DBFILESFolderMetadata *folderMetadata = (DBFILESFolderMetadata *)entry;
- fileModel.fileId = folderMetadata.id_;
- fileModel.fileName = folderMetadata.name;
- fileModel.displayName = folderMetadata.pathDisplay;
- fileModel.path_lower = folderMetadata.pathLower;
- fileModel.filetype = KMCloudServiceFileType_Folder;
- [_localFileList addObject:fileModel];
- }
- }
- }
- #pragma mark - private methods
- - (void)removeUploadOperation:(KMCloudOperation *)operation {
- KMCloudUploadOperationQueue *queue = [KMCloudUploadOperationQueue sharedInstance];
- if ([queue isUploadOperationExisting:operation.filePath]) {
- NSLog(@"removeUploadOperation operation.filePath == %@",operation.filePath);
- [queue cancel:operation.filePath];
- }
- }
- - (void)removeDownloadOperation:(KMCloudOperation *)operation {
- KMCloudDownloadOperationQueue *queue = [KMCloudDownloadOperationQueue sharedInstance];
- if ([queue isDownloadOperationExisting:operation.filePath]) {
- NSLog(@"removeOperation operation.filePath == %@",operation.filePath);
- [queue cancel:operation.filePath];
- }
- }
- - (BOOL)isLoadOperationExisting:(KMCloudOperation *)operation {
- KMCloudUploadOperationQueue *uploadQueue = [KMCloudUploadOperationQueue sharedInstance];
- KMCloudDownloadOperationQueue *downloadQueue = [KMCloudDownloadOperationQueue sharedInstance];
- NSMutableArray *operationArr = [NSMutableArray array];
- for (NSArray *opArr in @[uploadQueue.operations, downloadQueue.operations]) {
- for (int j = 0; j < opArr.count; j++) {
- [operationArr addObject:opArr[j]];
- }
- }
- for (KMCloudOperation *op in operationArr) {
- if ([op.filePath isEqualToString:operation.filePath]) {
- return YES;
- }
- }
- return NO;
- }
- - (NSString *)getFolderPathWithFileData:(KMServicesCloudFile *)fileData {
- if (KMCloudServiceFileType_Folder == fileData.filetype) {
- return fileData.displayName;
- } else {
- NSString *folderPath = [fileData.displayName stringByDeletingLastPathComponent];
- if ([folderPath isEqualToString:@"/"]) {
- return @"";
- } else {
- return folderPath;
- }
- }
- return nil;
- }
- - (KMServicesCloudFile *)localRootFolder {
- KMServicesCloudFile *fileData = [[KMServicesCloudFile alloc] init];
- fileData.displayName = @"";
- fileData.path_lower = @"";
- fileData.filetype = KMCloudServiceFileType_Folder;
- return fileData;
- }
- @end
|