Don Quihote

@ducphucphan

Rotate photo View full size
//
//  AppDelegate.m
//  TwiterApp
//
//  Created by Ku Tèo Hàng Xóm on 6/24/13.
//  Copyright (c) 2013 VTM. All rights reserved.
//

#include "Base64Transcoder.h"
#import "NSData+Base64FeedbackAdditions.h"

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>

#import "AppDelegate.h"
#import "QSStrings.h"

@implementation AppDelegate

#define TWITTER_OAUTH_CONSUMER_KEY      @"gj6xv6HULlL5XcsVIUqng"
#define TWITTER_OAUTH_CONSUMER_SECRET   @"L7C8LVAszXyZt2hMykpxh7nNNttnHHABC0QEcnAkco"
#define ACCESS_TOKEN                    @"107115404-5jYzIArQEv0TtW55wGdeuYpGEzqwqBOmIrliQSF3"
#define ACCESS_TOCKEN_SECRET            @"V5lz4DWFJE1X0pVcqTXIboTJuvamnll7lmD0pBcXeU"
#define TWITPIC_API_KEY                 @"869d42e60fc5ed0a473a2304e4610e02"
#define TWITPIC_API_VERSION             @"2"

#define oauth_token_key                 @"oauth_token"
#define oauth_token_secret_key          @"oauth_token_secret"

#define request_token                   @"https://api.twitter.com/oauth/request_token"
#define authorize                       @"https://api.twitter.com/oauth/authorize"
#define access_token                    @"https://api.twitter.com/oauth/access_token"
#define media                            @"https://api.twitter.com/1.1/statuses/update_with_media.json"

#define FETCH_PIN_STEP                  1
#define GUEST_PIN_STEP                  2
#define LOGIN                           3
#define UPLOAD                          4

- (id) init{
    self = [super init];
    if (self){
        oauth_token = nil;
        oauth_token_secret = nil;
        STEP = -1;
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}


- (NSString *)urlEncodeValue:(NSString *)str
{
    NSMutableString * output = [NSMutableString string];
    const unsigned char * source = (const unsigned char *)[str UTF8String];
    int sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
    
}

- (NSString *) generateNonce
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    NSMakeCollectable(theUUID);
    return (NSString *)string;
}

- (NSString *)signClearText:(NSString *)text withSecret:(NSString *)secret
{
    NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *clearTextData = [text dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[20];
	CCHmac(kCCHmacAlgSHA1, [secretData bytes], [secretData length], [clearTextData bytes], [clearTextData length], result);
    
    //Base64 Encoding
    
    char base64Result[32];
    size_t theResultLength = 32;
    Base64EncodeData(result, 20, base64Result, &theResultLength);
    NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];
    
    NSString *base64EncodedResult = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
    
    return [base64EncodedResult autorelease];
}


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    
}

- (NSMutableArray *) allParameterFromArray: (NSMutableArray *) _array withSignOfValue: (NSString *) _sign{
    NSMutableArray *tmpArr = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in _array){
        NSString *key = (NSString *)[[dict allKeys] objectAtIndex: 0];
        NSString *value = [dict valueForKey: key];
        [tmpArr addObject: [NSString stringWithFormat: @"%@=%@%@%@", key, _sign, [value URLEncodedString], _sign]];
    }
    return [tmpArr autorelease];
}

- (NSString *) findSignature: (NSMutableArray *) array withURLString: (NSString *) urlString andHTTPMethod: (NSString *)HTTPMethod{
    
    NSString *normalizedRequestParameters = [[self allParameterFromArray: array withSignOfValue: @""] componentsJoinedByString:@"&"];
    
    NSURL *URL = [NSURL URLWithString: urlString];
    
    NSString *ret = [NSString stringWithFormat:@"%@&%@&%@",
					 HTTPMethod,
					 [[URL URLStringWithoutQuery] URLEncodedString],
					 [normalizedRequestParameters URLEncodedString]];
    
    NSString *_signature = [self signClearText: ret
                                   withSecret:[NSString stringWithFormat:@"%@&%@",
                                               [_consumerSecretTextField.stringValue URLEncodedString],
                                               
                                               //Token Secret
                                               [@"" URLEncodedString]]];
    
    //I have a signature
    return _signature;
}



