1- import { Adapter , Result } from ' ./adapter'
2-
1+ import { Adapter , Result } from " ./adapter" ;
2+ import md5 from "../libs/md5" ;
33
44class Baidu implements Adapter {
5+ key : string ;
6+
7+ secret : string ;
58
6- key : string
9+ word : string = "" ;
710
8- secret : string
11+ isChinese : boolean = false ;
912
10- word : string = ''
13+ results : Result [ ] = [ ] ;
1114
12- isChinese : boolean = false
15+ phonetic : string = "" ;
1316
1417 constructor ( key : string , secret : string ) {
15- this . key = key
16- this . secret = secret
18+ this . key = key ;
19+ this . secret = secret ;
1720 }
1821
1922 url ( word : string ) : string {
20- this . isChinese = this . detectChinese ( word )
21- return 'http://openapi.youdao.com/api'
23+ this . isChinese = this . detectChinese ( word ) ;
24+ this . word = word ;
25+
26+ const from = this . isChinese ? "zh" : "auto" ;
27+ const to = this . isChinese ? "en" : "zh" ;
28+ const salt = Math . floor ( Math . random ( ) * 10000 ) . toString ( ) ;
29+ const sign = md5 ( `${ this . key } ${ word } ${ salt } ${ this . secret } ` ) ;
30+
31+ const params = new URLSearchParams ( {
32+ q : word ,
33+ from,
34+ to,
35+ appid : this . key ,
36+ salt,
37+ sign,
38+ dict : '1' ,
39+ action : '1' ,
40+ } ) ;
41+
42+ return "https://fanyi-api.baidu.com/api/trans/vip/translate?" + params . toString ( ) ;
2243 }
2344
24- parse ( response : any ) : Result [ ] {
25- return [ ]
45+ parse ( data : any ) : Result [ ] {
46+ if ( data . error_code ) {
47+ return this . parseError ( data . error_code ) ;
48+ }
49+
50+ const { trans_result :result } = data ;
51+ result . forEach ( item => {
52+ const pronounce = this . isChinese ? item . dst : this . word ;
53+ this . addResult ( item . dst , item . src , pronounce , pronounce ) ;
54+ } ) ;
55+
56+ return this . results ;
2657 }
27-
28- private detectChinese ( word : string ) : boolean {
29- return / ^ [ \u4e00 - \u9fa5 ] + $ / . test ( word )
58+
59+ private parseError ( code : number ) : Result [ ] {
60+ const messages = {
61+ 54000 : "缺少必填的参数" ,
62+ 58001 : "不支持的语言类型" ,
63+ 54005 : "翻译文本过长" ,
64+ 52003 : "应用ID无效" ,
65+ 58002 : "无相关服务的有效实例" ,
66+ 90107 : "开发者账号无效" ,
67+ 54001 : "签名检验失败,检查 KEY 和 SECRET" ,
68+ 54004 : "账户已经欠费" ,
69+ 54003 : "访问频率受限" ,
70+ } ;
71+
72+ const message = messages [ code ] || "请参考错误码:" + code ;
73+
74+ return this . addResult ( "👻 翻译出错啦" , message , "Ooops..." ) ;
3075 }
3176
77+ private addResult ( title : string , subtitle : string , arg : string = "" , pronounce : string = "" ) : Result [ ] {
78+ const quicklookurl = "https://fanyi.baidu.com/#auto/auto/" + this . word ;
79+ this . results . push ( { title, subtitle, arg, pronounce, quicklookurl } ) ;
80+ return this . results ;
81+ }
82+
83+ private detectChinese ( word : string ) : boolean {
84+ return / ^ [ \u4e00 - \u9fa5 ] + $ / . test ( word ) ;
85+ }
3286}
3387
34- export default Baidu
88+ export default Baidu ;
0 commit comments