Skip to content

Commit

Permalink
fix: meaningful error message
Browse files Browse the repository at this point in the history
Fixes #55
  • Loading branch information
uetchy committed Jan 5, 2021
1 parent b33b2b0 commit 2cdf86d
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 8 deletions.
10 changes: 8 additions & 2 deletions PolyglotSafariExtension/SafariExtensionHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import SafariServices
struct MessageType {
static let SendSettings = "settingsReceived"
static let SendTranslation = "translated"
static let SendError = "error"
static let PerformTranslation = "performTranslation"
}

Expand Down Expand Up @@ -58,14 +59,19 @@ class SafariExtensionHandler: SFSafariExtensionHandler {
let sourceLanguage = ud.string(forKey: SettingsKey.SourceLanguage) ?? "auto"
let targetLanguage = ud.string(forKey: SettingsKey.TargetLanguage) ?? "en"

googleTranslate(text, sourceLanguage: sourceLanguage, targetLanguage: targetLanguage) { translationResult in
googleTranslate(text, sourceLanguage: sourceLanguage, targetLanguage: targetLanguage, completionHandler: { translationResult in
page.dispatchMessageToScript(withName: MessageType.SendTranslation, userInfo: [
"translation": translationResult["translation"] ?? "",
"dictionary": translationResult["dictionary"] ?? [],
"synonyms": translationResult["synonyms"] ?? [],
"id": id,
])
}
}, errorHandler: { errorMessage in
page.dispatchMessageToScript(withName: MessageType.SendError, userInfo: [
"error": errorMessage,
"id": id,
])
})
}

// This method will be called when your toolbar item is clicked.
Expand Down
26 changes: 26 additions & 0 deletions PolyglotSafariExtension/Sources/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ interface ReceivedTranslation {
id: string;
}

interface UpstreamError {
error: string;
id: string;
}

enum RequestMessageType {
RequestSettings = "getSettings",
Translate = "translate",
Expand All @@ -68,6 +73,7 @@ enum RequestMessageType {
enum ResponseMessageType {
SettingsReceived = "settingsReceived",
TranslationReceived = "translated",
ErrorOccured = "error",
PerformTranslation = "performTranslation",
}

Expand Down Expand Up @@ -102,6 +108,9 @@ function handleMessage(msg: SafariExtensionMessageEvent): void {
case ResponseMessageType.TranslationReceived:
translationHandler(msg.message);
break;
case ResponseMessageType.ErrorOccured:
translationErrorHandler(msg.message);
break;
case ResponseMessageType.PerformTranslation:
performTranslation(); // TODO: support iframe
break;
Expand All @@ -120,6 +129,23 @@ function settingsHandler(received: ReceivedSettings): void {
console.debug(settings);
}

function translationErrorHandler(message: UpstreamError) {
if (message.id !== window.location.href) return;
const args = {
error: message.error,
};
const result = Mustache.render(
`
<div class="polyglot__inner">
<div class="polyglot__translation">
{{{error}}}
</div>
</div>`,
args
);
showPanel(result);
}

function translationHandler(message: ReceivedTranslation): void {
if (message.id !== window.location.href) return;

Expand Down
18 changes: 12 additions & 6 deletions PolyglotSafariExtension/Translator.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Alamofire
import Foundation

func googleTranslate(_ text: String, sourceLanguage: String, targetLanguage: String, completionHandler: @escaping (NSDictionary) -> Void) {
func googleTranslate(_ text: String, sourceLanguage: String, targetLanguage: String, completionHandler: @escaping (NSDictionary) -> Void, errorHandler: @escaping (String) -> Void) {
let endpoint: String = "https://translate.googleapis.com/translate_a/single?dt=t&dt=ss"
let params: Alamofire.Parameters = [
"client": "gtx",
Expand All @@ -17,21 +17,27 @@ func googleTranslate(_ text: String, sourceLanguage: String, targetLanguage: Str
.validate(statusCode: 200 ..< 300)
.responseJSON { response in
if response.result.error != nil {
NSLog(response.result.error?.localizedDescription ?? "")
return
let errorMessage = response.result.error?.localizedDescription ?? ""
NSLog(errorMessage)
if let statusCode = response.response?.statusCode, statusCode == 429 {
return errorHandler("The API rate limit has been exceeded. Please try again later.")
}
return errorHandler(errorMessage)
}

guard let json = response.result.value as? NSDictionary,
let sentences = json["sentences"] as? NSArray else {
return
let sentences = json["sentences"] as? NSArray
else {
return errorHandler("Illegal JSON response")
}

let result: NSMutableDictionary = [:]

// Translation
result["translation"] = sentences.compactMap { (item) -> String? in
guard let item = item as? NSDictionary,
let text = item["trans"] as? String else {
let text = item["trans"] as? String
else {
return nil
}
return text
Expand Down

0 comments on commit 2cdf86d

Please sign in to comment.