- (IBAction)fetchPIN:(id)sender{
    
    [loginError setHidden: YES];
    [getAccessTokenError setHidden: YES];
    STEP = FETCH_PIN_STEP;
    
    //for timestamp
    intervalFloat = [[NSDate date] timeIntervalSince1970];
    
    generateNonce = [[self generateNonce] retain];
    
    NSMutableArray *array = [[NSMutableArray arrayWithObjects:
                      [NSDictionary dictionaryWithObjectsAndKeys: @"oob", @"oauth_callback", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys: [_consumerKeyTextField.stringValue URLEncodedString], @"oauth_consumer_key", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys: generateNonce, @"oauth_nonce", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys: @"HMAC-SHA1", @"oauth_signature_method", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys: [NSString stringWithFormat: @"%i", (int) intervalFloat], @"oauth_timestamp", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys: @"1.0", @"oauth_version", nil],                      
                      nil] retain];
    NSString *HTTPMethod = @"POST";

    NSString *signature = [self findSignature: array withURLString: request_token andHTTPMethod: HTTPMethod];
    
    [array insertObject: [NSDictionary dictionaryWithObjectsAndKeys: @"", @"OAuth realm", nil] atIndex: 0];
    [array addObject: [NSDictionary dictionaryWithObjectsAndKeys: signature, @"oauth_signature", nil]];

    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: request_token]];
    [request addRequestHeader: @"Authorization" value: [[self allParameterFromArray: array withSignOfValue: @"\""] componentsJoinedByString:@","]];

    request.delegate = self;
    [request startAsynchronous];
    
}

- (IBAction) guestPin:(id)sender{
    
    [loginError setHidden: YES];
    [getAccessTokenError setHidden: YES];
    STEP = GUEST_PIN_STEP;
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: @"https://api.twitter.com/oauth/authorize"]];
    [request setRequestMethod:@"POST"];
    [request setPostValue: oauth_token_secret forKey:@"authenticity_token"];
    [request setPostValue: oauth_token forKey:@"oauth_token"];
    [request setPostValue: username.stringValue forKey:@"session[username_or_email]"];
    [request setPostValue: password.stringValue forKey:@"session[password]"];
    [request setPostValue: @"0" forKey:@"remember_me"];
    request.delegate = self;
    [request startAsynchronous];
    
}

- (IBAction) login:(id)sender{
    
    [getAccessTokenError setHidden: YES];
    STEP = LOGIN;
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: @"https://api.twitter.com/oauth/access_token"]];
    [request setRequestMethod:@"POST"];
    [request setPostValue: [_consumerKeyTextField.stringValue URLEncodedString] forKey:@"oauth_consumer_key"];
    [request setPostValue: generateNonce forKey:@"oauth_nonce"];
    [request setPostValue: @"HMAC-SHA1" forKey:@"oauth_signature_method"];
    [request setPostValue: [NSString stringWithFormat: @"%i", (int)intervalFloat] forKey:@"oauth_timestamp"];
    [request setPostValue: [oauth_token URLEncodedString] forKey:@"oauth_token"];
    [request setPostValue: [pinStatus2.stringValue URLEncodedString] forKey:@"oauth_verifier"];    
    [request setPostValue: @"1.0" forKey:@"oauth_version"];
    request.delegate = self;
    [request startAsynchronous];
}


- (void) opendialogAndSavePathTo: (NSTextField *)tf andFormatFile: (NSArray *) fileTypes{
	NSString *_pathFile = @"";
	NSOpenPanel* oPanel = [NSOpenPanel openPanel];
	[oPanel setCanChooseDirectories:NO];		// Disable the selection of directories in the dialog.
	[oPanel setCanChooseFiles:YES];				// Enable the selection of files in the dialog.
	[oPanel setCanCreateDirectories:YES];		// Enable the creation of directories in the dialog
	[oPanel setAllowsMultipleSelection:NO];		// Allow multiple files selection
	[oPanel setAlphaValue:1.0];				// Alpha value
	[oPanel setTitle:@"Select file"];
	
	if ( [oPanel runModalForDirectory:nil file:nil types:fileTypes] == NSOKButton ){
		NSArray* files = [oPanel filenames];
		// Loop through all the files and process them.
		for( int i = 0; i < [files count]; i++ ){
			_pathFile = [files objectAtIndex:i];
			[tf setStringValue: _pathFile];
		}
	}else {  //[oPanel runModalForDirectory:nil file:nil types:fileTypes] == NSCancelButton
		[tf setStringValue:@""];
		return;
	}
}


