Skip to content
This repository has been archived by the owner on Aug 16, 2023. It is now read-only.

Refactor system providers. #25

Merged
merged 3 commits into from
Jan 27, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Providers/Facebook/SimpleAuthFacebookProvider.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
// Copyright (c) 2013-2014 Byliner, Inc. All rights reserved.
//

#import "SimpleAuthSystemProvider.h"
#import "SimpleAuthProvider.h"

@interface SimpleAuthFacebookProvider : SimpleAuthSystemProvider
@interface SimpleAuthFacebookProvider : SimpleAuthProvider

@end
42 changes: 11 additions & 31 deletions Providers/Facebook/SimpleAuthFacebookProvider.m
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@

#import "SimpleAuthFacebookProvider.h"

#import "ACAccountStore+SimpleAuth.h"
#import <ReactiveCocoa/ReactiveCocoa.h>

@import Social;

@implementation SimpleAuthFacebookProvider

#pragma mark - SimpleAuthProvider
Expand Down Expand Up @@ -46,41 +49,18 @@ - (void)authorizeWithCompletion:(SimpleAuthRequestHandler)completion {

#pragma mark - Private

- (RACSignal *)systemAccounts {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
ACAccountStore *store = [[self class] accountStore];
ACAccountType *type = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *options = @{
ACFacebookAppIdKey : self.options[@"app_id"],
ACFacebookPermissionsKey : self.options[@"permissions"]
};
[store requestAccessToAccountsWithType:type options:options completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [store accountsWithAccountType:type];
NSUInteger numberOfAccounts = [accounts count];
if (numberOfAccounts == 0) {
error = (error ?: [[NSError alloc] initWithDomain:ACErrorDomain code:ACErrorAccountNotFound userInfo:nil]);
[subscriber sendError:error];
}
else {
[subscriber sendNext:accounts];
[subscriber sendCompleted];
}
}
else {
error = (error ?: [[NSError alloc] initWithDomain:ACErrorDomain code:ACErrorPermissionDenied userInfo:nil]);
[subscriber sendError:error];
}
}];
return nil;
}];
- (RACSignal *)allSystemAccounts {
NSDictionary *options = @{
ACFacebookAppIdKey : self.options[@"app_id"],
ACFacebookPermissionsKey : self.options[@"permissions"]
};
return [ACAccountStore SimpleAuth_accountsWithTypeIdentifier:ACAccountTypeIdentifierFacebook options:options];
}


