Skip to content

Commit

Permalink
fix: Youdao translator has only one result
Browse files Browse the repository at this point in the history
  • Loading branch information
silencewwt committed Jun 9, 2024
1 parent 8ad0b9b commit cdb3e9a
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 10 deletions.
12 changes: 10 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "youdao.translator",
"version": "3.0.0",
"version": "3.1.1",
"description": "Elegant translation tool",
"main": "index.js",
"scripts": {
Expand All @@ -12,9 +12,17 @@
"devDependencies": {
"rimraf": "^3.0.2",
"rollup": "^2.59.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-copy": "^3.4.0",
"rollup-plugin-json": "^4.0.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-ts": "^1.4.7",
"rollup-plugin-uglify": "^6.0.4",
"typescript": "^4.4.4"
"typescript": "^4.5.5"
},
"dependencies": {
"@types/boolbase": "^1.0.3",
"@types/cheerio": "^0.22.35",
"cheerio": "^1.0.0-rc.12"
}
}
6 changes: 6 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import ts from 'rollup-plugin-ts'
import copy from 'rollup-plugin-copy'
import { uglify } from 'rollup-plugin-uglify'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json'

export default {
input: 'src/index.ts',
Expand All @@ -16,6 +19,9 @@ export default {
{ src: 'runtime/*', dest: 'dist/runtime' },
{ src: 'assets/*', dest: 'dist/assets' }
]}),
nodeResolve(),
commonjs(),
json(),
uglify()
]
}
2 changes: 1 addition & 1 deletion src/adapters/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ export interface Adapter {

url :(word: string) => string;

parse: (response: any) => Result[]
parse: (response: any) => Promise<Result[]>
}

2 changes: 1 addition & 1 deletion src/adapters/baidu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class Baidu implements Adapter {
return "https://fanyi-api.baidu.com/api/trans/vip/translate?" + params.toString();
}

parse(data: any): Result[] {
async parse(data: any): Promise<Result[]> {
if (data.error_code) {
return this.parseError(data.error_code);
}
Expand Down
54 changes: 49 additions & 5 deletions src/adapters/youdao.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Adapter, Result } from "./adapter";
import md5 from "../libs/md5";
import cheerio from "cheerio";

class Youdao implements Adapter {
key: string;
Expand Down Expand Up @@ -40,16 +41,14 @@ class Youdao implements Adapter {
return "https://openapi.youdao.com/api?" + params.toString();
}

parse(data: any): Result[] {
async parse(data: any): Promise<Result[]> {
if (data.errorCode !== "0") {
return this.parseError(data.errorCode);
}

const { translation, basic, web } = data;

const { translation, webdict, web } = data;
this.parseTranslation(translation);
this.parseBasic(basic);
this.parseWeb(web);
await this.parseWebdict(webdict);

return this.results;
}
Expand Down Expand Up @@ -77,6 +76,51 @@ class Youdao implements Adapter {
}
}

// Thanks for @VWagen1989's solution
// https://github.com/whyliam/whyliam.workflows.youdao/issues/125#issuecomment-2119263993
private async parseWebdict(t: any) {
var url = t && t["url"]
await fetch(url)
.then(response => {
if (response.ok) {
return response.text();
}
throw new Error('Network response was not ok.');
})
.then(html => {
const $ = cheerio.load(html);
$('div.content-wrp.dict-container.opened').each((i, el) => {
this.parseResultItems($(el), $);
})
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
}

private parseResultItems(item, $) {
let e = this.word
// Tricky: It will just get the first trans-container.
// Because the others will not be available until you click the button to expand.
const tc = item.find('div[class^="trans-container"]');

let phonetics: string[] = [];
tc.find('span.phonetic').each((i, el) => {
const label = $(el).parent('span').contents().first().text().trim();
const phoneticText = $(el).text().trim();
phonetics.push(`${label} ${phoneticText}`);
});
const phoneticsCombined = phonetics.join('; ');
if (phoneticsCombined != '') {
this.addResult(phoneticsCombined, "回车可听发音", e, e);
}

// Extract translation results
item.find('ul li, ul a.clickable').each((i, el) => {
this.addResult($(el).text().trim(), this.word, e, e);
});
}

private parseWeb(web: any) {
if (web) {
web.forEach((item, index) => {
Expand Down
2 changes: 1 addition & 1 deletion src/translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Translator implements ITranslator{
// fetch
const response = await redaxios.create().get(url);
// parse
const result = this.adapter.parse(response.data);
const result = await this.adapter.parse(response.data);
// compose
return new Workflow().compose(result).output();
}
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"strict": true,
"esModuleInterop": false,
"outDir": "out-tsc",
"allowSyntheticDefaultImports": true,
"rootDir": "./"
},
"include": [
Expand Down

0 comments on commit cdb3e9a

Please sign in to comment.