Skip to content
Snippets Groups Projects
Unverified Commit c5f89935 authored by Kevin Aleman's avatar Kevin Aleman Committed by GitHub
Browse files

refactor: Move from `meteor/http` to `meteor/fetch` - 2x (#28799)

parent 9ce5d46c
No related branches found
No related tags found
No related merge requests found
import { KJUR } from 'jsrsasign';
import { HTTP } from 'meteor/http';
import NodeRSA from 'node-rsa';
function isValidAppleJWT(identityToken: string, header: any): boolean {
const applePublicKeys = HTTP.get('https://appleid.apple.com/auth/keys').data.keys as any;
import { fetch } from '../../../server/lib/http/fetch';
async function isValidAppleJWT(identityToken: string, header: any): Promise<boolean> {
const request = await fetch('https://appleid.apple.com/auth/keys', { method: 'GET' });
const applePublicKeys = (await request.json()).data.keys;
const { kid } = header;
const key = applePublicKeys.find((k: any) => k.kid === kid);
......@@ -19,10 +21,10 @@ function isValidAppleJWT(identityToken: string, header: any): boolean {
}
}
export function handleIdentityToken(identityToken: string): { id: string; email: string; name: string } {
export async function handleIdentityToken(identityToken: string): Promise<{ id: string; email: string; name: string }> {
const decodedToken = KJUR.jws.JWS.parse(identityToken);
if (!isValidAppleJWT(identityToken, decodedToken.headerObj)) {
if (!(await isValidAppleJWT(identityToken, decodedToken.headerObj))) {
throw new Error('identityToken is not a valid JWT');
}
......
......@@ -5,7 +5,7 @@ import { CustomOAuth } from '../../custom-oauth/server/custom_oauth_server';
import { handleIdentityToken } from '../lib/handleIdentityToken';
export class AppleCustomOAuth extends CustomOAuth {
getIdentity(_accessToken: string, query: Record<string, any>): any {
async getIdentity(_accessToken: string, query: Record<string, any>): Promise<any> {
const { id_token: identityToken, user: userStr = '' } = query;
let usrObj = {} as any;
......@@ -16,7 +16,7 @@ export class AppleCustomOAuth extends CustomOAuth {
}
try {
const serviceData = handleIdentityToken(identityToken);
const serviceData = await handleIdentityToken(identityToken);
if (usrObj?.name) {
serviceData.name = `${usrObj.name.firstName}${usrObj.name.middleName ? ` ${usrObj.name.middleName}` : ''}${
......
......@@ -4,7 +4,7 @@ import { Accounts } from 'meteor/accounts-base';
import { handleIdentityToken } from '../lib/handleIdentityToken';
import { settings } from '../../settings/server';
Accounts.registerLoginHandler('apple', (loginRequest) => {
Accounts.registerLoginHandler('apple', async (loginRequest) => {
if (!loginRequest.identityToken) {
return;
}
......@@ -16,7 +16,7 @@ Accounts.registerLoginHandler('apple', (loginRequest) => {
const { identityToken, fullName, email } = loginRequest;
try {
const serviceData = handleIdentityToken(identityToken);
const serviceData = await handleIdentityToken(identityToken);
if (!serviceData.email && email) {
serviceData.email = email;
......
......@@ -64,7 +64,7 @@ export class TranslationProviderRegistry {
return TranslationProviderRegistry[Providers][provider];
}
static getSupportedLanguages(target: string): ISupportedLanguage[] | undefined {
static async getSupportedLanguages(target: string): Promise<ISupportedLanguage[] | undefined> {
return TranslationProviderRegistry.enabled ? TranslationProviderRegistry.getActiveProvider()?.getSupportedLanguages(target) : undefined;
}
......@@ -302,7 +302,7 @@ export abstract class AutoTranslate {
targetMessage.html = escapeHTML(String(targetMessage.msg));
targetMessage = this.tokenize(targetMessage);
const translations = this._translateMessage(targetMessage, targetLanguages);
const translations = await this._translateMessage(targetMessage, targetLanguages);
if (!_.isEmpty(translations)) {
await Messages.addTranslations(message._id, translations, TranslationProviderRegistry[Provider] || '');
}
......@@ -316,7 +316,7 @@ export abstract class AutoTranslate {
// Removes the initial link `[ ](quoterl)` from quote message before translation
const translatedText = attachment?.text?.replace(/\[(.*?)\]\(.*?\)/g, '$1') || attachment?.text;
const attachmentMessage = { ...attachment, text: translatedText };
const translations = this._translateAttachmentDescriptions(attachmentMessage, targetLanguages);
const translations = await this._translateAttachmentDescriptions(attachmentMessage, targetLanguages);
if (!_.isEmpty(translations)) {
await Messages.addAttachmentTranslations(message._id, String(index), translations);
......@@ -345,7 +345,7 @@ export abstract class AutoTranslate {
* @param {string} target - the language into which shall be translated
* @returns [{ language, name }]
*/
abstract getSupportedLanguages(target: string): ISupportedLanguage[];
abstract getSupportedLanguages(target: string): Promise<ISupportedLanguage[]>;
/**
* Performs the actual translation of a message,
......@@ -356,7 +356,7 @@ export abstract class AutoTranslate {
* @param {object} targetLanguages
* @return {object}
*/
abstract _translateMessage(message: IMessage, targetLanguages: string[]): ITranslationResult;
abstract _translateMessage(message: IMessage, targetLanguages: string[]): Promise<ITranslationResult>;
/**
* Performs the actual translation of an attachment (precisely its description),
......@@ -366,7 +366,7 @@ export abstract class AutoTranslate {
* @param {object} targetLanguages
* @returns {object} translated messages for each target language
*/
abstract _translateAttachmentDescriptions(attachment: MessageAttachment, targetLanguages: string[]): ITranslationResult;
abstract _translateAttachmentDescriptions(attachment: MessageAttachment, targetLanguages: string[]): Promise<ITranslationResult>;
}
Meteor.startup(() => {
......
......@@ -78,7 +78,7 @@ class DeeplAutoTranslate extends AutoTranslate {
* @param {string} target
* @returns {object} code : value pair
*/
getSupportedLanguages(target: string): ISupportedLanguage[] {
async getSupportedLanguages(target: string): Promise<ISupportedLanguage[]> {
if (!this.apiKey) {
return [];
}
......@@ -196,12 +196,12 @@ class DeeplAutoTranslate extends AutoTranslate {
* @param {object} targetLanguages
* @returns {object} translations: Translated messages for each language
*/
_translateMessage(message: IMessage, targetLanguages: string[]): ITranslationResult {
async _translateMessage(message: IMessage, targetLanguages: string[]): Promise<ITranslationResult> {
const translations: { [k: string]: string } = {};
let msgs = message.msg.split('\n');
msgs = msgs.map((msg) => encodeURIComponent(msg));
const query = `text=${msgs.join('&text=')}`;
const supportedLanguages = this.getSupportedLanguages('en');
const supportedLanguages = await this.getSupportedLanguages('en');
targetLanguages.forEach((language) => {
if (language.indexOf('-') !== -1 && !_.findWhere(supportedLanguages, { language })) {
language = language.substr(0, 2);
......@@ -245,10 +245,10 @@ class DeeplAutoTranslate extends AutoTranslate {
* @param {object} targetLanguages
* @returns {object} translated messages for each target language
*/
_translateAttachmentDescriptions(attachment: MessageAttachment, targetLanguages: string[]): ITranslationResult {
async _translateAttachmentDescriptions(attachment: MessageAttachment, targetLanguages: string[]): Promise<ITranslationResult> {
const translations: { [k: string]: string } = {};
const query = `text=${encodeURIComponent(attachment.description || attachment.text || '')}`;
const supportedLanguages = this.getSupportedLanguages('en');
const supportedLanguages = await this.getSupportedLanguages('en');
targetLanguages.forEach((language) => {
if (language.indexOf('-') !== -1 && !_.findWhere(supportedLanguages, { language })) {
language = language.substr(0, 2);
......
......@@ -17,6 +17,7 @@ import type {
import { AutoTranslate, TranslationProviderRegistry } from './autotranslate';
import { SystemLogger } from '../../../server/lib/logger/system';
import { settings } from '../../settings/server';
import { fetch } from '../../../server/lib/http/fetch';
/**
* Represents google translate class
......@@ -75,7 +76,7 @@ class GoogleAutoTranslate extends AutoTranslate {
* @param {string} target : user language setting or 'en'
* @returns {object} code : value pair
*/
getSupportedLanguages(target: string): ISupportedLanguage[] {
async getSupportedLanguages(target: string): Promise<ISupportedLanguage[]> {
if (!this.apiKey) {
return [];
}
......@@ -91,9 +92,8 @@ class GoogleAutoTranslate extends AutoTranslate {
};
try {
result = HTTP.get('https://translation.googleapis.com/language/translate/v2/languages', {
params,
});
const request = await fetch(`https://translation.googleapis.com/language/translate/v2/languages?${new URLSearchParams(params)}`);
result = await request.json();
} catch (e: any) {
// Fallback: Get the English names of the target languages
if (
......@@ -106,9 +106,8 @@ class GoogleAutoTranslate extends AutoTranslate {
params.target = 'en';
target = 'en';
if (!this.supportedLanguages[target]) {
result = HTTP.get('https://translation.googleapis.com/language/translate/v2/languages', {
params,
});
const request = await fetch(`https://translation.googleapis.com/language/translate/v2/languages?${new URLSearchParams(params)}`);
result = await request.json();
}
}
}
......@@ -128,13 +127,13 @@ class GoogleAutoTranslate extends AutoTranslate {
* @param {object} targetLanguages
* @returns {object} translations: Translated messages for each language
*/
_translateMessage(message: IMessage, targetLanguages: string[]): ITranslationResult {
async _translateMessage(message: IMessage, targetLanguages: string[]): Promise<ITranslationResult> {
const translations: { [k: string]: string } = {};
let msgs = message.msg.split('\n');
msgs = msgs.map((msg) => encodeURIComponent(msg));
const query = `q=${msgs.join('&q=')}`;
const supportedLanguages = this.getSupportedLanguages('en');
const supportedLanguages = await this.getSupportedLanguages('en');
targetLanguages.forEach((language) => {
if (language.indexOf('-') !== -1 && !_.findWhere(supportedLanguages, { language })) {
......@@ -176,10 +175,10 @@ class GoogleAutoTranslate extends AutoTranslate {
* @param {object} targetLanguages
* @returns {object} translated attachment descriptions for each target language
*/
_translateAttachmentDescriptions(attachment: MessageAttachment, targetLanguages: string[]): ITranslationResult {
async _translateAttachmentDescriptions(attachment: MessageAttachment, targetLanguages: string[]): Promise<ITranslationResult> {
const translations: { [k: string]: string } = {};
const query = `q=${encodeURIComponent(attachment.description || attachment.text || '')}`;
const supportedLanguages = this.getSupportedLanguages('en');
const supportedLanguages = await this.getSupportedLanguages('en');
targetLanguages.forEach((language) => {
if (language.indexOf('-') !== -1 && !_.findWhere(supportedLanguages, { language })) {
......
......@@ -80,7 +80,7 @@ class MsAutoTranslate extends AutoTranslate {
* @param {string} target
* @returns {object} code : value pair
*/
getSupportedLanguages(target: string): ISupportedLanguage[] {
async getSupportedLanguages(target: string): Promise<ISupportedLanguage[]> {
if (!this.apiKey) {
return [];
}
......@@ -103,14 +103,14 @@ class MsAutoTranslate extends AutoTranslate {
* @throws Communication Errors
* @returns {object} translations: Translated messages for each language
*/
_translate(
async _translate(
data: {
Text: string;
}[],
targetLanguages: string[],
): ITranslationResult {
): Promise<ITranslationResult> {
let translations: { [k: string]: string } = {};
const supportedLanguages = this.getSupportedLanguages('en');
const supportedLanguages = await this.getSupportedLanguages('en');
targetLanguages = targetLanguages.map((language) => {
if (language.indexOf('-') !== -1 && !_.findWhere(supportedLanguages, { language })) {
language = language.substr(0, 2);
......@@ -151,7 +151,7 @@ class MsAutoTranslate extends AutoTranslate {
* @param {object} targetLanguages
* @returns {object} translations: Translated messages for each language
*/
_translateMessage(message: IMessage, targetLanguages: string[]): ITranslationResult {
async _translateMessage(message: IMessage, targetLanguages: string[]): Promise<ITranslationResult> {
// There are multi-sentence-messages where multiple sentences come from different languages
// This is a problem for translation services since the language detection fails.
// Thus, we'll split the message in sentences, get them translated, and join them again after translation
......@@ -171,7 +171,7 @@ class MsAutoTranslate extends AutoTranslate {
* @param {object} targetLanguages
* @returns {object} translated messages for each target language
*/
_translateAttachmentDescriptions(attachment: MessageAttachment, targetLanguages: string[]): ITranslationResult {
async _translateAttachmentDescriptions(attachment: MessageAttachment, targetLanguages: string[]): Promise<ITranslationResult> {
try {
return this._translate(
[
......
......@@ -189,9 +189,9 @@ export class CustomOAuth {
registerService() {
const self = this;
OAuth.registerService(this.name, 2, null, (query) => {
const response = self.getAccessToken(query);
const identity = self.getIdentity(response.access_token, query);
OAuth.registerService(this.name, 2, null, async (query) => {
const response = await self.getAccessToken(query);
const identity = await self.getIdentity(response.access_token, query);
const serviceData = {
_OAuthCustom: true,
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment