Skip to content

Commit

Permalink
Use diffirent goole api for sentences translation
Browse files Browse the repository at this point in the history
  • Loading branch information
Nitrino committed Aug 12, 2023
1 parent 9c2ade8 commit 55ff909
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 42 deletions.
18 changes: 11 additions & 7 deletions src/models/translations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,17 @@ export const requestSubTranslation = createEvent<string>();
export const cleanSubTranslation = createEvent();
export const fetchSubTranslationFx = createEffect<{ source: string; language: string }, string>(
async ({ source, language }) => {
return await chrome.runtime.sendMessage({
type: "translateFullText",
language: language,
text: source,
});
try {
const resp = await chrome.runtime.sendMessage({
type: "translateFullText",
language: language,
text: source,
});

return JSON.parse(resp)["sentences"][0]["trans"];
} catch (error) {
console.error(error);
}
}
);

Expand All @@ -34,8 +40,6 @@ export const fetchWordTranslationFx = createEffect<
text: source,
});

console.log("++result", result);

const transcription: string = result[0][0];
const mainTranslation: string = result[1][0][0][5][0][0];
const alternativesRaw = (result[3] && result[3][5] && result[3][5][0]) || [];
Expand Down
18 changes: 6 additions & 12 deletions src/pages/background/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import reloadOnUpdate from "virtual:reload-on-update-in-background-script";
import { TWordTranslate, googleTranslateFetcher } from "@src/utils/googleTranslateFetcher";
import { TWordTranslate, googleTranslateBatchFetcher } from "@src/utils/googleTranslateBatchFetcher";
import { googleTranslateSingleFetcher } from "@src/utils/googleTranslateSingleFetcher";

reloadOnUpdate("pages/background");

async function getCurrentTab() {
let queryOptions = { active: true, lastFocusedWindow: true };
// `tab` will either be a `tabs.Tab` instance or `undefined`.
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}

/**
* Extension reloading is necessary because the browser automatically caches the css.
* If you do not use the css of the content script, please delete it.
Expand All @@ -22,22 +16,22 @@ chrome.runtime.onMessage.addListener(function (message, _sender, sendResponse) {
console.log("read: ", message);

if (message.type === "translateWord") {
googleTranslateFetcher
googleTranslateBatchFetcher
.getWordTranslation({ text: message.text, lang: message.language })
.then((respData: TWordTranslate) => sendResponse(respData));
}
if (message.type === "translateWordFull") {
googleTranslateFetcher
googleTranslateBatchFetcher
.getWordFullTranslation({ text: message.text, lang: message.language })
.then((respData: unknown) => sendResponse(respData));
}
if (message.type === "translateFullText") {
googleTranslateFetcher
googleTranslateSingleFetcher
.getFullTextTranslation({ text: message.text, lang: message.language })
.then((respData: unknown) => sendResponse(respData));
}
if (message.type === "getTextLanguage") {
googleTranslateFetcher
googleTranslateBatchFetcher
.getTextLanguage({ text: message.text, lang: message.language })
.then((respData: unknown) => sendResponse(respData));
}
Expand Down
25 changes: 25 additions & 0 deletions src/pages/content/components/Subs/SubFullTranslation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { FC, useEffect } from "react";
import { useUnit } from "effector-react";

import { $currentSubTranslation, cleanSubTranslation, requestSubTranslation } from "@src/models/translations";

export const SubFullTranslation: FC<{ text: string }> = ({ text }) => {
const [currentSubTranslation, handleRequestSubTranslation, handleCleanSubTranslation] = useUnit([
$currentSubTranslation,
requestSubTranslation,
cleanSubTranslation,
]);

useEffect(() => {
handleRequestSubTranslation(text);
return () => {
handleCleanSubTranslation();
};
}, []);

if (!currentSubTranslation) {
return null;
}

return <div className="es-full-translation">{currentSubTranslation}</div>;
};
22 changes: 1 addition & 21 deletions src/pages/content/components/Subs/Subs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { findPhrasalVerbs } from "@src/utils/findPhrasalVerbs";
import { joinTranslations } from "@src/utils/joinTranslations";
import { SubItemTranslation } from "./SubItemTranslation";
import { PhrasalVerbTranslation } from "./PhrasalVerbTranslation";
import { SubFullTranslation } from "./SubFullTranslation";

type TSubsProps = {};

Expand Down Expand Up @@ -159,24 +160,3 @@ const SubItem: FC<TSubItemProps> = ({ subItem, phrasalVerbs, index }) => {
</>
);
};

const SubFullTranslation: FC<{ text: string }> = ({ text }) => {
const [currentSubTranslation, handleRequestSubTranslation, handleCleanSubTranslation] = useUnit([
$currentSubTranslation,
requestSubTranslation,
cleanSubTranslation,
]);

useEffect(() => {
handleRequestSubTranslation(text);
return () => {
handleCleanSubTranslation();
};
}, []);

if (!currentSubTranslation) {
return null;
}

return <div className="es-full-translation">{currentSubTranslation}</div>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type TRequest = {
lang: string;
};

class GoogleTranslateFetcher {
class GoogleTranslateBatchFetcher {
#baseUrl: string;

constructor() {
Expand Down Expand Up @@ -122,4 +122,4 @@ class GoogleTranslateFetcher {
}
}

export const googleTranslateFetcher = new GoogleTranslateFetcher();
export const googleTranslateBatchFetcher = new GoogleTranslateBatchFetcher();
42 changes: 42 additions & 0 deletions src/utils/googleTranslateSingleFetcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export type TWordTranslate = {
original: string;
lang: string;
main: string;
alternatives: [];
};

type TRequest = {
text: string;
lang: string;
};

class GoogleTranslateSingleFetcher {
#baseUrl: string;

constructor() {
this.#baseUrl = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=rm&dj=1";
}

async getFullTextTranslation({ text, lang }: TRequest): Promise<string> {
return await this.get({ text, lang });
}

async get({ text, lang }: TRequest): Promise<string> {
const body = new URLSearchParams({
sl: "auto",
tl: lang,
q: text,
}).toString();

const headers = { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" };

const resp = await fetch(this.#baseUrl, {
method: "POST",
body: body,
headers: headers,
});
return await resp.text();
}
}

export const googleTranslateSingleFetcher = new GoogleTranslateSingleFetcher();

0 comments on commit 55ff909

Please sign in to comment.