import { AppPluginBase } from '../../basic/AppPluginBase' ; import googleTranslate from 'google-translate' ; export interface TranslateResult { translatedText : string ; originalText : string ; detectedSourceLanguage : string ; } export interface DetectResult { language : string ; isReliable : boolean ; confidence : number ; originalText : string ; } export class AppTranslateManager extends AppPluginBase < null > { public async onReady ( ) { } public async onStart ( ) { } public async onClose ( ) { } private newTranslator ( key ) { return googleTranslate ( key ) ; } public async translate < T extends string | string [ ] > ( googleTranslationKey , src , to ) { return new Promise < any > ( resolve => { this . newTranslator ( googleTranslationKey ) . translate ( src , to , ( err , result ) : void => { if ( err ) { this . logger . error ( 'Error happened when translate. ' + `err=${ JSON . stringify ( err ) }, src=${ src }` ) ; resolve ( ) ; } else { if ( ! Array . isArray ( src ) ) { resolve ( { translatedText : result . translatedText , originalText : result . originalText , detectedSourceLanguage : result . detectedSourceLanguage , } ) ; } else if ( src . length > 1 ) { resolve ( result . map ( ( res ) => { return { translatedText : res . translatedText , originalText : res . originalText , detectedSourceLanguage : res . detectedSourceLanguage , } ; } ) ) ; } else { resolve ( [ { translatedText : result . translatedText , originalText : result . originalText , detectedSourceLanguage : result . detectedSourceLanguage , } ] ) ; } } } ) ; } ) ; } public async detectLanguage ( googleTranslationKey , src ) { return new Promise < DetectResult > ( resolve => { this . newTranslator ( googleTranslationKey ) . detectLanguage ( src , ( err , result ) => { if ( err ) { this . logger . error ( `Error happened when detect language. err=${ err }, src=${ src }` ) ; resolve ( ) ; } else { resolve ( { language : result . language , isReliable : result . isReliable , confidence : result . confidence , originalText : result . originalText , } ) ; } } ) ; } ) ; } }