Skip to content

Commit

Permalink
cleanup and fancier demo UI
Browse files Browse the repository at this point in the history
  • Loading branch information
gpolak committed Aug 13, 2014
1 parent 0be5a5c commit 5ac648a
Show file tree
Hide file tree
Showing 12 changed files with 867 additions and 92 deletions.
2 changes: 2 additions & 0 deletions FGTranslator/FGTranslateRequest.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,6 @@ enum
clientSecret:(NSString *)clientSecret
completion:(void (^)(NSString *translatedMessage, NSString *detectedSource, NSError *error))completion;

+ (void)flushCredentials;

@end
47 changes: 15 additions & 32 deletions FGTranslator/FGTranslateRequest.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#import "FGTranslateRequest.h"
#import "FGAzureToken.h"
#import "NSString+FGTranslator.h"
#import "XMLDictionary.h"


@implementation FGTranslateRequest
Expand Down Expand Up @@ -81,8 +82,6 @@ + (AFHTTPRequestOperation *)bingTranslateMessage:(NSString *)message
FGAzureToken *token = [FGTranslateRequest azureToken];
if ([token isValid])
{
// TODO: remove
NSLog(@"azure token still valid");
return [FGTranslateRequest doBingTranslateMessage:message
withSource:source
target:target
Expand All @@ -91,9 +90,6 @@ + (AFHTTPRequestOperation *)bingTranslateMessage:(NSString *)message
}
else
{
// TODO: remove
NSLog(@"azure token expired, will retrieve");

__block AFHTTPRequestOperation *operation;
operation = [FGTranslateRequest getBingAuthTokenWithId:clientId secret:clientSecret completion:^(FGAzureToken *token, NSError *error) {
if (!error)
Expand All @@ -103,8 +99,6 @@ + (AFHTTPRequestOperation *)bingTranslateMessage:(NSString *)message
}
else
{
// TODO: remove
NSLog(@"could not generate Azure token:%@", error);
NSError *fgError = [NSError errorWithDomain:FG_TRANSLATOR_ERROR_DOMAIN code:FGTranslationErrorNoToken userInfo:error.userInfo];
completion(nil, nil, fgError);
}
Expand Down Expand Up @@ -145,35 +139,18 @@ + (AFHTTPRequestOperation *)doBingTranslateMessage:(NSString *)message

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"BING XML:%@", responseObject);
XMLDictionaryParser *parser = [XMLDictionaryParser sharedInstance];
NSDictionary *dict = [parser dictionaryWithParser:responseObject];
NSLog(@"BING DICT:%@", dict);
NSLog(@"BING XML:%@", [dict innerText]);
completion([dict innerText], nil, nil);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSError *fgError = [NSError errorWithDomain:FG_TRANSLATOR_ERROR_DOMAIN code:FGTranslationErrorOther userInfo:error.userInfo];
completion(nil, nil, fgError);
}];
//
// AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//
// if (FGIsDebugEnabled)
// {
// NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"Bing translate response:%@", responseString);
// }
//
// XMLDictionaryParser *parser = [XMLDictionaryParser sharedInstance];
// NSDictionary *dict = [parser dictionaryWithData:responseObject];
//
// completion([dict innerText], nil, nil);
//
// } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
// FGDebug(@"unable to translate with bing:%@", error);
// NSError *fgError = [NSError errorWithDomain:FG_TRANSLATION_ERROR_DOMAIN code:FGTranslationErrorOther userInfo:nil];
// completion(nil, nil, fgError);
//
// }];

[operation start];
return operation;
}
Expand Down Expand Up @@ -204,8 +181,6 @@ + (AFHTTPRequestOperation *)getBingAuthTokenWithId:(NSString *)clientId
NSDate *expiration = [NSDate dateWithTimeIntervalSinceNow:expiry];

FGAzureToken *azureToken = [[FGAzureToken alloc] initWithToken:token expiry:expiration];
// TODO: remove this
NSLog(@"Azure token: %@", azureToken);

completion(azureToken, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
Expand All @@ -217,6 +192,14 @@ + (AFHTTPRequestOperation *)getBingAuthTokenWithId:(NSString *)clientId
return operation;
}

+ (void)flushCredentials
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:FG_TRANSLATOR_AZURE_TOKEN];
[defaults removeObjectForKey:FG_TRANSLATOR_AZURE_TOKEN_EXPIRY];
[defaults synchronize];
}

+ (void)setAzureToken:(FGAzureToken *)azureToken
{
if (!azureToken)
Expand Down
4 changes: 2 additions & 2 deletions FGTranslator/FGTranslator.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@ enum FGTranslatorError
FGTranslatorErrorSame = 2,
FGTranslatorErrorTranslationInProgress = 3,
FGTranslatorErrorAlreadyTranslated = 4,
FGTranslatorErrorMissingCredentials = 5
};

@interface FGTranslator : NSObject
{
// TODO: is this needed?
__strong FGTranslator *_retained_self;
}

@property (nonatomic) BOOL preferSourceGuess;
Expand All @@ -47,5 +46,6 @@ typedef void (^FGTranslatorCompletionHandler)(NSError *error, NSString *translat
- (void)cancelTranslation;

+ (void)flushCache;
+ (void)flushCredentials;

@end
110 changes: 75 additions & 35 deletions FGTranslator/FGTranslator.m
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,6 @@ - (id)initWithBingAzureClientId:(NSString *)clientId secret:(NSString *)secret
return self;
}

