Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
actions-user committed Dec 1, 2024
2 parents dba0533 + 05e47de commit 25a9ba6
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 26 deletions.
2 changes: 1 addition & 1 deletion api/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = (req, res) => {
res.json({
code: 200,
message: "Welcome to the DeepL Free API. Please POST to /api/translate. Visit http://github.com/OwO-Network/DeepLX for more information."
message: "Welcome to the DeepL Free API. Please POST to /api/translate. Visit http://github.com/OwO-Network/DeepLX for more information. \n If ip not working, write issue on github"
});
};
6 changes: 3 additions & 3 deletions api/translate.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Max-Age', '86400'); // Кэширование preflight-запросов на 1 день
res.setHeader('Access-Control-Max-Age', '86400');
return res.status(204).end();
}

Expand All @@ -20,10 +20,10 @@ module.exports = async (req, res) => {
});
}

const { text, source_lang = 'auto', target_lang = 'RU', tag_handling = '' } = req.body;
const { text, source_lang = 'auto', target_lang = 'RU', tag_handling = '', dl_session = '', proxy = '' } = req.body;

try {
const result = await translate(text, source_lang, target_lang, tag_handling);
const result = await translate(text, source_lang, target_lang, tag_handling, dl_session, proxy);
const duration = Date.now() - startTime;
console.log(`[LOG] ${new Date().toISOString()} | 200 | ${duration}ms | POST "/translate"`);

Expand Down
71 changes: 49 additions & 22 deletions translate.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const axios = require('axios').default;
const { random } = require('lodash');
const zlib = require('zlib');

const DEEPL_BASE_URL = 'https://www2.deepl.com/jsonrpc';
Expand All @@ -9,7 +8,7 @@ function getICount(translateText) {
}

function getRandomNumber() {
return random(8300000, 8399998) * 1000;
return Math.floor(Math.random() * (8399998 - 8300000 + 1)) + 8300000;
}

function getTimestamp(iCount) {
Expand Down Expand Up @@ -39,37 +38,63 @@ function formatPostString(postData) {
}

async function makeRequest(postData, method, dlSession = '', proxy = '') {
const url = `${DEEPL_BASE_URL}?client=chrome-extension,1.6.0&method=${method}`;
const url = `${DEEPL_BASE_URL}?client=chrome-extension%2C1.28.0&method=${method}`;
const postDataStr = formatPostString(postData);

const headers = {
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br', // Добавлено
'Authorization': 'None',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json',
'Origin': 'chrome-extension://bppidhpdkcbahckohjehbehjmcnhpkck',
'DNT': '1',
'Origin': 'chrome-extension://cofdbpoegempjloogbagkncekinflcnj',
'Pragma': 'no-cache',
'Priority': 'u=1, i',
'Referer': 'https://www.deepl.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'none',
'Sec-GPC': '1',
'User-Agent': 'DeepLBrowserExtension/1.28.0 Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
};

if (dlSession) {
headers['Cookie'] = `dl_session=${dlSession}`;
}

const axiosOptions = {
method: 'POST',
url: url,
headers: headers,
data: postDataStr,
responseType: 'arraybuffer',
decompress: false,
validateStatus: function (status) {
return status >= 200 && status < 500;
},
};

if (proxy) {
const [host, port] = proxy.split(':');
axiosOptions.proxy = {
host: host,
port: parseInt(port, 10),
};
} else {
axiosOptions.proxy = false;
}

try {
const response = await axios.post(url, postDataStr, {
headers: headers,
responseType: 'arraybuffer',
decompress: false,
...(proxy && { proxy: proxy }),
validateStatus: function (status) {
return status >= 200 && status < 500;
},
});
const response = await axios(axiosOptions);

let data;
const encoding = response.headers['content-encoding'];
if (encoding === 'br') {
data = zlib.brotliDecompressSync(response.data).toString();
} else if (encoding === 'gzip') {
data = zlib.gunzipSync(response.data).toString(); // Обработка Gzip
} else {
data = response.data.toString();
}
Expand All @@ -96,7 +121,7 @@ async function splitText(text, tagHandling) {
lang_user_selected: 'auto',
},
splitting: 'newlines',
text_type: (tagHandling === 'html' || tagHandling === 'xml' || isRichText(text)) ? 'richtext' : 'plaintext',
text_type: tagHandling || isRichText(text) ? 'richtext' : 'plaintext',
},
};

Expand All @@ -116,7 +141,7 @@ async function translate(
throw new Error('Нет текста для перевода.');
}

const splitResult = await splitText(text, tagHandling);
const splitResult = await splitText(text, tagHandling === 'html' || tagHandling === 'xml');
if (!splitResult || !splitResult.result) {
throw new Error('Не удалось разделить текст.');
}
Expand All @@ -134,9 +159,9 @@ async function translate(

jobs.push({
kind: 'default',
preferred_num_beams: 4,
raw_en_context_before: contextBefore,
raw_en_context_after: contextAfter,
preferred_num_beams: 1,
sentences: [
{
id: idx + 1,
Expand All @@ -158,21 +183,23 @@ async function translate(
const iCount = getICount(text);
const id = getRandomNumber();

const commonJobParams = {
mode: 'translate',
...(hasRegionalVariant && { regionalVariant: targetLang }),
};

const postData = {
jsonrpc: '2.0',
method: 'LMT_handle_jobs',
id: id,
params: {
jobs: jobs,
lang: {
source_lang_user_selected: detectedSourceLang.toUpperCase(),
source_lang_computed: detectedSourceLang.toUpperCase(),
target_lang: targetLangCode.toUpperCase(),
},
priority: 1,
commonJobParams: {
mode: 'translate',
...(hasRegionalVariant && { regionalVariant: targetLang }),
},
commonJobParams: commonJobParams,
timestamp: getTimestamp(iCount),
},
};
Expand Down

0 comments on commit 25a9ba6

Please sign in to comment.