UNPKG

n8n-nodes-useapi

Version:

Ability to use multiple Midjourney, Riffusion, Mureka, Runway, MiniMax, InsightFaceSwap, Pika and PixVerse accounts complete with automated load balancing.

1,100 lines 65.4 kB
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UseApi = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const ImagesCreateDescription_1 = require("../minimax/ImagesCreateDescription");
const ImagesRetrieveDescription_1 = require("../minimax/ImagesRetrieveDescription");
const RunwayDescription_1 = require("../runwayml/RunwayDescription");
const Gen3TurboDescription_1 = require("../runwayml/Gen3TurboDescription");
const Gen4Description_1 = require("../runwayml/Gen4Description");
const TextToImageDescription_1 = require("../runwayml/TextToImageDescription");
const LipSyncDescription_1 = require("../runwayml/LipSyncDescription");
const VideoToVideoDescription_1 = require("../runwayml/VideoToVideoDescription");
const AccountCreateDescription_1 = require("../runwayml/AccountCreateDescription");
const MinimaxDescription_1 = require("../minimax/MinimaxDescription");
const VideosCreateDescription_1 = require("../minimax/VideosCreateDescription");
const AccountCreateDescription_2 = require("../minimax/AccountCreateDescription");
const VideosRetrieveDescription_1 = require("../minimax/VideosRetrieveDescription");
const FilesCreateDescription_1 = require("../minimax/FilesCreateDescription");
const FilesListDescription_1 = require("../minimax/FilesListDescription");
const ImagineDescription_1 = require("../midjourney/ImagineDescription");
const GetJobDescription_1 = require("../midjourney/GetJobDescription");
const ButtonDescription_1 = require("../midjourney/ButtonDescription");
const MidjourneyDescription_1 = require("../midjourney/MidjourneyDescription");
const BASE_URL_V1 = 'https://api.useapi.net/v1';
const BASE_URL_V2 = 'https://api.useapi.net/v2';
void BASE_URL_V2;
class UseApi {
    constructor() {
        this.description = {
            displayName: 'UseAPI',
            name: 'useApi',
            icon: 'file:useapi.svg',
            group: ['transform'],
            version: 1,
            subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
            description: 'Interact with RunwayML through UseAPI',
            defaults: {
                name: 'UseAPI',
            },
            inputs: ['main'],
            outputs: ['main'],
            credentials: [
                {
                    name: 'useApiApi',
                    required: true,
                    displayOptions: {
                        show: {
                            resource: ['runway'],
                        },
                    },
                },
                {
                    name: 'useApiMinimax',
                    required: true,
                    displayOptions: {
                        show: {
                            resource: ['minimax'],
                        },
                    },
                },
                {
                    name: 'useApiMidjourney',
                    required: true,
                    displayOptions: {
                        show: {
                            resource: ['midjourney'],
                        },
                    },
                },
            ],
            properties: [
                {
                    displayName: 'Resource',
                    name: 'resource',
                    type: 'options',
                    noDataExpression: true,
                    options: [
                        {
                            name: 'Runway',
                            value: 'runway',
                        },
                        {
                            name: 'Minimax',
                            value: 'minimax',
                        },
                        {
                            name: 'Midjourney',
                            value: 'midjourney',
                        },
                    ],
                    default: 'runway',
                },
                ...RunwayDescription_1.runwayOperations,
                ...RunwayDescription_1.runwayFields,
                ...Gen3TurboDescription_1.gen3TurboFields,
                ...TextToImageDescription_1.textToImageFields,
                ...LipSyncDescription_1.lipSyncFields,
                ...VideoToVideoDescription_1.videoToVideoFields,
                ...AccountCreateDescription_1.accountCreateFields,
                ...Gen4Description_1.gen4Fields,
                ...MinimaxDescription_1.minimaxOperations,
                ...MinimaxDescription_1.minimaxFields,
                ...VideosCreateDescription_1.videosCreateFields,
                ...AccountCreateDescription_2.accountCreateFields,
                ...VideosRetrieveDescription_1.videosRetrieveFields,
                ...FilesCreateDescription_1.filesCreateFields,
                ...FilesListDescription_1.filesListFields,
                ...ImagineDescription_1.imagineFields,
                ...GetJobDescription_1.getJobFields,
                ...ButtonDescription_1.buttonFields,
                ...MidjourneyDescription_1.midjourneyOperations,
            ],
        };
    }
    async execute() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
        const items = this.getInputData();
        const returnData = [];
        for (let i = 0; i < items.length; i++) {
            try {
                const resource = this.getNodeParameter('resource', i);
                const operation = this.getNodeParameter('operation', i);
                let responseData;
                if (resource === 'runway') {
                    if (operation === 'getAssets') {
                        const offset = this.getNodeParameter('offset', i);
                        const limit = this.getNodeParameter('limit', i);
                        const additionalFields = this.getNodeParameter('additionalFields', i, {});
                        let queryString = `?offset=${offset}&limit=${limit}`;
                        if (additionalFields.mediaType)
                            queryString += `&mediaType=${encodeURIComponent(additionalFields.mediaType)}`;
                        const fullUrl = `${BASE_URL_V1}/runwayml/assets/${queryString}`;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: fullUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                        if (responseData && Array.isArray(responseData.assets)) {
                            const filterType = this.getNodeParameter('filterType', i, 'none');
                            if (filterType !== 'none') {
                                const filterValue = this.getNodeParameter('filterValue', i, '');
                                if (filterValue) {
                                    responseData.assets = responseData.assets.filter((asset) => {
                                        var _a;
                                        if (filterType === 'id') {
                                            return String(asset.id) === filterValue;
                                        }
                                        return (_a = String(asset[filterType])) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(filterValue.toLowerCase());
                                    });
                                }
                            }
                        }
                    }
                    else if (operation === 'getAsset') {
                        const assetId = this.getNodeParameter('assetId', i);
                        const fullUrl = `${BASE_URL_V1}/runwayml/assets/${assetId}`;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: fullUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'deleteAsset') {
                        const assetId = this.getNodeParameter('assetId', i);
                        const confirmation = this.getNodeParameter('confirmation', i);
                        if (!confirmation) {
                            throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Operation cancelled: You must confirm the deletion by checking the confirmation checkbox.', { itemIndex: i });
                        }
                        const fullUrl = `${BASE_URL_V1}/runwayml/assets/${assetId}`;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'DELETE',
                            url: fullUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'uploadAsset') {
                        const name = this.getNodeParameter('name', i);
                        const inputType = this.getNodeParameter('inputType', i);
                        const additionalFields = this.getNodeParameter('additionalFields', i, {});
                        let queryUrl = `${BASE_URL_V1}/runwayml/assets/?name=${encodeURIComponent(name)}`;
                        if (additionalFields.duration)
                            queryUrl += `&duration=${additionalFields.duration}`;
                        if (additionalFields.width)
                            queryUrl += `&width=${additionalFields.width}`;
                        if (additionalFields.height)
                            queryUrl += `&height=${additionalFields.height}`;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        let binaryData;
                        let contentType;
                        if (inputType === 'binaryData') {
                            const binaryPropertyName = this.getNodeParameter('binaryPropertyName', i);
                            if (!items[i].binary) {
                                throw new n8n_workflow_1.NodeApiError(this.getNode(), { message: 'No binary data found' });
                            }
                            const binary = items[i].binary;
                            if (!(binaryPropertyName in binary)) {
                                throw new n8n_workflow_1.NodeApiError(this.getNode(), { message: `No binary data found in property "${binaryPropertyName}"` });
                            }
                            const binaryProperty = binary[binaryPropertyName];
                            binaryData = await this.helpers.getBinaryDataBuffer(i, binaryPropertyName);
                            contentType = binaryProperty.mimeType;
                        }
                        else if (inputType === 'url') {
                            const url = this.getNodeParameter('url', i);
                            const response = await this.helpers.request({
                                method: 'GET',
                                url,
                                encoding: null,
                            });
                            binaryData = response;
                            const fileExtension = (_a = url.split('.').pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase();
                            if (fileExtension) {
                                const contentTypeMap = {
                                    'png': 'image/png',
                                    'jpg': 'image/jpeg',
                                    'jpeg': 'image/jpeg',
                                    'gif': 'image/gif',
                                    'webp': 'image/webp',
                                    'mpo': 'image/mpo',
                                    'mp4': 'video/mp4',
                                    'mov': 'video/quicktime',
                                    '3gp': 'video/3gpp',
                                    'mkv': 'video/x-matroska',
                                    'flv': 'video/x-flv',
                                    'mpeg': 'video/mpeg',
                                    'ts': 'video/MP2T',
                                    'avi': 'video/x-msvideo',
                                    'mjpeg': 'video/x-motion-jpeg',
                                    'webm': 'video/webm',
                                    'ogv': 'video/ogg',
                                    'wav': 'audio/wav',
                                    'mp3': 'audio/mpeg',
                                    'flac': 'audio/flac',
                                    'ogg': 'audio/ogg',
                                };
                                contentType = contentTypeMap[fileExtension] || 'application/octet-stream';
                            }
                            else {
                                contentType = 'application/octet-stream';
                            }
                        }
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: queryUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': contentType,
                            },
                            body: binaryData,
                            json: true,
                        });
                    }
                    else if (operation === 'gen3TurboCreate') {
                        const firstImageAssetId = this.getNodeParameter('firstImage_assetId', i);
                        const imageInput = this.getNodeParameter('imageInput', i);
                        const textPrompt = this.getNodeParameter('text_prompt', i, '');
                        const aspectRatio = this.getNodeParameter('aspect_ratio', i);
                        const seconds = this.getNodeParameter('seconds', i);
                        const seed = this.getNodeParameter('seed', i, '');
                        const cameraMotionOptions = this.getNodeParameter('cameraMotionOptions', i, {});
                        const additionalSettings = this.getNodeParameter('additionalSettings', i, {});
                        const requestBody = {
                            firstImage_assetId: firstImageAssetId,
                            text_prompt: textPrompt || undefined,
                            aspect_ratio: aspectRatio,
                            seconds: seconds,
                        };
                        if (imageInput === 'firstAndLastImages' || imageInput === 'allImages') {
                            requestBody.lastImage_assetId = this.getNodeParameter('lastImage_assetId', i, '');
                        }
                        if (imageInput === 'allImages') {
                            requestBody.middleImage_assetId = this.getNodeParameter('middleImage_assetId', i, '');
                        }
                        if (seed !== '') {
                            requestBody.seed = seed;
                        }
                        if (cameraMotionOptions.static) {
                            requestBody.static = true;
                        }
                        else {
                            if (cameraMotionOptions.horizontal !== undefined)
                                requestBody.horizontal = cameraMotionOptions.horizontal;
                            if (cameraMotionOptions.vertical !== undefined)
                                requestBody.vertical = cameraMotionOptions.vertical;
                            if (cameraMotionOptions.zoom !== undefined)
                                requestBody.zoom = cameraMotionOptions.zoom;
                            if (cameraMotionOptions.roll !== undefined)
                                requestBody.roll = cameraMotionOptions.roll;
                            if (cameraMotionOptions.pan !== undefined)
                                requestBody.pan = cameraMotionOptions.pan;
                            if (cameraMotionOptions.tilt !== undefined)
                                requestBody.tilt = cameraMotionOptions.tilt;
                        }
                        if (additionalSettings.exploreMode)
                            requestBody.exploreMode = true;
                        if (additionalSettings.replyUrl)
                            requestBody.replyUrl = additionalSettings.replyUrl;
                        if (additionalSettings.replyRef)
                            requestBody.replyRef = additionalSettings.replyRef;
                        if (additionalSettings.maxJobs)
                            requestBody.maxJobs = additionalSettings.maxJobs;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V1}/runwayml/gen3turbo/create`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json',
                            },
                            body: requestBody,
                            json: true,
                        });
                    }
                    else if (operation === 'getTasks') {
                        const offset = this.getNodeParameter('offset', i);
                        const limit = this.getNodeParameter('limit', i);
                        const additionalFields = this.getNodeParameter('additionalFields', i, {});
                        let queryString = `?offset=${offset}&limit=${limit}`;
                        if (additionalFields.email)
                            queryString += `&email=${encodeURIComponent(additionalFields.email)}`;
                        if (additionalFields.statuses)
                            queryString += `&statuses=${encodeURIComponent(additionalFields.statuses)}`;
                        const fullUrl = `${BASE_URL_V1}/runwayml/tasks/${queryString}`;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: fullUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'getTask') {
                        const taskId = this.getNodeParameter('taskId', i);
                        const fullUrl = `${BASE_URL_V1}/runwayml/tasks/${taskId}`;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: fullUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'describeImage') {
                        const imageAssetId = this.getNodeParameter('imageAssetId', i);
                        const fullUrl = `${BASE_URL_V1}/runwayml/frames/describe/${imageAssetId}`;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: fullUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'textToImage') {
                        const textPrompt = this.getNodeParameter('text_prompt', i);
                        const style = this.getNodeParameter('style', i);
                        const aspectRatio = this.getNodeParameter('aspect_ratio', i);
                        const additionalOptions = this.getNodeParameter('additionalOptions', i, {});
                        let queryUrl = `${BASE_URL_V1}/runwayml/text_to_image_preview/?text_prompt=${encodeURIComponent(textPrompt)}`;
                        queryUrl += `&style=${style}&aspect_ratio=${aspectRatio}`;
                        if (additionalOptions.prompt_weight)
                            queryUrl += `&prompt_weight=${additionalOptions.prompt_weight}`;
                        if (additionalOptions.negative_prompt)
                            queryUrl += `&negative_prompt=${encodeURIComponent(additionalOptions.negative_prompt)}`;
                        if (additionalOptions.seed)
                            queryUrl += `&seed=${additionalOptions.seed}`;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: queryUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'lipSync') {
                        const inputType = this.getNodeParameter('inputType', i);
                        const requestBody = {};
                        if (inputType === 'imageAudio' || inputType === 'imageVoiceText') {
                            requestBody.image_assetId = this.getNodeParameter('image_assetId', i);
                        }
                        if (inputType === 'videoAudio' || inputType === 'videoVoiceText') {
                            requestBody.video_assetId = this.getNodeParameter('video_assetId', i);
                        }
                        if (inputType === 'imageAudio' || inputType === 'videoAudio') {
                            requestBody.audio_assetId = this.getNodeParameter('audio_assetId', i);
                        }
                        if (inputType === 'imageVoiceText' || inputType === 'videoVoiceText') {
                            requestBody.voiceId = this.getNodeParameter('voiceId', i);
                            requestBody.voice_text = this.getNodeParameter('voice_text', i);
                            requestBody.model_id = this.getNodeParameter('model_id', i);
                        }
                        const additionalOptions = this.getNodeParameter('additionalOptions', i, {});
                        if (additionalOptions.exploreMode)
                            requestBody.exploreMode = true;
                        if (additionalOptions.replyUrl)
                            requestBody.replyUrl = additionalOptions.replyUrl;
                        if (additionalOptions.replyRef)
                            requestBody.replyRef = additionalOptions.replyRef;
                        if (additionalOptions.maxJobs)
                            requestBody.maxJobs = additionalOptions.maxJobs;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V1}/runwayml/lipsync/create`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json',
                            },
                            body: requestBody,
                            json: true,
                        });
                    }
                    else if (operation === 'videoToVideo') {
                        const assetId = this.getNodeParameter('assetId', i);
                        const textPrompt = this.getNodeParameter('text_prompt', i);
                        const aspectRatio = this.getNodeParameter('aspect_ratio', i);
                        const structureTransformation = this.getNodeParameter('structure_transformation', i);
                        const seconds = this.getNodeParameter('seconds', i);
                        const additionalOptions = this.getNodeParameter('additionalOptions', i, {});
                        const requestBody = {
                            assetId: assetId,
                            text_prompt: textPrompt,
                            aspect_ratio: aspectRatio,
                            structure_transformation: structureTransformation,
                            seconds: seconds
                        };
                        if (additionalOptions.seed)
                            requestBody.seed = additionalOptions.seed;
                        if (additionalOptions.exploreMode)
                            requestBody.exploreMode = true;
                        if (additionalOptions.replyUrl)
                            requestBody.replyUrl = additionalOptions.replyUrl;
                        if (additionalOptions.replyRef)
                            requestBody.replyRef = additionalOptions.replyRef;
                        if (additionalOptions.maxJobs)
                            requestBody.maxJobs = additionalOptions.maxJobs;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V1}/runwayml/gen3turbo/video`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json',
                            },
                            body: requestBody,
                            json: true,
                        });
                    }
                    else if (operation === 'gen4Create') {
                        const firstImageAssetId = this.getNodeParameter('firstImage_assetId', i);
                        const textPrompt = this.getNodeParameter('text_prompt', i, '');
                        const aspectRatio = this.getNodeParameter('aspect_ratio', i);
                        const seconds = this.getNodeParameter('seconds', i);
                        const additionalOptions = this.getNodeParameter('additionalOptions', i, {});
                        const requestBody = {
                            firstImage_assetId: firstImageAssetId,
                            aspect_ratio: aspectRatio,
                            seconds: seconds
                        };
                        if (textPrompt) {
                            requestBody.text_prompt = textPrompt;
                        }
                        if (additionalOptions.seed !== undefined)
                            requestBody.seed = additionalOptions.seed;
                        if (additionalOptions.exploreMode)
                            requestBody.exploreMode = true;
                        if (additionalOptions.replyUrl)
                            requestBody.replyUrl = additionalOptions.replyUrl;
                        if (additionalOptions.replyRef)
                            requestBody.replyRef = additionalOptions.replyRef;
                        if (additionalOptions.maxJobs)
                            requestBody.maxJobs = additionalOptions.maxJobs;
                        const credentials = await this.getCredentials('useApiApi');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V1}/runwayml/gen4/create`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json',
                            },
                            body: requestBody,
                            json: true,
                        });
                    }
                    else if (operation === 'createAccount') {
                        const confirmRegistration = this.getNodeParameter('confirmRegistration', i);
                        if (!confirmRegistration) {
                            throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Operation cancelled: Please confirm the registration by checking the confirmation checkbox.', { itemIndex: i });
                        }
                        const credentials = await this.getCredentials('useApiApi');
                        const apiToken = credentials.apiKey;
                        const runwayEmail = credentials.runwayEmail;
                        const runwayPassword = credentials.runwayPassword;
                        const maxJobs = 5;
                        if (!runwayEmail || !runwayPassword) {
                            throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Missing required credential fields: Please ensure "Runway Email" and "Runway Password" are set in your credentials.', { itemIndex: i });
                        }
                        const requestBody = {
                            email: runwayEmail,
                            password: runwayPassword,
                            maxJobs: maxJobs,
                        };
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V1}/runwayml/accounts/${runwayEmail}`,
                            headers: {
                                'Authorization': `Bearer ${apiToken}`,
                                'Content-Type': 'application/json',
                            },
                            body: requestBody,
                            json: true,
                        });
                    }
                }
                else if (resource === 'minimax') {
                    if (operation === 'getAccountInfo') {
                        const additionalFields = this.getNodeParameter('additionalFields', i, {});
                        let queryString = '';
                        if (additionalFields.includeUsageStats)
                            queryString += '?includeUsageStats=true';
                        const fullUrl = `${BASE_URL_V1}/minimax/account${queryString}`;
                        const credentials = await this.getCredentials('useApiMinimax');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: fullUrl,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'createVideo') {
                        const inputType = this.getNodeParameter('inputType', i);
                        const requestBody = {};
                        const prompt = this.getNodeParameter('prompt', i, '');
                        if (prompt)
                            requestBody.prompt = prompt;
                        if (inputType === 'imageText') {
                            requestBody.fileID = this.getNodeParameter('fileID', i);
                        }
                        requestBody.model = this.getNodeParameter('model', i);
                        const additionalOptions = this.getNodeParameter('additionalOptions', i, {});
                        if (additionalOptions.account)
                            requestBody.account = additionalOptions.account;
                        if (additionalOptions.promptOptimization !== undefined)
                            requestBody.promptOptimization = additionalOptions.promptOptimization;
                        if (additionalOptions.replyUrl)
                            requestBody.replyUrl = additionalOptions.replyUrl;
                        if (additionalOptions.replyRef)
                            requestBody.replyRef = additionalOptions.replyRef;
                        if (additionalOptions.maxJobs)
                            requestBody.maxJobs = additionalOptions.maxJobs;
                        const credentials = await this.getCredentials('useApiMinimax');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V1}/minimax/videos/create`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json',
                            },
                            body: requestBody,
                            json: true,
                        });
                    }
                    else if (operation === 'createAccount') {
                        const confirmRegistration = this.getNodeParameter('confirmRegistration', i);
                        if (!confirmRegistration) {
                            throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Operation cancelled: Please confirm the registration by checking the confirmation checkbox.', { itemIndex: i });
                        }
                        const credentials = await this.getCredentials('useApiMinimax');
                        const apiToken = credentials.apiKey;
                        const minimaxAccount = credentials.minimaxAccount;
                        const minimaxUrl = credentials.minimaxUrl;
                        const minimaxToken = credentials.minimaxToken;
                        const maxJobs = credentials.maxJobs || 1;
                        if (!minimaxAccount || !minimaxToken) {
                            throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Missing required credential fields: Please ensure "Account Name" and "Minimax API Token" are set in your credentials.', { itemIndex: i });
                        }
                        const requestBody = {
                            account: minimaxAccount,
                            url: minimaxUrl || '',
                            token: minimaxToken,
                            maxJobs: maxJobs,
                        };
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V1}/minimax/accounts/${minimaxAccount}`,
                            headers: {
                                'Authorization': `Bearer ${apiToken}`,
                                'Content-Type': 'application/json',
                            },
                            body: requestBody,
                            json: true,
                        });
                    }
                    else if (operation === 'retrieveVideo') {
                        const videoId = this.getNodeParameter('videoId', i);
                        const credentials = await this.getCredentials('useApiMinimax');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: `${BASE_URL_V1}/minimax/videos/${videoId}`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'uploadFile') {
                        const account = this.getNodeParameter('account', i, '');
                        const inputType = this.getNodeParameter('inputType', i);
                        const credentials = await this.getCredentials('useApiMinimax');
                        const token = credentials.apiKey;
                        let url = `${BASE_URL_V1}/minimax/files/`;
                        if (account) {
                            url += `?account=${encodeURIComponent(account)}`;
                        }
                        let binaryData;
                        let contentType;
                        if (inputType === 'binaryData') {
                            const binaryPropertyName = this.getNodeParameter('binaryPropertyName', i);
                            if (!items[i].binary) {
                                throw new n8n_workflow_1.NodeApiError(this.getNode(), { message: 'No binary data found' });
                            }
                            const binary = items[i].binary;
                            if (!(binaryPropertyName in binary)) {
                                throw new n8n_workflow_1.NodeApiError(this.getNode(), { message: `No binary data found in property "${binaryPropertyName}"` });
                            }
                            const binaryProperty = binary[binaryPropertyName];
                            binaryData = await this.helpers.getBinaryDataBuffer(i, binaryPropertyName);
                            contentType = binaryProperty.mimeType;
                            if (!contentType.startsWith('image/')) {
                                throw new n8n_workflow_1.NodeApiError(this.getNode(), { message: `Invalid content type: ${contentType}. Only image files are supported.` });
                            }
                        }
                        else if (inputType === 'url') {
                            const imageUrl = this.getNodeParameter('url', i);
                            const response = await this.helpers.request({
                                method: 'GET',
                                url: imageUrl,
                                encoding: null,
                            });
                            binaryData = response;
                            const fileExtension = (_b = imageUrl.split('.').pop()) === null || _b === void 0 ? void 0 : _b.toLowerCase();
                            if (fileExtension === 'png') {
                                contentType = 'image/png';
                            }
                            else if (['jpg', 'jpeg'].includes(fileExtension || '')) {
                                contentType = 'image/jpeg';
                            }
                            else if (fileExtension === 'webp') {
                                contentType = 'image/jpeg';
                            }
                            else {
                                contentType = 'image/jpeg';
                            }
                        }
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: url,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': contentType,
                            },
                            body: binaryData,
                            json: true,
                        });
                    }
                    else if (operation === 'listFiles') {
                        const account = this.getNodeParameter('account', i, '');
                        const limit = this.getNodeParameter('limit', i, 10);
                        const credentials = await this.getCredentials('useApiMinimax');
                        const token = credentials.apiKey;
                        let url = `${BASE_URL_V1}/minimax/files/?limit=${limit}`;
                        if (account) {
                            url += `&account=${encodeURIComponent(account)}`;
                        }
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: url,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                        if (responseData && Array.isArray(responseData)) {
                            const filterType = this.getNodeParameter('filterType', i, 'none');
                            if (filterType !== 'none') {
                                const filterValue = this.getNodeParameter('filterValue', i, '');
                                if (filterValue) {
                                    responseData = responseData.filter(file => {
                                        var _a;
                                        if (filterType === 'file_id') {
                                            return String(file.file_id) === filterValue ||
                                                String(file.fileId) === filterValue ||
                                                String(file.id) === filterValue;
                                        }
                                        return String(file[filterType]) === filterValue ||
                                            ((_a = String(file[filterType])) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(filterValue.toLowerCase()));
                                    });
                                }
                            }
                        }
                    }
                    else if (operation === 'listImages') {
                        try {
                            const limit = this.getNodeParameter('limit', i, 10);
                            console.log(`DEBUG: Listing images, limit: ${limit}`);
                            const url = `${BASE_URL_V1}/minimax/images/?limit=${limit}`;
                            console.log(`DEBUG: Using URL: ${url}`);
                            const credentials = await this.getCredentials('useApiMinimax');
                            const token = credentials.apiKey;
                            console.log(`DEBUG: Token available: ${token ? 'Yes (not shown for security)' : 'No'}`);
                            try {
                                responseData = await this.helpers.request({
                                    method: 'GET',
                                    url: url,
                                    headers: {
                                        'Authorization': `Bearer ${token}`,
                                    },
                                    json: true,
                                });
                                console.log(`DEBUG: Response received:`, responseData);
                                if (responseData && Array.isArray(responseData)) {
                                    const filterType = this.getNodeParameter('filterType', i, 'none');
                                    if (filterType !== 'none') {
                                        const filterValue = this.getNodeParameter('filterValue', i, '');
                                        if (filterValue) {
                                            responseData = responseData.filter(image => {
                                                var _a;
                                                if (filterType === 'id') {
                                                    return String(image.id) === filterValue ||
                                                        String(image.imageId) === filterValue;
                                                }
                                                return String(image[filterType]) === filterValue ||
                                                    ((_a = String(image[filterType])) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(filterValue.toLowerCase()));
                                            });
                                        }
                                    }
                                }
                            }
                            catch (requestError) {
                                console.error(`DEBUG: API request error:`, requestError.message);
                                if (requestError.response) {
                                    console.error(`DEBUG: Status code:`, requestError.response.statusCode);
                                    console.error(`DEBUG: Response body:`, requestError.response.body);
                                }
                                throw requestError;
                            }
                        }
                        catch (error) {
                            console.error(`DEBUG: Operation error:`, error.message);
                            if (this.continueOnFail()) {
                                const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({
                                    error: error.message,
                                    details: ((_c = error.response) === null || _c === void 0 ? void 0 : _c.body) || "No additional details",
                                    status: (_d = error.response) === null || _d === void 0 ? void 0 : _d.statusCode,
                                    statusText: (_e = error.response) === null || _e === void 0 ? void 0 : _e.statusText
                                }), { itemData: { item: i } });
                                returnData.push(...executionData);
                                continue;
                            }
                            throw error;
                        }
                    }
                    else if (operation === 'listVideos') {
                        try {
                            const limit = this.getNodeParameter('limit', i, 10);
                            console.log(`DEBUG: Listing videos, limit: ${limit}`);
                            const url = `${BASE_URL_V1}/minimax/videos/?limit=${limit}`;
                            console.log(`DEBUG: Using URL: ${url}`);
                            const credentials = await this.getCredentials('useApiMinimax');
                            const token = credentials.apiKey;
                            console.log(`DEBUG: Token available: ${token ? 'Yes (not shown for security)' : 'No'}`);
                            try {
                                responseData = await this.helpers.request({
                                    method: 'GET',
                                    url: url,
                                    headers: {
                                        'Authorization': `Bearer ${token}`,
                                    },
                                    json: true,
                                });
                                console.log(`DEBUG: Response received:`, responseData);
                                if (responseData && Array.isArray(responseData)) {
                                    const filterType = this.getNodeParameter('filterType', i, 'none');
                                    if (filterType !== 'none') {
                                        const filterValue = this.getNodeParameter('filterValue', i, '');
                                        if (filterValue) {
                                            responseData = responseData.filter(video => {
                                                var _a;
                                                if (filterType === 'id') {
                                                    return String(video.id) === filterValue ||
                                                        String(video.videoId) === filterValue;
                                                }
                                                return String(video[filterType]) === filterValue ||
                                                    ((_a = String(video[filterType])) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(filterValue.toLowerCase()));
                                            });
                                        }
                                    }
                                }
                            }
                            catch (requestError) {
                                console.error(`DEBUG: API request error:`, requestError.message);
                                if (requestError.response) {
                                    console.error(`DEBUG: Status code:`, requestError.response.statusCode);
                                    console.error(`DEBUG: Response body:`, requestError.response.body);
                                }
                                throw requestError;
                            }
                        }
                        catch (error) {
                            console.error(`DEBUG: Operation error:`, error.message);
                            if (this.continueOnFail()) {
                                const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({
                                    error: error.message,
                                    details: ((_f = error.response) === null || _f === void 0 ? void 0 : _f.body) || "No additional details",
                                    status: (_g = error.response) === null || _g === void 0 ? void 0 : _g.statusCode,
                                    statusText: (_h = error.response) === null || _h === void 0 ? void 0 : _h.statusText
                                }), { itemData: { item: i } });
                                returnData.push(...executionData);
                                continue;
                            }
                            throw error;
                        }
                    }
                    else if (operation === ImagesCreateDescription_1.IMAGES_CREATE_OPERATION) {
                        try {
                            const prompt = this.getNodeParameter('prompt', i);
                            console.log(`DEBUG: Using prompt: ${prompt}`);
                            const requestBody = {
                                prompt: prompt,
                            };
                            const additionalOptions = this.getNodeParameter('additionalOptions', i, {});
                            if (additionalOptions.promptOptimization !== undefined)
                                requestBody.promptOptimization = additionalOptions.promptOptimization;
                            if (additionalOptions.model)
                                requestBody.model = additionalOptions.model;
                            if (additionalOptions.aspectRatio)
                                requestBody.aspectRatio = additionalOptions.aspectRatio;
                            if (additionalOptions.quantity)
                                requestBody.quantity = additionalOptions.quantity;
                            if (additionalOptions.replyUrl)
                                requestBody.replyUrl = additionalOptions.replyUrl;
                            if (additionalOptions.replyRef)
                                requestBody.replyRef = additionalOptions.replyRef;
                            console.log(`DEBUG: Request body:`, requestBody);
                            const url = `${BASE_URL_V1}/minimax/images/create`;
                            console.log(`DEBUG: Using URL: ${url}`);
                            const credentials = await this.getCredentials('useApiMinimax');
                            const token = credentials.apiKey;
                            console.log(`DEBUG: Token available: ${token ? 'Yes (not shown for security)' : 'No'}`);
                            try {
                                responseData = await this.helpers.request({
                                    method: 'POST',
                                    url: url,
                                    headers: {
                                        'Authorization': `Bearer ${token}`,
                                        'Content-Type': 'application/json',
                                    },
                                    body: requestBody,
                                    json: true,
                                });
                                console.log(`DEBUG: Response received:`, responseData);
                            }
                            catch (requestError) {
                                console.error(`DEBUG: API request error:`, requestError.message);
                                if (requestError.response) {
                                    console.error(`DEBUG: Status code:`, requestError.response.statusCode);
                                    console.error(`DEBUG: Response body:`, requestError.response.body);
                                }
                                throw requestError;
                            }
                        }
                        catch (error) {
                            console.error(`DEBUG: Operation error:`, error.message);
                            if (this.continueOnFail()) {
                                const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({
                                    error: error.message,
                                    details: ((_j = error.response) === null || _j === void 0 ? void 0 : _j.body) || "No additional details",
                                    status: (_k = error.response) === null || _k === void 0 ? void 0 : _k.statusCode,
                                    statusText: (_l = error.response) === null || _l === void 0 ? void 0 : _l.statusText
                                }), { itemData: { item: i } });
                                returnData.push(...executionData);
                                continue;
                            }
                            throw error;
                        }
                    }
                    else if (operation === ImagesRetrieveDescription_1.IMAGES_RETRIEVE_OPERATION) {
                        try {
                            const imageId = this.getNodeParameter('imageId', i);
                            console.log(`DEBUG: Retrieving image with ID: ${imageId}`);
                            const url = `${BASE_URL_V1}/minimax/images/${imageId}`;
                            console.log(`DEBUG: Using URL: ${url}`);
                            const credentials = await this.getCredentials('useApiMinimax');
                            const token = credentials.apiKey;
                            console.log(`DEBUG: Token available: ${token ? 'Yes (not shown for security)' : 'No'}`);
                            try {
                                responseData = await this.helpers.request({
                                    method: 'GET',
                                    url: url,
                                    headers: {
                                        'Authorization': `Bearer ${token}`,
                                    },
                                    json: true,
                                });
                                console.log(`DEBUG: Response received:`, responseData);
                            }
                            catch (requestError) {
                                console.error(`DEBUG: API request error:`, requestError.message);
                                if (requestError.response) {
                                    console.error(`DEBUG: Status code:`, requestError.response.statusCode);
                                    console.error(`DEBUG: Response body:`, requestError.response.body);
                                }
                                throw requestError;
                            }
                        }
                        catch (error) {
                            console.error(`DEBUG: Operation error:`, error.message);
                            if (this.continueOnFail()) {
                                const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({
                                    error: error.message,
                                    details: ((_m = error.response) === null || _m === void 0 ? void 0 : _m.body) || "No additional details",
                                    status: (_o = error.response) === null || _o === void 0 ? void 0 : _o.statusCode,
                                    statusText: (_p = error.response) === null || _p === void 0 ? void 0 : _p.statusText
                                }), { itemData: { item: i } });
                                returnData.push(...executionData);
                                continue;
                            }
                            throw error;
                        }
                    }
                }
                else if (resource === 'midjourney') {
                    if (operation === 'imagine') {
                        const prompt = this.getNodeParameter('prompt', i);
                        const additionalOptions = this.getNodeParameter('additionalOptions', i, {});
                        const credentials = await this.getCredentials('useApiMidjourney');
                        const token = credentials.apiKey;
                        let finalPrompt = prompt;
                        if (additionalOptions.aspectRatio) {
                            finalPrompt = `${prompt} --ar ${additionalOptions.aspectRatio}`;
                        }
                        const body = {
                            prompt: finalPrompt,
                        };
                        if (additionalOptions.maxJobs) {
                            body.maxJobs = additionalOptions.maxJobs;
                        }
                        else if (credentials.maxJobs) {
                            body.maxJobs = credentials.maxJobs;
                        }
                        if (additionalOptions.replyUrl) {
                            body.replyUrl = additionalOptions.replyUrl;
                        }
                        if (additionalOptions.replyRef) {
                            body.replyRef = additionalOptions.replyRef;
                        }
                        if (additionalOptions.discord) {
                            body.discord = additionalOptions.discord;
                        }
                        else if (credentials.discordToken) {
                            body.discord = credentials.discordToken;
                        }
                        if (additionalOptions.server) {
                            body.server = additionalOptions.server;
                        }
                        else if (credentials.discordServer) {
                            body.server = credentials.discordServer;
                        }
                        if (additionalOptions.channel) {
                            body.channel = additionalOptions.channel;
                        }
                        else if (credentials.discordChannel) {
                            body.channel = credentials.discordChannel;
                        }
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V2}/jobs/imagine`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json',
                            },
                            body,
                            json: true,
                        });
                    }
                    else if (operation === 'getJob') {
                        const jobId = this.getNodeParameter('jobId', i);
                        const credentials = await this.getCredentials('useApiMidjourney');
                        const token = credentials.apiKey;
                        responseData = await this.helpers.request({
                            method: 'GET',
                            url: `${BASE_URL_V2}/jobs/?jobid=${jobId}`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                            },
                            json: true,
                        });
                    }
                    else if (operation === 'button') {
                        const jobId = this.getNodeParameter('jobId', i);
                        const button = this.getNodeParameter('button', i);
                        const additionalOptions = this.getNodeParameter('additionalOptions', i, {});
                        const credentials = await this.getCredentials('useApiMidjourney');
                        const token = credentials.apiKey;
                        const body = {
                            jobid: jobId,
                            button: button,
                        };
                        if (additionalOptions.prompt) {
                            body.prompt = additionalOptions.prompt;
                        }
                        if (additionalOptions.maxJobs) {
                            body.maxJobs = additionalOptions.maxJobs;
                        }
                        else if (credentials.maxJobs) {
                            body.maxJobs = credentials.maxJobs;
                        }
                        if (additionalOptions.replyUrl) {
                            body.replyUrl = additionalOptions.replyUrl;
                        }
                        if (additionalOptions.replyRef) {
                            body.replyRef = additionalOptions.replyRef;
                        }
                        if (additionalOptions.discord) {
                            body.discord = additionalOptions.discord;
                        }
                        else if (credentials.discordToken) {
                            body.discord = credentials.discordToken;
                        }
                        responseData = await this.helpers.request({
                            method: 'POST',
                            url: `${BASE_URL_V2}/jobs/button`,
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json',
                            },
                            body,
                            json: true,
                        });
                    }
                }
                const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray(responseData || { error: "Failed to get data from API" }), { itemData: { item: i } });
                returnData.push(...executionData);
            }
            catch (error) {
                if (this.continueOnFail()) {
                    const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({
                        error: error.message,
                        details: ((_q = error.response) === null || _q === void 0 ? void 0 : _q.data) || "No additional details",
                        status: (_r = error.response) === null || _r === void 0 ? void 0 : _r.status,
                        statusText: (_s = error.response) === null || _s === void 0 ? void 0 : _s.statusText
                    }), { itemData: { item: i } });
                    returnData.push(...executionData);
                    continue;
                }
                throw error;
            }
        }
        return [returnData];
    }
}
exports.UseApi = UseApi;
//# sourceMappingURL=UseApi.node.js.map