// TODO: remove this
- (void)dealloc
{
NSLog(@"FGTranslator dealloc called");
}

+ (NSCache *)translationCache
{
static dispatch_once_t pred = 0;
Expand All @@ -83,6 +77,11 @@ + (NSCache *)translationCache
return translationCache;
}

+ (void)flushCredentials
{
[FGTranslateRequest flushCredentials];
}

+ (void)flushCache
{
[[FGTranslator translationCache] removeAllObjects];
Expand Down Expand Up @@ -115,6 +114,14 @@ - (void)translateText:(NSString *)text
if (!completion || !text || text.length == 0)
return;

if (self.googleAPIKey.length == 0 && (self.azureClientId.length == 0 || self.azureClientSecret.length == 0))
{
NSError *error = [self errorWithCode:FGTranslatorErrorMissingCredentials
description:@"missing Google or Bing credentials"];
completion(error, nil, nil);
return;
}

if (self.translatorState == FGTranslatorStateInProgress)
{
NSError *error = [self errorWithCode:FGTranslatorErrorTranslationInProgress description:@"translation already in progress"];
Expand Down Expand Up @@ -154,47 +161,80 @@ - (void)translateText:(NSString *)text
if (self.preferSourceGuess && [self shouldGuessSourceWithText:text])
source = nil;

// _retained_self = self;

self.completionHandler = completion;

self.operation = [FGTranslateRequest googleTranslateMessage:text
withSource:source
target:target
key:self.googleAPIKey
completion:^(NSString *translatedMessage, NSString *detectedSource, NSError *error)
if (self.googleAPIKey)
{
// TODO: handle properly
if (error)
self.operation = [FGTranslateRequest googleTranslateMessage:text
withSource:source
target:target
key:self.googleAPIKey
completion:^(NSString *translatedMessage, NSString *detectedSource, NSError *error)
{
FGTranslatorError errorState = error.code == FGTranslationErrorBadRequest ? FGTranslatorErrorUnableToTranslate : FGTranslatorErrorNetworkError;
if (error)
[self handleError:error];
else
[self handleSuccessWithOriginal:text translatedMessage:translatedMessage detectedSource:detectedSource];

NSError *fgError = [self errorWithCode:errorState description:nil];
if (completion)
completion(fgError, nil, nil);
}
else
self.translatorState = FGTranslatorStateCompleted;
}];
}
else if (self.azureClientId && self.azureClientSecret)
{
self.operation = [FGTranslateRequest bingTranslateMessage:text
withSource:source
target:target
clientId:self.azureClientId
clientSecret:self.azureClientSecret
completion:^(NSString *translatedMessage, NSString *detectedSource, NSError *error)
{
if ([self isTranslated:translatedMessage sameAsOriginal:text])
{
NSError *fgError = [self errorWithCode:FGTranslatorErrorUnableToTranslate description:@"unable to translate"];
if (completion)
completion(fgError, nil, nil);
}
if (error)
[self handleError:error];
else
{
completion(nil, translatedMessage, detectedSource);
}
}
}];
[self handleSuccessWithOriginal:text translatedMessage:translatedMessage detectedSource:detectedSource];

self.translatorState = FGTranslatorStateCompleted;
}];
}
else
{
NSError *error = [self errorWithCode:FGTranslatorErrorMissingCredentials
description:@"missing Google or Bing credentials"];
completion(error, nil, nil);

self.translatorState = FGTranslatorStateCompleted;
}
}

- (void)handleError:(NSError *)error
{
FGTranslatorError errorState = error.code == FGTranslationErrorBadRequest ? FGTranslatorErrorUnableToTranslate : FGTranslatorErrorNetworkError;

NSError *fgError = [self errorWithCode:errorState description:nil];
if (self.completionHandler)
self.completionHandler(fgError, nil, nil);
}

- (void)handleSuccessWithOriginal:(NSString *)original
translatedMessage:(NSString *)translatedMessage
detectedSource:(NSString *)detectedSource
{
if ([self isTranslated:translatedMessage sameAsOriginal:original])
{
NSError *fgError = [self errorWithCode:FGTranslatorErrorUnableToTranslate description:@"unable to translate"];
if (self.completionHandler)
self.completionHandler(fgError, nil, nil);
}
else
{
self.completionHandler(nil, translatedMessage, detectedSource);
}
}

- (void)cancelTranslation
{
self.completionHandler = nil;
[self.operation cancel];

// _retained_self = nil;
}


Expand Down Expand Up @@ -226,7 +266,7 @@ - (BOOL)isTranslated:(NSString *)translated sameAsOriginal:(NSString *)original
return [t caseInsensitiveCompare:o] == NSOrderedSame;
}

// massage to make Google Translate happy
// massage languge code to make Google Translate happy
- (NSString *)filteredLanguageCodeFromCode:(NSString *)code
{
if (!code || code.length <= 3)
Expand Down
1 change: 1 addition & 0 deletions FGTranslator/NSString+FGTranslator.m
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ - (NSUInteger)wordCharacterCount
+ (NSString *)urlEncodedStringFromString:(NSString *)original
{
NSMutableString *escaped = [NSMutableString stringWithString:[original stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

[escaped replaceOccurrencesOfString:@"$" withString:@"%24" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [escaped length])];
[escaped replaceOccurrencesOfString:@"&" withString:@"%26" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [escaped length])];
[escaped replaceOccurrencesOfString:@"+" withString:@"%2B" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [escaped length])];
Expand Down
Loading

0 comments on commit 5ac648a

Please sign in to comment.