- (RACSignal *)systemAccount {
return [[self systemAccounts] flattenMap:^RACStream *(NSArray *accounts) {
ACAccount *account = [accounts lastObject];
return [RACSignal return:account];
return [[self allSystemAccounts] map:^(NSArray *accounts) {
return [accounts lastObject];
}];
}

Expand Down
4 changes: 2 additions & 2 deletions Providers/Twitter/SimpleAuthTwitterProvider.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
// Copyright (c) 2013-2014 Byliner, Inc. All rights reserved.
//

#import "SimpleAuthSystemProvider.h"
#import "SimpleAuthProvider.h"

@interface SimpleAuthTwitterProvider : SimpleAuthSystemProvider
@interface SimpleAuthTwitterProvider : SimpleAuthProvider

@end
174 changes: 69 additions & 105 deletions Providers/Twitter/SimpleAuthTwitterProvider.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
#import "SimpleAuthTwitterProvider.h"

#import "UIWindow+SimpleAuthAdditions.h"

#import "ACAccountStore+SimpleAuth.h"
#import <cocoa-oauth/GCOAuth.h>
#import <ReactiveCocoa/ReactiveCocoa.h>

@import Social;

@implementation SimpleAuthTwitterProvider

#pragma mark - SimpleAuthProvider
Expand All @@ -35,29 +37,18 @@ + (NSDictionary *)defaultOptions {
}


#pragma mark - SimpleAuthSystemProvider

- (void)authorizeWithSystemAccount:(ACAccount *)account completion:(SimpleAuthRequestHandler)completion {
RACSignal *accountSignal = [self twitterAccountWithAccount:account];
RACSignal *accessTokenSignal = [self accessTokenWithAccount:account];
RACSignal *zipSignal = [RACSignal zip:@[ accountSignal, accessTokenSignal ] reduce:^(NSDictionary *accountDictionary, NSDictionary *accessTokenDictionary) {
return [self responseWithAccount:account accountDictionary:accountDictionary accessTokenDictionary:accessTokenDictionary];
}];
[[zipSignal deliverOn:[RACScheduler mainThreadScheduler]]
subscribeNext:^(NSDictionary *dictionary) {
completion(dictionary, nil);
}
error:^(NSError *error) {
completion(nil, error);
}];
}


- (void)loadSystemAccount:(SimpleAuthSystemAccountHandler)completion {
[[[self selectedTwitterAccount]
deliverOn:[RACScheduler mainThreadScheduler]]
subscribeNext:^(ACAccount *account) {
completion(account, nil);
- (void)authorizeWithCompletion:(SimpleAuthRequestHandler)completion {
[[[self systemAccount]
flattenMap:^(ACAccount *account) {
NSArray *signals = @[
[RACSignal return:account],
[self remoteAccountWithSystemAccount:account],
[self accessTokenWithSystemAccount:account]
];
return [self rac_liftSelector:@selector(dictionaryWithSystemAccount:remoteAccount:accessToken:) withSignalsFromArray:signals];
}]
subscribeNext:^(NSDictionary *response) {
completion(response, nil);
}
error:^(NSError *error) {
completion(nil, error);
Expand All @@ -67,45 +58,25 @@ - (void)loadSystemAccount:(SimpleAuthSystemAccountHandler)completion {

#pragma mark - Private

- (RACSignal *)allTwitterAccounts {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
ACAccountStore *store = [[self class] accountStore];
ACAccountType *type = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[store requestAccessToAccountsWithType:type options:nil completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [store accountsWithAccountType:type];
NSUInteger numberOfAccounts = [accounts count];
if (numberOfAccounts) {
[subscriber sendNext:accounts];
[subscriber sendCompleted];
}
else {
[subscriber sendError:(error ?: [[NSError alloc] initWithDomain:ACErrorDomain code:ACErrorAccountNotFound userInfo:nil])];
}
}
else {
[subscriber sendError:(error ?: [[NSError alloc] initWithDomain:ACErrorDomain code:ACErrorPermissionDenied userInfo:nil])];
}
}];
return nil;
}];
- (RACSignal *)allSystemAccounts {
return [ACAccountStore SimpleAuth_accountsWithTypeIdentifier:ACAccountTypeIdentifierTwitter options:nil];
}


- (RACSignal *)selectedTwitterAccount {
return [[self allTwitterAccounts] flattenMap:^RACStream *(NSArray *accounts) {
- (RACSignal *)systemAccount {
return [[self allSystemAccounts] flattenMap:^RACStream *(NSArray *accounts) {
if ([accounts count] == 1) {
ACAccount *account = [accounts lastObject];
return [RACSignal return:account];
}
else {
return [self twitterAccountFromAccounts:accounts];
return [self systemAccountFromAccounts:accounts];
}
}];
}


- (RACSignal *)twitterAccountFromAccounts:(NSArray *)accounts {
- (RACSignal *)systemAccountFromAccounts:(NSArray *)accounts {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
dispatch_async(dispatch_get_main_queue(), ^{
UIActionSheet *sheet = [UIActionSheet new];
Expand Down Expand Up @@ -133,114 +104,107 @@ - (RACSignal *)twitterAccountFromAccounts:(NSArray *)accounts {
}];

sheet.delegate = (id)sheet;
void (^block) (UIActionSheet *) = self.options[SimpleAuthPresentInterfaceBlockKey];
SimpleAuthInterfaceHandler block = self.options[SimpleAuthPresentInterfaceBlockKey];
block(sheet);
});
return nil;
}];
}


- (RACSignal *)requestTokenWithParameters:(NSDictionary *)parameters {
- (RACSignal *)reverseAuthRequestToken {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
NSDictionary *parameters = @{ @"x_auth_mode" : @"reverse_auth" };
NSURLRequest *request = [GCOAuth
URLRequestForPath:@"/oauth/request_token"
POSTParameters:parameters
scheme:@"https"
host:@"api.twitter.com"
consumerKey:self.options[@"consumer_key"]
consumerSecret:self.options[@"consumer_secret"]
accessToken:nil
tokenSecret:nil];
[NSURLConnection
sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
URLRequestForPath:@"/oauth/request_token"
POSTParameters:parameters
scheme:@"https"
host:@"api.twitter.com"
consumerKey:self.options[@"consumer_key"]
consumerSecret:self.options[@"consumer_secret"]
accessToken:nil
tokenSecret:nil];
[NSURLConnection sendAsynchronousRequest:request queue:self.operationQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 99)];
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode == 200 && data) {
if ([indexSet containsIndex:statusCode] && data) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[subscriber sendNext:string];
[subscriber sendCompleted];
}
else {
[subscriber sendError:error];
[subscriber sendError:connectionError];
}
}];
return nil;
}];
}


- (RACSignal *)accessTokenWithAccount:(ACAccount *)account {
- (RACSignal *)accessTokenWithSystemAccount:(ACAccount *)account {
return [[self reverseAuthRequestToken] flattenMap:^(NSString *token) {
return [self accessTokenWithReverseAuthRequestToken:token account:account];
}];
}


- (RACSignal *)twitterAccountWithAccount:(ACAccount *)account {
- (RACSignal *)remoteAccountWithSystemAccount:(ACAccount *)account {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
NSURL *URL = [NSURL URLWithString:@"https://api.twitter.com/1.1/account/verify_credentials.json"];
SLRequest *request = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:URL
parameters:nil];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:URL parameters:nil];
request.account = account;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *connectionError) {
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 99)];
NSInteger statusCode = [response statusCode];
if (statusCode == 200 && data) {
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[subscriber sendNext:dictionary];
[subscriber sendCompleted];
if ([indexSet containsIndex:statusCode] && data) {
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parseError];
if (dictionary) {
[subscriber sendNext:dictionary];
[subscriber sendCompleted];
}
else {
[subscriber sendNext:parseError];
}
}
else {
[subscriber sendError:error];
[subscriber sendError:connectionError];
}
}];
return nil;
}];
}


