Files
api.pawol.nu/src/api/parole/services/parole.js
T

84 lines
2.5 KiB
JavaScript
Raw Normal View History

2022-05-12 03:33:24 +04:00
'use strict';
2022-05-20 00:05:34 +04:00
const qs = require('qs')
const axios = require('axios')
2022-12-09 04:42:27 +04:00
const Diff = require('diff')
2022-05-12 03:33:24 +04:00
const { createCoreService } = require('@strapi/strapi').factories;
const { ValidationError } = require("@strapi/utils").errors
2022-05-12 03:33:24 +04:00
2022-05-20 00:05:34 +04:00
class Translator {
constructor() {
this.deeplApi = process.env.DEEPL_URL || 'api-free.deepl.com'
this.deeplKey = process.env.DEEPL_KEY
this.urlRequest = `https://${this.deeplApi}/v2/translate`
}
async get(origin, target, text) {
try {
const data = {
auth_key: this.deeplKey,
source_lang: origin,
target_lang: target,
text
}
const result = await axios.post(this.urlRequest, qs.stringify(data), {
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
return result.data
} catch (error) {
console.log('error', error)
}
}
}
module.exports = createCoreService('api::parole.parole', ({strapi}) => ({
async translate(origin, target, text) {
const translator = new Translator()
const data = await translator.get(origin, target, text)
return data.translations[0].text
},
async translateLyrics(parolesFR) {
const anglais = await this.translate('FR', 'EN', parolesFR)
const espagnol = await this.translate('FR', 'ES', parolesFR)
const allemand = await this.translate('FR', 'DE', parolesFR)
const italien = await this.translate('FR', 'IT', parolesFR)
2022-12-09 04:42:27 +04:00
return {
francais: parolesFR,
anglais: anglais + '\n\n (Translated by DeepL)',
espagnol: espagnol + '\n\n (Traducido por DeepL)',
allemand: allemand + '\n\n (Übersetzt von DeepL)',
italien: italien + '\n\n (Tradotto da DeepL)'
}
},
validateParoles(titre, transcription) {
if (!titre || titre.trim().length === 0) {
throw new ValidationError('Champ obligatoire. Veuillez choisir un titre.');
}
2022-12-09 04:42:27 +04:00
if (!transcription || transcription.trim().length === 0) {
throw new ValidationError('Champ obligatoire. Veuillez renseigner la transcription.')
}
2022-12-09 04:42:27 +04:00
if (transcription.trim().length < 10) {
throw new ValidationError('La transcription doit contenir au moins 10 caractères.')
}
2022-12-09 04:42:27 +04:00
},
parolesDiff(titre = '', oldString, newString) {
const patch = Diff.createPatch(titre, oldString, newString, 'supprimée', 'ajoutée')
const parsePatch = Diff.parsePatch(patch)
if (parsePatch[0].hunks.length > 0) {
2022-12-12 22:19:59 +04:00
const jsonDiff = Diff.diffWords(oldString, newString)
return {
patch,
jsonDiff
}
2022-12-09 04:42:27 +04:00
}
2022-05-20 00:05:34 +04:00
}
}));