@ai-growth/n8n-nodes-wordpress
Version:
n8n node for WordPress integration with AI GROWTH - SEO WP plugin
268 lines (267 loc) • 14 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.MediaUploadService = void 0;
var form_data_1 = require("form-data");
var ErrorUtils_1 = require("../utils/ErrorUtils");
var ImageDownloadService_1 = require("./ImageDownloadService");
var ImageUrlService_1 = require("./ImageUrlService");
/**
* Serviço para upload de imagens para a biblioteca de mídia do WordPress
*/
var MediaUploadService = /** @class */ (function () {
/**
* Construtor do serviço
* @param client Cliente WordPress
*/
function MediaUploadService(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
*/
MediaUploadService.prototype.uploadFromUrl = function (imageUrl, options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var downloadResult, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
return [4 /*yield*/, this.downloadService.downloadImage(imageUrl, options.downloadOptions)];
case 1:
downloadResult = _a.sent();
return [4 /*yield*/, this.uploadBuffer(downloadResult.data, {
filename: options.filename || downloadResult.filename,
mimeType: options.mimeType || downloadResult.mimeType,
metadata: options.metadata
})];
case 2:
// Fazer upload dos dados baixados
return [2 /*return*/, _a.sent()];
case 3:
error_1 = _a.sent();
if (error_1 instanceof ErrorUtils_1.WordPressError) {
throw error_1;
}
throw new ErrorUtils_1.WordPressError("Erro ao fazer upload da imagem a partir da URL: ".concat(imageUrl), ErrorUtils_1.WordPressErrorType.UNKNOWN);
case 4: return [2 /*return*/];
}
});
});
};
/**
* 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
*/
MediaUploadService.prototype.uploadBuffer = function (buffer, options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var filename, mimeType, formData, headers, response, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 5, , 6]);
// 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);
}
filename = options.filename || "image-".concat(Date.now(), ".jpg");
mimeType = options.mimeType || 'image/jpeg';
formData = new form_data_1["default"]();
formData.append('file', buffer, {
filename: filename,
contentType: mimeType
});
headers = __assign(__assign({}, formData.getHeaders()), { 'Content-Disposition': "attachment; filename=\"".concat(filename, "\"") });
return [4 /*yield*/, this.client.postWithOptions('wp/v2/media', formData, { headers: headers })];
case 1:
response = _a.sent();
// Verificar resposta
if (!response || !response.id) {
throw new ErrorUtils_1.WordPressError('Falha ao fazer upload da imagem: Resposta inválida', ErrorUtils_1.WordPressErrorType.UNKNOWN);
}
if (!options.metadata) return [3 /*break*/, 4];
return [4 /*yield*/, this.updateImageMetadata(response.id, options.metadata)];
case 2:
_a.sent();
return [4 /*yield*/, this.getMedia(response.id)];
case 3:
// Buscar a imagem atualizada
return [2 /*return*/, _a.sent()];
case 4:
// Formatar resposta
return [2 /*return*/, this.formatMediaResponse(response)];
case 5:
error_2 = _a.sent();
if (error_2 instanceof ErrorUtils_1.WordPressError) {
throw error_2;
}
throw new ErrorUtils_1.WordPressError("Erro ao fazer upload da imagem: ".concat(error_2 instanceof Error ? error_2.message : 'Erro desconhecido'), ErrorUtils_1.WordPressErrorType.UNKNOWN);
case 6: return [2 /*return*/];
}
});
});
};
/**
* 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
*/
MediaUploadService.prototype.updateImageMetadata = function (imageId, metadata) {
return __awaiter(this, void 0, void 0, function () {
var updateData, response, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 4, , 5]);
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;
}
if (!(Object.keys(updateData).length === 0)) return [3 /*break*/, 2];
return [4 /*yield*/, this.getMedia(imageId)];
case 1: return [2 /*return*/, _a.sent()];
case 2: return [4 /*yield*/, this.client.post("wp/v2/media/".concat(imageId), updateData)];
case 3:
response = _a.sent();
// Formatar resposta
return [2 /*return*/, this.formatMediaResponse(response)];
case 4:
error_3 = _a.sent();
if (error_3 instanceof ErrorUtils_1.WordPressError) {
throw error_3;
}
throw new ErrorUtils_1.WordPressError("Erro ao atualizar metadados da imagem: ".concat(imageId), ErrorUtils_1.WordPressErrorType.UNKNOWN);
case 5: return [2 /*return*/];
}
});
});
};
/**
* Obtém uma mídia específica da biblioteca
* @param mediaId ID da mídia
* @returns Informações da mídia
*/
MediaUploadService.prototype.getMedia = function (mediaId) {
return __awaiter(this, void 0, void 0, function () {
var response, error_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.client.get("wp/v2/media/".concat(mediaId))];
case 1:
response = _a.sent();
return [2 /*return*/, this.formatMediaResponse(response)];
case 2:
error_4 = _a.sent();
if (error_4 instanceof ErrorUtils_1.WordPressError) {
throw error_4;
}
throw new ErrorUtils_1.WordPressError("Erro ao obter m\u00EDdia: ".concat(mediaId), ErrorUtils_1.WordPressErrorType.UNKNOWN);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Formata a resposta da API para o formato de IWordPressImage
* @param response Resposta da API
* @returns Imagem formatada
*/
MediaUploadService.prototype.formatMediaResponse = function (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
var sizes = {};
if (response.media_details && response.media_details.sizes) {
var mediaSizes_1 = response.media_details.sizes;
Object.keys(mediaSizes_1).forEach(function (size) {
if (mediaSizes_1[size] && mediaSizes_1[size].source_url) {
sizes[size] = mediaSizes_1[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: sizes
};
};
return MediaUploadService;
}());
exports.MediaUploadService = MediaUploadService;