- (IBAction) uploadPhotoAction:(id)sender{
    
    STEP = UPLOAD;
    
    [progressBar setIndeterminate: NO];
    [progressBar setDoubleValue: 0.0f];
    
    switch ([sender tag]) {
        case 1:
            [self opendialogAndSavePathTo: imageSrc andFormatFile: [NSArray arrayWithObjects: @"png", @"PNG", @"jpg", @"JPG", nil]];
            break;
        case 2:
        {
            
            ASIFormDataRequest *postRequest = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: @"http://api.twitpic.com/1/uploadAndPost.xml"]];
            [postRequest setRequestMethod:@"POST"];
            
            // just some random text that will never occur in the body
            NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
            // header value
            NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
            // set header
            [postRequest addRequestHeader:@"Content-Type" value:headerBoundary];
            
            NSMutableData *postBody = [NSMutableData data];
            
            // api_key
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData: [@"Content-Disposition: form-data; name=\"key\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData: [@"869d42e60fc5ed0a473a2304e4610e02" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData: [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
            // consumer_token
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Disposition: form-data; name=\"consumer_token\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[TWITTER_OAUTH_CONSUMER_KEY dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
            // consumer_secret
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Disposition: form-data; name=\"consumer_secret\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[TWITTER_OAUTH_CONSUMER_SECRET dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
            //oauth_token
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Disposition: form-data; name=\"oauth_token\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[access_oauth_token.stringValue dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
            //oauth_secret
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Disposition: form-data; name=\"oauth_secret\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[access_oauth_token_secret.stringValue dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
            // message part
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Disposition: form-data; name=\"message\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[[comment string] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
            
            // media part
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Disposition: form-data; name=\"media\"; filename=\"fish.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
            NSImage *_img = [[NSImage alloc] initWithContentsOfFile:imageSrc.stringValue];
            NSData *imageData = [_img TIFFRepresentation];
            
            // add it to body
            [postBody appendData:imageData];
            [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            
            // final boundary
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
            
            

            
            [postRequest setPostBody: postBody];
            
            [postRequest setUploadProgressDelegate: self];


                
            postRequest.delegate = self;
            [postRequest startAsynchronous];
        }
            break;
    }
}


- (void) requestStarted:(ASIHTTPRequest *)_request{
    NSLog(@"requestStarted.....%@", _request);
}

- (void) requestFinished:(ASIHTTPRequest *)_request{
    
    NSString *result = [_request responseString];
    
    switch (STEP) {
        case FETCH_PIN_STEP:
        {
            //Find oauth_token_secret and oauth_token
            NSArray *tmpArr1 = [result componentsSeparatedByString: @"&"];
            for (NSString *tmpStr in tmpArr1){
                NSArray *tmpArr2 = [tmpStr componentsSeparatedByString: @"="];
                if ([tmpArr2 count] == 2){
                    NSString *key = (NSString *)[tmpArr2 objectAtIndex: 0];
                    if ([key isEqualToString: oauth_token_secret_key]){
                        oauth_token_secret = [tmpArr2 objectAtIndex: 1];
                        [oauth_token_secret retain];
                    }else if ([key isEqualToString: oauth_token_key]){
                        oauth_token = [tmpArr2 objectAtIndex: 1];
                        [oauth_token retain];
                    }
                }
            }
            
            pinStatus1.stringValue = [NSString stringWithFormat: @"%@?%@", authorize, result];
        }
            break;
        case GUEST_PIN_STEP:
        {
            if (([result rangeOfString: @"<code>"].location != NSNotFound) && ([result rangeOfString: @"</code>"].location != NSNotFound)) {
                NSArray *tmpArr = [result componentsSeparatedByString: @"<code>"];
                tmpArr = [[tmpArr objectAtIndex: 1] componentsSeparatedByString: @"</code>"];
                pinStatus2.stringValue = [tmpArr objectAtIndex: 0];
            }else{
                [loginError setHidden: NO];
                loginError.stringValue = [NSString stringWithFormat: @"[Login Error]: %@", result];
            }
        }
            break;
        
        case LOGIN:
        {
            NSArray *tmpArr1 = [result componentsSeparatedByString: @"&"];
            for (NSString *tmpString in tmpArr1){
                NSArray *tmpArr2 = [tmpString componentsSeparatedByString: @"="];
                if ([tmpArr2 count] == 2){
                    if ([[tmpArr2 objectAtIndex: 0] isEqualToString: @"oauth_token"]) {
                        access_oauth_token.stringValue = [tmpArr2 objectAtIndex: 1];
                    }else if ([[tmpArr2 objectAtIndex: 0] isEqualToString: @"oauth_token_secret"]) {
                        access_oauth_token_secret.stringValue = [tmpArr2 objectAtIndex: 1];
                    }else if ([[tmpArr2 objectAtIndex: 0] isEqualToString: @"user_id"]) {
                        userID.stringValue = [tmpArr2 objectAtIndex: 1];
                    }else if ([[tmpArr2 objectAtIndex: 0] isEqualToString: @"screen_name"]) {
                        screenName.stringValue = [tmpArr2 objectAtIndex: 1];
                    }
                }
            }
        }
        
            break;
            
        case UPLOAD:
            NSLog(@"%@", result);
            break;
    }
}