- (RACSignal *)reverseAuthRequestToken {
return [self requestTokenWithParameters:@{
@"x_auth_mode" : @"reverse_auth"
}];
}


- (RACSignal *)accessTokenWithReverseAuthRequestToken:(NSString *)token account:(ACAccount *)account {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
NSURL *URL = [NSURL URLWithString:@"https://api.twitter.com/oauth/access_token"];
NSDictionary *parameters = @{
@"x_reverse_auth_parameters" : token,
@"x_reverse_auth_target" : self.options[@"consumer_key"]
};
SLRequest *request = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:URL
parameters:parameters];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:URL parameters:parameters];
request.account = account;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *connectionError) {
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 99)];
NSInteger statusCode = [response statusCode];
if (statusCode == 200 && data) {
if ([indexSet containsIndex:statusCode] && data) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dictionary = [CMDQueryStringSerialization dictionaryWithQueryString:string];
[subscriber sendNext:dictionary];
[subscriber sendCompleted];
}
else {
[subscriber sendError:error];
[subscriber sendError:connectionError];
}
}];
return nil;
}];
}


- (NSDictionary *)responseWithAccount:(ACAccount *)account accountDictionary:(NSDictionary *)accountDictionary accessTokenDictionary:(NSDictionary *)accessToken {
- (NSDictionary *)dictionaryWithSystemAccount:(ACAccount *)systemAccount remoteAccount:(NSDictionary *)remoteAccount accessToken:(NSDictionary *)accessToken {
NSMutableDictionary *dictionary = [NSMutableDictionary new];

// Provider
Expand All @@ -253,31 +217,31 @@ - (NSDictionary *)responseWithAccount:(ACAccount *)account accountDictionary:(NS
};

// User ID
dictionary[@"uid"] = accountDictionary[@"id"];
dictionary[@"uid"] = remoteAccount[@"id"];

// Extra
dictionary[@"extra"] = @{
@"raw_info" : accountDictionary,
@"account" : account
@"raw_info" : remoteAccount,
@"account" : systemAccount
};

// Profile image
NSString *avatar = accountDictionary[@"profile_image_url_https"];
NSString *avatar = remoteAccount[@"profile_image_url_https"];
avatar = [avatar stringByReplacingOccurrencesOfString:@"_normal" withString:@""];

// Profile
NSString *profile = [NSString stringWithFormat:@"https://twitter.com/%@", accountDictionary[@"screen_name"]];
NSString *profile = [NSString stringWithFormat:@"https://twitter.com/%@", remoteAccount[@"screen_name"]];

// User info
NSMutableDictionary *user = [NSMutableDictionary new];
user[@"nickname"] = accountDictionary[@"screen_name"];
user[@"name"] = accountDictionary[@"name"];
user[@"location"] = accountDictionary[@"location"];
user[@"nickname"] = remoteAccount[@"screen_name"];
user[@"name"] = remoteAccount[@"name"];
user[@"location"] = remoteAccount[@"location"];
user[@"image"] = avatar;
user[@"description"] = accountDictionary[@"description"];
user[@"description"] = remoteAccount[@"description"];
user[@"urls"] = @{
@"Twitter" : profile,
@"Website" : accountDictionary[@"url"]
@"Website" : remoteAccount[@"url"]
};
dictionary[@"info"] = user;

Expand Down
Loading