UNPKG

n8n-nodes-hjhcomfyui

Version:

n8n node to integrate with ComfyUI stable diffusion workflows

321 lines 13.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Hjhcomfyuicheck = void 0; const n8n_workflow_1 = require("n8n-workflow"); const n8n_workflow_2 = require("n8n-workflow"); function getReturnPostData(data) { let outputs = data.outputs; let prompt = data.prompt[2]; let status = data.status; if (status.status_str == "success") { let outputId = null; for (let id in prompt) { if (prompt[id]["_meta"]["title"] == "HJH Check Result") { outputId = id; break; } } if (outputId) { try { let res = outputs[outputId]["text"]; if (typeof (res) == "string") { res = JSON.parse(res); } if (typeof (res[0]) == "string") { res[0] = JSON.parse(res[0]); } return res[0]; } catch (e) { return []; } } } else { let ret = { "code": 400, "data": {}, "message": "HjhComfyUI workflow execution failed", }; let executionError = status["messages"][2][1]; data = { "node_type": executionError["node_type"], "exception_type": executionError["exception_type"], }; ret["data"] = data; ret["message"] = executionError["exception_message"]; return ret; } return []; } class Hjhcomfyuicheck { constructor() { this.description = { displayName: 'HjhComfyUICheck', name: 'hjhcomfyuicheck', icon: 'file:hjhcomfyuicheck.svg', group: ['transform'], version: 1, description: 'Execute HjhComfyUICheck workflows', defaults: { name: 'HjhComfyUICheck', }, credentials: [ { name: 'hjhComfyUIApi', required: true, }, ], inputs: ['main'], outputs: ['main'], properties: [ { displayName: 'Use Hjh Services', name: 'useHjhServices', type: 'boolean', default: true, description: 'Whether to use Hjh services in the workflow', }, { displayName: 'Hjh Services', name: 'services', type: 'string', typeOptions: { rows: 10, }, default: '', description: 'The Hjh services in JSON format', }, { displayName: 'Hjh User Image', name: 'userImage', type: 'string', typeOptions: { rows: 10, }, default: '', required: true, description: 'The user image', }, { displayName: 'Hjh Workflow JSON', name: 'workflow', type: 'string', typeOptions: { rows: 10, }, default: '', required: true, description: 'The HjhComfyUICheck workflow in JSON format', }, { displayName: 'Wait For Result', name: 'waitForResult', type: 'boolean', default: true, description: 'Whether to wait for the workflow to complete before returning results', }, { displayName: 'Timeout', name: 'timeout', type: 'number', default: 30, description: 'Maximum time in seconds to wait for workflow completion', }, ], }; } async execute() { var _a, _b; const useHjhServices = this.getNodeParameter('useHjhServices', 0); const waitForResult = this.getNodeParameter('waitForResult', 0); const services = this.getNodeParameter('services', 0); const userImage = this.getNodeParameter('userImage', 0); let workflow = this.getNodeParameter('workflow', 0); const timeout = this.getNodeParameter('timeout', 0); let apiUrl = ""; let apiKey = ""; let apiUrls = []; if (useHjhServices) { if (services) { let services1 = JSON.parse(services); apiUrl = services1.comfyui_check; apiUrls = apiUrl.split(","); } else { const credentials = await this.getCredentials('hjhComfyUIApi'); apiUrl = credentials.apiUrl; apiKey = credentials.apiKey; apiUrls[0] = apiUrl; } } else { const credentials = await this.getCredentials('hjhComfyUIApi'); apiUrl = credentials.apiUrl; apiKey = credentials.apiKey; apiUrls[0] = apiUrl; } let url = apiUrl; console.log('[HjhComfyUICheck] Executing with API URL:', apiUrl); const headers = { 'Content-Type': 'application/json', }; if (apiKey) { console.log('[HjhComfyUICheck] Using API key authentication'); headers['Authorization'] = `Bearer ${apiKey}`; } try { let errors = []; apiUrl = ""; for (const apiUrl1 of apiUrls) { console.log('[HjhComfyUIScale] Checking API connection...', apiUrl1); try { await this.helpers.request({ method: 'GET', url: `${apiUrl1}/system_stats`, headers, json: true, timeout: 1000 }); apiUrl = apiUrl1; break; } catch (error) { console.error('[HjhComfyUIScaleJson] Execution error:', error); this.logger.error('[HjhComfyUIScaleJson] Execution error:', error); errors.push(error.toString()); } } if (apiUrl == "") { throw new n8n_workflow_2.NodeApiError(this.getNode(), { message: 'No available service ' + errors.join(", ") }); } workflow = workflow.replace("<user-image>", userImage); console.log('[HjhComfyUICheck] Queueing prompt...'); this.logger.debug('[HjhComfyUICheck] Queueing prompt with workflow:' + workflow); url = `${apiUrl}/prompt`; const response = await this.helpers.request({ method: 'POST', url: `${apiUrl}/prompt`, headers, body: { prompt: JSON.parse(workflow), }, timeout: 30000, json: true, }); if (!response.prompt_id) { throw new n8n_workflow_2.NodeApiError(this.getNode(), { message: 'Failed to get prompt ID from HjhComfyUICheck' }); } const promptId = response.prompt_id; console.log('[HjhComfyUICheck] Prompt queued with ID:', promptId); if (waitForResult) { let attempts = 0; const maxAttempts = timeout; let startTime = new Date().getTime(); await new Promise(resolve => setTimeout(resolve, 1000)); let endTime = new Date().getTime(); while (endTime - startTime < maxAttempts * 1000) { console.log(`[HjhComfyUICheck] Checking execution status (attempt ${attempts + 1}/${maxAttempts})...`); await new Promise(resolve => setTimeout(resolve, 1000)); attempts++; let promptResult; try { const history = await this.helpers.request({ method: 'GET', url: `${apiUrl}/history/${promptId}`, headers, timeout: 3000, json: true, }); promptResult = history[promptId]; endTime = new Date().getTime(); } catch (error) { console.error('[HjhComfyUIScaleJson] Execution error:', error); this.logger.error('[HjhComfyUIScaleJson] Execution error:', error); errors.push(error.toString()); continue; } if (!promptResult) { console.log('[HjhComfyUICheck] Prompt not found in history'); continue; } if (promptResult.status === undefined) { console.log('[HjhComfyUICheck] Execution status not found'); continue; } if ((_a = promptResult.status) === null || _a === void 0 ? void 0 : _a.completed) { console.log('[HjhComfyUICheck] Execution completed'); if (((_b = promptResult.status) === null || _b === void 0 ? void 0 : _b.status_str) === 'error') { throw new n8n_workflow_2.NodeApiError(this.getNode(), { message: '[HjhComfyUICheck] Workflow execution failed' }); } if (!promptResult.outputs) { throw new n8n_workflow_2.NodeApiError(this.getNode(), { message: '[HjhComfyUICheck] No outputs found in workflow result' }); } console.log(promptResult); let checkResult = getReturnPostData(promptResult); if (checkResult) { if (checkResult.code != 200) { throw new n8n_workflow_2.NodeApiError(this.getNode(), { message: '[HjhComfyUICheck] Workflow execution failed: ' + checkResult.message }); } let faceAttrs = JSON.parse(checkResult.data.face_attrs); if (faceAttrs.data.counts > 0) { let responseData = { code: 200, message: 'ok', description: 'ok', checkResult: checkResult, promptResult: promptResult, promptId: promptId, }; console.log('[HjhComfyUI] get images result successfully'); return [this.helpers.returnJsonArray(responseData)]; } else { throw new n8n_workflow_2.NodeApiError(this.getNode(), { message: '[HjhComfyUICheck] Workflow execution failed: no face found' }); } } else { throw new n8n_workflow_2.NodeApiError(this.getNode(), { message: '[HjhComfyUICheck] Workflow execution failed: no check result found' }); } } } } else { let responseData = { code: 200, message: 'ok', description: 'ok', files: [], checkResult: {}, promptResult: {}, promptId: promptId, }; console.log('[HjhComfyUI] send prompt successfully'); return [this.helpers.returnJsonArray(responseData)]; } throw new n8n_workflow_2.NodeApiError(this.getNode(), { message: `Execution timeout after ${timeout} seconds` }); } catch (error) { console.error('[HjhComfyUICheck] Execution error:', error); this.logger.error('[HjhComfyUICheck] Execution error:', error); if (!this.continueOnFail()) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), { message: `HjhComfyUICheck API Error: ${error.message} ${url} ${apiUrl} ${apiKey} ` + error.toString(), description: `HjhComfyUICheck API Error: ${error.message} ${url} ${apiUrl} ${apiKey} ` + error.toString() }, { message: `HjhComfyUICheck API Error: ${error.message} ${url} ${apiUrl} ${apiKey} ` + error.toString(), description: `HjhComfyUICheck API Error: ${error.message} ${url} ${apiUrl} ${apiKey} ` + error.toString() }); } let errorItems = { code: 500, message: error.message, description: `HjhComfyUICheck API Error: ${error.message} ${url} ${apiUrl} ${apiKey} ${error.toString()} ` + error.stack, }; return [this.helpers.returnJsonArray(errorItems)]; } } } exports.Hjhcomfyuicheck = Hjhcomfyuicheck; //# sourceMappingURL=Hjhcomfyuicheck.node.js.map