Use crypto UUID if available

This commit is contained in:
Cohee 2024-06-10 14:18:38 +03:00
parent a20b2a566d
commit d1ed983106
2 changed files with 15 additions and 9 deletions

View File

@ -2,7 +2,7 @@ const fetch = require('node-fetch').default;
const https = require('https');
const express = require('express');
const { readSecret, SECRET_KEYS } = require('./secrets');
const { getConfigValue } = require('../util');
const { getConfigValue, uuidv4 } = require('../util');
const { jsonParser } = require('../express-common');
const DEEPLX_URL_DEFAULT = 'http://127.0.0.1:1188/translate';
@ -103,7 +103,6 @@ router.post('/google', jsonParser, async (request, response) => {
});
router.post('/yandex', jsonParser, async (request, response) => {
const chunks = request.body.chunks;
const lang = request.body.lang;
@ -113,17 +112,17 @@ router.post('/yandex', jsonParser, async (request, response) => {
// reconstruct original text to log
let inputText = '';
const params = new URLSearchParams();
for (const chunk of chunks) {
params.append('text', chunk);
inputText += chunk;
}
params.append('lang', lang);
const ucid = crypto.randomUUID().replaceAll('-', '');
const ucid = uuidv4().replaceAll('-', '');
console.log('Input text: ' + inputText);
try {
const result = await fetch(`https://translate.yandex.net/api/v1/tr.json/translate?ucid=${ucid}&srv=android&format=text`, {
method: 'POST',
@ -135,9 +134,9 @@ router.post('/yandex', jsonParser, async (request, response) => {
});
if (!result.ok) {
const error = await result.message();
console.log('Yandex error: ', result.code, error);
return response.sendStatus(result.code);
const error = await result.text();
console.log('Yandex error: ', result.statusText, error);
return response.sendStatus(500);
}
const json = await result.json();

View File

@ -293,7 +293,14 @@ const color = {
white: (mess) => color.byNum(mess, 37),
};
/**
* Gets a random UUIDv4 string.
* @returns {string} A UUIDv4 string
*/
function uuidv4() {
if ('randomUUID' in crypto) {
return crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);