- (void) requestFailed:(ASIHTTPRequest *) _request{
    switch (STEP) {
        case FETCH_PIN_STEP:
            pinStatus1.stringValue = [_request responseString];
            break;
        case GUEST_PIN_STEP:
            pinStatus2.stringValue = [_request responseString];
            break;
        case LOGIN:
            [getAccessTokenError setHidden: NO];
            getAccessTokenError.stringValue = [_request responseString];
            break;
            
        case UPLOAD:
        {
            NSAlert *alert = [NSAlert alertWithMessageText: @"Done !"
                                             defaultButton: @"OK"
                                           alternateButton: nil
                                               otherButton: nil
                                 informativeTextWithFormat: @"" ];
            [alert runModal];
        }
            break;
    }
}

- (void)setDoubleValue:(double)newProgress{
    [progressBar setIndeterminate: NO];
    [progressBar setDoubleValue: newProgress];
}

@end


@implementation NSString (AppDelegate)
- (NSString *)URLEncodedString
{
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                           (CFStringRef)self,
                                                                           NULL,
																		   CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                           kCFStringEncodingUTF8);
    [result autorelease];
	return result;
}

- (NSString*)URLDecodedString
{
	NSString *result = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
																						   (CFStringRef)self,
																						   CFSTR(""),
																						   kCFStringEncodingUTF8);
    [result autorelease];
	return result;
}

@end

@implementation NSURL (AppDelegate)

- (NSString *)URLStringWithoutQuery
{
    NSArray *parts = [[self absoluteString] componentsSeparatedByString:@"?"];
    return [parts objectAtIndex:0];
}

@end

Views 150

464 days ago

//
// AppDelegate.m
// TwiterApp
//
// Created by Ku Tèo Hàng Xóm on 6/24/13.
// Copyright (c) 2013 VTM. All rights reserved.
//

#include "Base64Transcoder.h"
#import "NSData+Base64FeedbackAdditions.h"

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>

#import "AppDelegate.h"
#import "QSStrings.h"

AppDelegate

#define TWITTER_OAUTH_CONSUMER_KEY @"gj6xv6HULlL5XcsVIUqng"
#define TWITTER_OAUTH_CONSUMER_SECRET @"L7C8LVAszXyZt2hMykpxh7nNNttnHHABC0QEcnAkco"
#define ACCESS_TOKEN @"107115404-5jYzIArQEv0TtW55wGdeuYpGEzqwqBOmIrliQSF3"
#define ACCESS_TOCKEN_SECRET @"V5lz4DWFJE1X0pVcqTXIboTJuvamnll7lmD0pBcXeU"
#define TWITPIC_API_KEY @"869d42e60fc5ed0a473a2304e4610e02"
#define TWITPIC_API_VERSION @"2"

#define oauth_token_key @"oauth_token"
#define oauth_token_secret_key @"oauth_token_secret"

#define request_token @";https://api.twitter.com/oauth/request_token"
#define authorize @";https://api.twitter.com/oauth/authorize"
#define access_token @";https://api.twitter.com/oauth/access_token"
#define media @";https://api.twitter.com/1.1/statuses/update_with_media.json"

#define FETCH_PIN_STEP 1
#define GUEST_PIN_STEP 2
#define LOGIN 3
#define UPLOAD 4

- (id) init{
self = [super init];
if (self){
oauth_token = nil;
oauth_token_secret = nil;
STEP = -1;
}
return self;
}

- (void)dealloc
{
[super dealloc];
}


- (NSString *)urlEncodeValue:(NSString *)str
{
NSMutableString * output = [NSMutableString string];
const unsigned char * source = (const unsigned char *)[str UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;

}

- (NSString *) generateNonce
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
NSMakeCollectable(theUUID);
return (NSString *)string;
}

- (NSString *)signClearText:(NSString *)text withSecret:(NSString *)secret
{
NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSData *clearTextData = [text dataUsingEncoding:NSUTF8StringEncoding];
unsigned char result[20];
CCHmac(kCCHmacAlgSHA1, [secretData bytes], [secretData length], [clearTextData bytes], [clearTextData length], result);

//Base64 Encoding

char base64Result[32];
size_t theResultLength = 32;
Base64EncodeData(result, 20, base64Result, &theResultLength);
NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];

NSString *base64EncodedResult = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

return [base64EncodedResult autorelease];
}


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

}

- (NSMutableArray *) allParameterFromArray: (NSMutableArray *) _array withSignOfValue: (NSString *) _sign{
NSMutableArray *tmpArr = [[NSMutableArray alloc] init];
for (NSDictionary *dict in _array){
NSString *key = (NSString *)[[dict allKeys] objectAtIndex: 0];
NSString *value = [dict valueForKey: key];
[tmpArr addObject: [NSString stringWithFormat: @"%@=%@%@%@", key, _sign, [value URLEncodedString], _sign]];
}
return [tmpArr autorelease];
}

- (NSString *) findSignature: (NSMutableArray *) array withURLString: (NSString *) urlString andHTTPMethod: (NSString *)HTTPMethod{

NSString *normalizedRequestParameters = [[self allParameterFromArray: array withSignOfValue: @""] componentsJoinedByString:@"&"];

NSURL *URL = [NSURL URLWithString: urlString];

NSString *ret = [NSString stringWithFormat:@"%@&%@&%@",
HTTPMethod,
[[URL URLStringWithoutQuery] URLEncodedString],
[normalizedRequestParameters URLEncodedString]];

NSString *_signature = [self signClearText: ret
withSecret:[NSString stringWithFormat:@"%@&%@",
[_consumerSecretTextField.stringValue URLEncodedString],

//Token Secret
[@"" URLEncodedString]]];

//I have a signature
return _signature;
}



- (IBAction)fetchPIN:(id)sender{

[loginError setHidden: YES];
[getAccessTokenError setHidden: YES];
STEP = FETCH_PIN_STEP;

//for timestamp
intervalFloat = [[NSDate date] timeIntervalSince1970];

generateNonce = [[self generateNonce] retain];

NSMutableArray *array = [[NSMutableArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys: @"oob", @"oauth_callback", nil],
[NSDictionary dictionaryWithObjectsAndKeys: [_consumerKeyTextField.stringValue URLEncodedString], @"oauth_consumer_key", nil],
[NSDictionary dictionaryWithObjectsAndKeys: generateNonce, @"oauth_nonce", nil],
[NSDictionary dictionaryWithObjectsAndKeys: @"HMAC-SHA1", @"oauth_signature_method", nil],
[NSDictionary dictionaryWithObjectsAndKeys: [NSString stringWithFormat: @"%i", (int) intervalFloat], @"oauth_timestamp", nil],
[NSDictionary dictionaryWithObjectsAndKeys: @"1.0", @"oauth_version", nil],
nil] retain];
NSString *HTTPMethod = @"POST";

NSString *signature = [self findSignature: array withURLString: request_token andHTTPMethod: HTTPMethod];

[array insertObject: [NSDictionary dictionaryWithObjectsAndKeys: @"", @"OAuth realm", nil] atIndex: 0];
[array addObject: [NSDictionary dictionaryWithObjectsAndKeys: signature, @"oauth_signature", nil]];


ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: request_token]];
[request addRequestHeader: @"Authorization" value: [[self allParameterFromArray: array withSignOfValue: @"\""] componentsJoinedByString:@","]];

request.delegate = self;
[request startAsynchronous];

}

- (IBAction) guestPin:(id)sender{

[loginError setHidden: YES];
[getAccessTokenError setHidden: YES];
STEP = GUEST_PIN_STEP;

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: @";https://api.twitter.com/oauth/authorize"]];
[request setRequestMethod:@"POST"];
[request setPostValue: oauth_token_secret forKey:@"authenticity_token"];
[request setPostValue: oauth_token forKey:@"oauth_token"];
[request setPostValue: username.stringValue forKey:@"session[username_or_email]"];
[request setPostValue: password.stringValue forKey:@"session[password]"];
[request setPostValue: @"0" forKey:@"remember_me"];
request.delegate = self;
[request startAsynchronous];

}

- (IBAction) login:(id)sender{

[getAccessTokenError setHidden: YES];
STEP = LOGIN;

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: @";https://api.twitter.com/oauth/access_token"]];
[request setRequestMethod:@"POST"];
[request setPostValue: [_consumerKeyTextField.stringValue URLEncodedString] forKey:@"oauth_consumer_key"];
[request setPostValue: generateNonce forKey:@"oauth_nonce"];
[request setPostValue: @"HMAC-SHA1" forKey:@"oauth_signature_method"];
[request setPostValue: [NSString stringWithFormat: @"%i", (int)intervalFloat] forKey:@"oauth_timestamp"];
[request setPostValue: [oauth_token URLEncodedString] forKey:@"oauth_token"];
[request setPostValue: [pinStatus2.stringValue URLEncodedString] forKey:@"oauth_verifier"];
[request setPostValue: @"1.0" forKey:@"oauth_version"];
request.delegate = self;
[request startAsynchronous];
}


- (void) opendialogAndSavePathTo: (NSTextField *)tf andFormatFile: (NSArray *) fileTypes{
NSString *_pathFile = @"";
NSOpenPanel* oPanel = [NSOpenPanel openPanel];
[oPanel setCanChooseDirectories:NO]; // Disable the selection of directories in the dialog.
[oPanel setCanChooseFiles:YES]; // Enable the selection of files in the dialog.
[oPanel setCanCreateDirectories:YES]; // Enable the creation of directories in the dialog
[oPanel setAllowsMultipleSelection:NO]; // Allow multiple files selection
[oPanel setAlphaValue:1.0]; // Alpha value
[oPanel setTitle:@"Select file"];

if ( [oPanel runModalForDirectory:nil file:nil types:fileTypes] == NSOKButton ){
NSArray* files = [oPanel filenames];
// Loop through all the files and process them.
for( int i = 0; i < [files count]; i++ ){
_pathFile = [files objectAtIndex:i];
[tf setStringValue: _pathFile];
}
}else { //[oPanel runModalForDirectory:nil file:nil types:fileTypes] == NSCancelButton
[tf setStringValue:@""];
return;
}
}


- (IBAction) uploadPhotoAction:(id)sender{

STEP = UPLOAD;

[progressBar setIndeterminate: NO];
[progressBar setDoubleValue: 0.0f];

switch ([sender tag]) {
case 1:
[self opendialogAndSavePathTo: imageSrc andFormatFile: [NSArray arrayWithObjects: @"png", @"PNG", @"jpg", @"JPG", nil]];
break;
case 2:
{

ASIFormDataRequest *postRequest = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: @";http://api.twitpic.com/1/uploadAndPost.xml"]];
[postRequest setRequestMethod:@"POST"];

// just some random text that will never occur in the body
NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
// header value
NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
// set header
[postRequest addRequestHeader:@"Content-Type" value:headerBoundary];

NSMutableData *postBody = [NSMutableData data];

// api_key
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData: [@"Content-Disposition: form-data; name=\"key\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData: [@"869d42e60fc5ed0a473a2304e4610e02" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData: [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// consumer_token
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"consumer_token\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[TWITTER_OAUTH_CONSUMER_KEY dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// consumer_secret
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"consumer_secret\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[TWITTER_OAUTH_CONSUMER_SECRET dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//oauth_token
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"oauth_token\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[access_oauth_token.stringValue dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//oauth_secret
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"oauth_secret\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[access_oauth_token_secret.stringValue dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// message part
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"message\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[comment string] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


// media part
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"media\"; filename=\";fish.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

NSImage *_img = [[NSImage alloc] initWithContentsOfFile:imageSrc.stringValue];
NSData *imageData = [_img TIFFRepresentation];

// add it to body
[postBody appendData:imageData];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// final boundary
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];




[postRequest setPostBody: postBody];

[postRequest setUploadProgressDelegate: self];



postRequest.delegate = self;
[postRequest startAsynchronous];
}
break;
}
}


