'use strict'; const qs = require('qs') const axios = require('axios') const Diff = require('diff') const { createCoreService } = require('@strapi/strapi').factories; const { ApplicationError } = require("@strapi/utils").errors 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, { text: Array.isArray(text) ? text : [text], source_lang: origin, target_lang: target, }, { headers: { Authorization: `DeepL-Auth-Key ${this.deeplKey}`, 'Content-Type': 'application/json' } }) return result.data } catch (error) { console.error('DeepL error:', error?.response?.data || 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) 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 ApplicationError('Champ obligatoire. Veuillez choisir un titre.'); } if (!transcription || transcription.trim().length === 0) { throw new ApplicationError('Champ obligatoire. Veuillez renseigner la transcription.') } if (transcription.trim().length < 10) { throw new ApplicationError('La transcription doit contenir au moins 10 caractères.') } }, 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) { const jsonDiff = Diff.diffWords(oldString, newString) return { patch, jsonDiff } } } }));