UNPKG

@ai-growth/n8n-nodes-wordpress

Version:

n8n node for WordPress integration with AI GROWTH - SEO WP plugin

188 lines 8.32 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MediaUploadService = void 0; const form_data_1 = __importDefault(require("form-data")); const ErrorUtils_1 = require("../utils/ErrorUtils"); const ImageDownloadService_1 = require("./ImageDownloadService"); const ImageUrlService_1 = require("./ImageUrlService"); /** * Serviço para upload de imagens para a biblioteca de mídia do WordPress */ class MediaUploadService { /** * Construtor do serviço * @param client Cliente WordPress */ constructor(client) { this.client = client; this.downloadService = new ImageDownloadService_1.ImageDownloadService(); this.urlService = new ImageUrlService_1.ImageUrlService(); } /** * Faz upload de uma imagem para a biblioteca de mídia a partir de uma URL * @param imageUrl URL da imagem * @param options Opções de upload * @returns Imagem carregada */ async uploadFromUrl(imageUrl, options = {}) { try { // Baixar a imagem da URL const downloadResult = await this.downloadService.downloadImage(imageUrl, options.downloadOptions); // Fazer upload dos dados baixados return await this.uploadBuffer(downloadResult.data, { filename: options.filename || downloadResult.filename, mimeType: options.mimeType || downloadResult.mimeType, metadata: options.metadata }); } catch (error) { if (error instanceof ErrorUtils_1.WordPressError) { throw error; } throw new ErrorUtils_1.WordPressError(`Erro ao fazer upload da imagem a partir da URL: ${imageUrl}`, ErrorUtils_1.WordPressErrorType.UNKNOWN); } } /** * Faz upload de dados binários de imagem para a biblioteca de mídia * @param buffer Buffer contendo os dados da imagem * @param options Opções de upload * @returns Imagem carregada */ async uploadBuffer(buffer, options = {}) { try { // Validar dados de entrada if (!buffer || buffer.length === 0) { throw new ErrorUtils_1.WordPressError('Dados de imagem vazios ou inválidos', ErrorUtils_1.WordPressErrorType.VALIDATION_FAILED); } // Gerar nome de arquivo se não fornecido const filename = options.filename || `image-${Date.now()}.jpg`; // Determinar tipo MIME const mimeType = options.mimeType || 'image/jpeg'; // Criar FormData para upload const formData = new form_data_1.default(); formData.append('file', buffer, { filename, contentType: mimeType, }); // Cabeçalhos adicionais const headers = { ...formData.getHeaders(), 'Content-Disposition': `attachment; filename="${filename}"` }; // Fazer upload para a biblioteca de mídia do WordPress const response = await this.client.postWithOptions('media', formData, { headers }); // Verificar resposta if (!response || !response.id) { throw new ErrorUtils_1.WordPressError('Falha ao fazer upload da imagem: Resposta inválida', ErrorUtils_1.WordPressErrorType.UNKNOWN); } // Atualizar metadados se fornecidos if (options.metadata) { await this.updateImageMetadata(response.id, options.metadata); // Buscar a imagem atualizada return await this.getMedia(response.id); } // Formatar resposta return this.formatMediaResponse(response); } catch (error) { if (error instanceof ErrorUtils_1.WordPressError) { throw error; } throw new ErrorUtils_1.WordPressError(`Erro ao fazer upload da imagem: ${error instanceof Error ? error.message : 'Erro desconhecido'}`, ErrorUtils_1.WordPressErrorType.UNKNOWN); } } /** * Atualiza os metadados de uma imagem existente * @param imageId ID da imagem na biblioteca de mídia * @param metadata Metadados a serem atualizados * @returns Imagem atualizada */ async updateImageMetadata(imageId, metadata) { try { // Objeto para armazenar os dados a serem atualizados const updateData = {}; // Definir metadados if (metadata.alt_text !== undefined) { updateData.alt_text = metadata.alt_text; } if (metadata.caption !== undefined) { updateData.caption = metadata.caption; } if (metadata.description !== undefined) { updateData.description = metadata.description; } if (metadata.title !== undefined) { updateData.title = metadata.title; } // Se não há metadados para atualizar, retornar a mídia atual if (Object.keys(updateData).length === 0) { return await this.getMedia(imageId); } // Atualizar a mídia const response = await this.client.post(`media/${imageId}`, updateData); // Formatar resposta return this.formatMediaResponse(response); } catch (error) { if (error instanceof ErrorUtils_1.WordPressError) { throw error; } throw new ErrorUtils_1.WordPressError(`Erro ao atualizar metadados da imagem: ${imageId}`, ErrorUtils_1.WordPressErrorType.UNKNOWN); } } /** * Obtém uma mídia específica da biblioteca * @param mediaId ID da mídia * @returns Informações da mídia */ async getMedia(mediaId) { try { const response = await this.client.get(`media/${mediaId}`); return this.formatMediaResponse(response); } catch (error) { if (error instanceof ErrorUtils_1.WordPressError) { throw error; } throw new ErrorUtils_1.WordPressError(`Erro ao obter mídia: ${mediaId}`, ErrorUtils_1.WordPressErrorType.UNKNOWN); } } /** * Formata a resposta da API para o formato de IWordPressImage * @param response Resposta da API * @returns Imagem formatada */ formatMediaResponse(response) { var _a, _b, _c, _d, _e, _f, _g; if (!response || !response.id) { throw new ErrorUtils_1.WordPressError('Resposta inválida da API de mídia', ErrorUtils_1.WordPressErrorType.UNKNOWN); } // Extrair URLs de diferentes tamanhos da imagem const sizes = {}; if (response.media_details && response.media_details.sizes) { const mediaSizes = response.media_details.sizes; Object.keys(mediaSizes).forEach(size => { if (mediaSizes[size] && mediaSizes[size].source_url) { sizes[size] = mediaSizes[size].source_url; } }); } // Formatar resultado return { id: response.id, url: response.source_url || ((_a = response.guid) === null || _a === void 0 ? void 0 : _a.rendered) || '', title: ((_b = response.title) === null || _b === void 0 ? void 0 : _b.rendered) || ((_c = response.title) === null || _c === void 0 ? void 0 : _c.raw) || '', alt: response.alt_text || '', caption: ((_d = response.caption) === null || _d === void 0 ? void 0 : _d.rendered) || ((_e = response.caption) === null || _e === void 0 ? void 0 : _e.raw) || '', description: ((_f = response.description) === null || _f === void 0 ? void 0 : _f.rendered) || ((_g = response.description) === null || _g === void 0 ? void 0 : _g.raw) || '', mime_type: response.mime_type || '', date_created: response.date || '', sizes }; } } exports.MediaUploadService = MediaUploadService; //# sourceMappingURL=MediaUploadService.js.map