- (void) requestStarted:(ASIHTTPRequest *)_request{
NSLog(@"requestStarted.....%@", _request);
}

- (void) requestFinished:(ASIHTTPRequest *)_request{

NSString *result = [_request responseString];

switch (STEP) {
case FETCH_PIN_STEP:
{
//Find oauth_token_secret and oauth_token
NSArray *tmpArr1 = [result componentsSeparatedByString: @"&"];
for (NSString *tmpStr in tmpArr1){
NSArray *tmpArr2 = [tmpStr componentsSeparatedByString: @"="];
if ([tmpArr2 count] == 2){
NSString *key = (NSString *)[tmpArr2 objectAtIndex: 0];
if ([key isEqualToString: oauth_token_secret_key]){
oauth_token_secret = [tmpArr2 objectAtIndex: 1];
[oauth_token_secret retain];
}else if ([key isEqualToString: oauth_token_key]){
oauth_token = [tmpArr2 objectAtIndex: 1];
[oauth_token retain];
}
}
}

pinStatus1.stringValue = [NSString stringWithFormat: @"%@?%@", authorize, result];
}
break;
case GUEST_PIN_STEP:
{
if (([result rangeOfString: @"<code>"].location != NSNotFound) && ([result rangeOfString: @"</code>"].location != NSNotFound)) {
NSArray *tmpArr = [result componentsSeparatedByString: @"<code>"];
tmpArr = [[tmpArr objectAtIndex: 1] componentsSeparatedByString: @"</code>"];
pinStatus2.stringValue = [tmpArr objectAtIndex: 0];
}else{
[loginError setHidden: NO];
loginError.stringValue = [NSString stringWithFormat: @"[Login Error]: %@", result];
}
}
break;

case LOGIN:
{
NSArray *tmpArr1 = [result componentsSeparatedByString: @"&"];
for (NSString *tmpString in tmpArr1){
NSArray *tmpArr2 = [tmpString componentsSeparatedByString: @"="];
if ([tmpArr2 count] == 2){
if ([[tmpArr2 objectAtIndex: 0] isEqualToString: @"oauth_token"]) {
access_oauth_token.stringValue = [tmpArr2 objectAtIndex: 1];
}else if ([[tmpArr2 objectAtIndex: 0] isEqualToString: @"oauth_token_secret"]) {
access_oauth_token_secret.stringValue = [tmpArr2 objectAtIndex: 1];
}else if ([[tmpArr2 objectAtIndex: 0] isEqualToString: @"user_id"]) {
userID.stringValue = [tmpArr2 objectAtIndex: 1];
}else if ([[tmpArr2 objectAtIndex: 0] isEqualToString: @"screen_name"]) {
screenName.stringValue = [tmpArr2 objectAtIndex: 1];
}
}
}
}

break;

case UPLOAD:
NSLog(@"%@", result);
break;
}
}

- (void) requestFailed:(ASIHTTPRequest *) _request{
switch (STEP) {
case FETCH_PIN_STEP:
pinStatus1.stringValue = [_request responseString];
break;
case GUEST_PIN_STEP:
pinStatus2.stringValue = [_request responseString];
break;
case LOGIN:
[getAccessTokenError setHidden: NO];
getAccessTokenError.stringValue = [_request responseString];
break;

case UPLOAD:
{
NSAlert *alert = [NSAlert alertWithMessageText: @"Done !"
defaultButton: @"OK"
alternateButton: nil
otherButton: nil
informativeTextWithFormat: @"" ];
[alert runModal];
}
break;
}
}

- (void)setDoubleValue:(double)newProgress{
[progressBar setIndeterminate: NO];
[progressBar setDoubleValue: newProgress];
}




NSString (AppDelegate)
- (NSString *)URLEncodedString
{
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]"),
kCFStringEncodingUTF8);
[result autorelease];
return result;
}

- (NSString*)URLDecodedString
{
NSString *result = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
(CFStringRef)self,
CFSTR(""),
kCFStringEncodingUTF8);
[result autorelease];
return result;
}



NSURL (AppDelegate)

- (NSString *)URLStringWithoutQuery
{
NSArray *parts = [[self absoluteString] componentsSeparatedByString:@"?"];
return [parts objectAtIndex:0];
}


0 Comments

Realtime comments disabled