Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0cb2af3dc3 | ||
|
|
9d999f92a9 | ||
|
|
01e8668d1a | ||
|
|
8e58d962a7 | ||
|
|
c59c308d32 | ||
|
|
4560f2cca9 | ||
|
|
872752b820 | ||
|
|
97bb2b69c5 | ||
|
|
08fe87c8af | ||
|
|
d43e5fcefc | ||
|
|
65492a108c | ||
|
|
1939ff4153 | ||
|
|
4c32248d86 | ||
|
|
5ddbfdf44b | ||
|
|
7e86c20383 | ||
|
|
3adf77617b | ||
|
|
1bc62a5fb4 | ||
|
|
d473a211d0 | ||
|
|
3aa239e58d | ||
|
|
223aa5e70b | ||
|
|
5eef60a4eb | ||
|
|
de750995cb | ||
|
|
0f58fbcebd | ||
|
|
6dc964c425 | ||
|
|
4171c08413 | ||
|
|
4348ab45dc | ||
|
|
df46e3a0e5 | ||
|
|
2772101bbf | ||
|
|
72fee51d32 | ||
|
|
ffe0f98360 | ||
|
|
68377a84bc | ||
|
|
50d4c399e9 | ||
|
|
5a3955dfcb | ||
|
|
03227b52c0 | ||
|
|
8a8fbccfaa | ||
|
|
018d9a7b8d | ||
|
|
774fd566d1 | ||
|
|
b81fcae6fb | ||
|
|
b6b34c9062 | ||
|
|
f73baa091a | ||
|
|
a838cb7ad4 | ||
|
|
2afcade4f2 | ||
|
|
d70333baa6 | ||
|
|
43cfebd97a | ||
|
|
763d2f77ce | ||
|
|
f1b68164c6 | ||
|
|
6437de4def | ||
|
|
b24bdb070e | ||
|
|
33b57aea34 | ||
|
|
71dcbe0d11 | ||
|
|
8e3ee6468f | ||
|
|
b8f39239ba | ||
|
|
9296f8f703 | ||
|
|
6ed7807081 | ||
|
|
43fe0a384a | ||
|
|
dae6e46a8e | ||
|
|
f7f3d9708b | ||
|
|
52d6e07eeb | ||
|
|
f64c242ee5 | ||
|
|
c0450b58d5 | ||
|
|
47168930dc | ||
|
|
3043093d22 | ||
|
|
271552b453 |
@@ -4,4 +4,15 @@ FROM mcr.microsoft.com/vscode/devcontainers/typescript-node:${VARIANT}
|
|||||||
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
|
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
|
||||||
# && apt-get -y install --no-install-recommends <your-package-list-here>
|
# && apt-get -y install --no-install-recommends <your-package-list-here>
|
||||||
|
|
||||||
|
WORKDIR "/"
|
||||||
|
|
||||||
|
# Install fly
|
||||||
|
RUN curl -L https://fly.io/install.sh | sh
|
||||||
|
|
||||||
|
ENV FLYCTL_INSTALL="/root/.fly"
|
||||||
|
ENV PATH="$FLYCTL_INSTALL/bin:$PATH"
|
||||||
|
|
||||||
|
# RUN echo 'export FLYCTL_INSTALL="/home/node/.fly"' >> ~/.bashrc
|
||||||
|
# RUN echo 'export PATH="$FLYCTL_INSTALL/bin:$PATH"' >> ~/.bashrc
|
||||||
|
|
||||||
RUN npm install -g bun
|
RUN npm install -g bun
|
||||||
@@ -1,17 +1,21 @@
|
|||||||
{
|
{
|
||||||
"name": "Comfy Deploy Dev",
|
"name": "Comfy Deploy Dev",
|
||||||
"dockerComposeFile": "docker-compose.yml",
|
"dockerComposeFile": "docker-compose.yml",
|
||||||
"service": "app",
|
"service": "app",
|
||||||
"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
|
"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
|
||||||
"postCreateCommand": "cd web && bun install && bun run migrate-local",
|
"postCreateCommand": "cd web && bun install && bun run migrate-local",
|
||||||
"customizations": {
|
"remoteUser": "root",
|
||||||
"vscode": {
|
"customizations": {
|
||||||
"extensions": [
|
"vscode": {
|
||||||
"biomejs.biome",
|
"extensions": [
|
||||||
"formulahendry.auto-rename-tag",
|
"biomejs.biome",
|
||||||
"bradlc.vscode-tailwindcss",
|
"formulahendry.auto-rename-tag",
|
||||||
"stivo.tailwind-fold"
|
"bradlc.vscode-tailwindcss",
|
||||||
]
|
"stivo.tailwind-fold",
|
||||||
}
|
"streetsidesoftware.code-spell-checker",
|
||||||
}
|
"GitHub.copilot",
|
||||||
}
|
"ms-azuretools.vscode-docker"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,7 @@
|
|||||||
{
|
{
|
||||||
"recommendations": [
|
"recommendations": [
|
||||||
"DavidAnson.vscode-markdownlint", // markdown linting
|
|
||||||
"esbenp.prettier-vscode", // prettier plugin
|
|
||||||
"dbaeumer.vscode-eslint", // eslint plugin
|
|
||||||
"bradlc.vscode-tailwindcss", // hinting / autocompletion for tailwind
|
"bradlc.vscode-tailwindcss", // hinting / autocompletion for tailwind
|
||||||
"ban.spellright", // Spell check for docs
|
"ban.spellright", // Spell check for docs
|
||||||
"stripe.vscode-stripe", // stripe VSCode extension
|
|
||||||
"rebornix.project-snippets", // Share useful snippets between collaborators
|
|
||||||
"inlang.vs-code-extension",
|
|
||||||
"biomejs.biome" // improved i18n DX
|
"biomejs.biome" // improved i18n DX
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,18 +2,15 @@
|
|||||||
"typescript.tsdk": "node_modules/typescript/lib",
|
"typescript.tsdk": "node_modules/typescript/lib",
|
||||||
"editor.formatOnSave": true,
|
"editor.formatOnSave": true,
|
||||||
"editor.codeActionsOnSave": {
|
"editor.codeActionsOnSave": {
|
||||||
"quickfix.biome": "explicit",
|
"quickfix.biome": "always"
|
||||||
"source.organizeImports.biome": "explicit"
|
// "source.organizeImports.biome": "explicit"
|
||||||
},
|
},
|
||||||
"typescript.preferences.importModuleSpecifier": "non-relative",
|
"typescript.preferences.importModuleSpecifier": "non-relative",
|
||||||
"spellright.language": ["en"],
|
"spellright.language": ["en"],
|
||||||
"spellright.documentTypes": ["markdown", "typescript", "typescriptreact"],
|
"spellright.documentTypes": ["markdown", "typescript", "typescriptreact"],
|
||||||
"tailwindCSS.experimental.classRegex": [
|
"tailwindCSS.experimental.classRegex": [
|
||||||
[
|
["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]
|
||||||
"cva\\(([^)]*)\\)",
|
]
|
||||||
"[\"'`]([^\"'`]*).*?[\"'`]"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
// "eslint.workingDirectories": [
|
// "eslint.workingDirectories": [
|
||||||
// { "mode": "auto" }
|
// { "mode": "auto" }
|
||||||
// ],
|
// ],
|
||||||
|
|||||||
@@ -75,10 +75,11 @@ Major areas
|
|||||||
3. `bun i`
|
3. `bun i`
|
||||||
4. Start docker
|
4. Start docker
|
||||||
5. `cp .env.example .env.local`
|
5. `cp .env.example .env.local`
|
||||||
6. Repace `JWT_SECRET` with `openssl rand -hex 32`
|
6. Replace `JWT_SECRET` with `openssl rand -hex 32`
|
||||||
7. Get a local clerk dev key for `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY`
|
7. Get a local clerk dev key for `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY`
|
||||||
8. Keep a terminal live for `bun run db-dev`
|
8. Keep a terminal live for `bun run db-dev`
|
||||||
9. Finally start the next server with `bun dev`
|
9. Execute the local migration to create the initial data `bun run migrate-local`
|
||||||
|
10. Finally start the next server with `bun dev`
|
||||||
|
|
||||||
**Schema Changes**
|
**Schema Changes**
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://biomejs.dev/schemas/1.5.2/schema.json",
|
"$schema": "./web/node_modules/@biomejs/biome/configuration_schema.json",
|
||||||
"organizeImports": {
|
"organizeImports": {
|
||||||
"enabled": true
|
"enabled": true
|
||||||
},
|
},
|
||||||
|
"formatter": {
|
||||||
|
"indentStyle": "space",
|
||||||
|
"indentWidth": 2,
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
"linter": {
|
"linter": {
|
||||||
"enabled": true,
|
"enabled": false,
|
||||||
"rules": {
|
"rules": {
|
||||||
"recommended": true
|
"recommended": true
|
||||||
}
|
}
|
||||||
@@ -312,7 +312,8 @@ async def build_logic(item: Item):
|
|||||||
config = {
|
config = {
|
||||||
"name": item.name,
|
"name": item.name,
|
||||||
"deploy_test": os.environ.get("DEPLOY_TEST_FLAG", "False"),
|
"deploy_test": os.environ.get("DEPLOY_TEST_FLAG", "False"),
|
||||||
"gpu": item.gpu
|
"gpu": item.gpu,
|
||||||
|
"civitai_token": os.environ.get("CIVITAI_TOKEN", "")
|
||||||
}
|
}
|
||||||
with open(f"{folder_path}/config.py", "w") as f:
|
with open(f"{folder_path}/config.py", "w") as f:
|
||||||
f.write("config = " + json.dumps(config))
|
f.write("config = " + json.dumps(config))
|
||||||
|
|||||||
@@ -36,6 +36,9 @@ if not deploy_test:
|
|||||||
|
|
||||||
dockerfile_image = (
|
dockerfile_image = (
|
||||||
modal.Image.debian_slim()
|
modal.Image.debian_slim()
|
||||||
|
.env({
|
||||||
|
"CIVITAI_TOKEN": config["civitai_token"],
|
||||||
|
})
|
||||||
.apt_install("git", "wget")
|
.apt_install("git", "wget")
|
||||||
.pip_install(
|
.pip_install(
|
||||||
"git+https://github.com/modal-labs/asgiproxy.git", "httpx", "tqdm"
|
"git+https://github.com/modal-labs/asgiproxy.git", "httpx", "tqdm"
|
||||||
@@ -231,7 +234,8 @@ def run(input: Input):
|
|||||||
async def bar(request_input: RequestInput):
|
async def bar(request_input: RequestInput):
|
||||||
# print(request_input)
|
# print(request_input)
|
||||||
if not deploy_test:
|
if not deploy_test:
|
||||||
return run.remote(request_input.input)
|
run.spawn(request_input.input)
|
||||||
|
return {"status": "success"}
|
||||||
# pass
|
# pass
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -49,6 +49,12 @@ with open('models.json') as f:
|
|||||||
models = json.load(f)
|
models = json.load(f)
|
||||||
|
|
||||||
for model in models:
|
for model in models:
|
||||||
|
import os
|
||||||
|
if "civitai.com/api" in model['url'] and not "token=" in model['url']:
|
||||||
|
if "?" in model['url']:
|
||||||
|
model['url'] += "&token=" + os.environ.get('CIVITAI_TOKEN', '')
|
||||||
|
else:
|
||||||
|
model['url'] += "?token=" + os.environ.get('CIVITAI_TOKEN', '')
|
||||||
response = requests.request("POST", f"{root_url}/model/install", json=model, headers=headers)
|
response = requests.request("POST", f"{root_url}/model/install", json=model, headers=headers)
|
||||||
print(response.text)
|
print(response.text)
|
||||||
|
|
||||||
|
|||||||
@@ -3,20 +3,20 @@ from PIL import Image, ImageOps
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
import folder_paths
|
import folder_paths
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
class ComfyUIDeployExternalCheckpoint:
|
||||||
class ComfyUIDeployExternalCheckpoints:
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
return {
|
return {
|
||||||
"required": {
|
"required": {
|
||||||
"input_id": (
|
"input_id": (
|
||||||
"STRING",
|
"STRING",
|
||||||
{"multiline": False, "default": "input_checkpoints"},
|
{"multiline": False, "default": "input_checkpoint"},
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
"optional": {
|
"optional": {
|
||||||
"default_checkpoints_name": (folder_paths.get_filename_list("checkpoints"), ),
|
"default_checkpoint_name": (folder_paths.get_filename_list("checkpoints"), ),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ class ComfyUIDeployExternalCheckpoints:
|
|||||||
|
|
||||||
CATEGORY = "deploy"
|
CATEGORY = "deploy"
|
||||||
|
|
||||||
def run(self, input_id, default_checkpoints_name=None):
|
def run(self, input_id, default_checkpoint_name=None):
|
||||||
import requests
|
import requests
|
||||||
import os
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
@@ -39,18 +39,30 @@ class ComfyUIDeployExternalCheckpoints:
|
|||||||
destination_path = os.path.join(
|
destination_path = os.path.join(
|
||||||
folder_paths.folder_names_and_paths["checkpoints"][0][0], unique_filename)
|
folder_paths.folder_names_and_paths["checkpoints"][0][0], unique_filename)
|
||||||
print(destination_path)
|
print(destination_path)
|
||||||
print("Downloading external checkpoints - " +
|
print("Downloading external checkpoint - " +
|
||||||
input_id + " to " + destination_path)
|
input_id + " to " + destination_path)
|
||||||
response = requests.get(
|
response = requests.get(
|
||||||
input_id, headers={'User-Agent': 'Mozilla/5.0'}, allow_redirects=True)
|
input_id, headers={'User-Agent': 'Mozilla/5.0'}, allow_redirects=True, stream=True)
|
||||||
|
file_size = int(response.headers.get('Content-Length', 0))
|
||||||
|
chunk = 1
|
||||||
|
chunk_size = 1024
|
||||||
|
num_bars = int(file_size / chunk_size)
|
||||||
|
|
||||||
with open(destination_path, 'wb') as out_file:
|
with open(destination_path, 'wb') as out_file:
|
||||||
out_file.write(response.content)
|
for chunk in tqdm(
|
||||||
|
response.iter_content(chunk_size=chunk_size),
|
||||||
|
total=num_bars,
|
||||||
|
unit='KB',
|
||||||
|
desc="Downloading",
|
||||||
|
leave=True # leave=True to keep progress bars
|
||||||
|
):
|
||||||
|
out_file.write(chunk)
|
||||||
return (unique_filename,)
|
return (unique_filename,)
|
||||||
else:
|
else:
|
||||||
return (default_checkpoints_name,)
|
return (default_checkpoints_name,)
|
||||||
|
|
||||||
|
|
||||||
NODE_CLASS_MAPPINGS = {
|
NODE_CLASS_MAPPINGS = {
|
||||||
"ComfyUIDeployExternalCheckpoints": ComfyUIDeployExternalCheckpoints}
|
"ComfyUIDeployExternalCheckpoint": ComfyUIDeployExternalCheckpoint}
|
||||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||||
"ComfyUIDeployExternalCheckpoints": "External Checkpoints (ComfyUI Deploy)"}
|
"ComfyUIDeployExternalCheckpoint": "External Checkpoint (ComfyUI Deploy)"}
|
||||||
|
|||||||
@@ -29,9 +29,7 @@ class ComfyUIDeployExternalText:
|
|||||||
CATEGORY = "text"
|
CATEGORY = "text"
|
||||||
|
|
||||||
def run(self, input_id, default_value=None):
|
def run(self, input_id, default_value=None):
|
||||||
if not input_id or len(input_id.strip()) == 0:
|
return [default_value]
|
||||||
return [default_value]
|
|
||||||
return [input_id]
|
|
||||||
|
|
||||||
|
|
||||||
NODE_CLASS_MAPPINGS = {"ComfyUIDeployExternalText": ComfyUIDeployExternalText}
|
NODE_CLASS_MAPPINGS = {"ComfyUIDeployExternalText": ComfyUIDeployExternalText}
|
||||||
|
|||||||
@@ -22,10 +22,14 @@ from logging.handlers import RotatingFileHandler
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
import threading
|
import threading
|
||||||
|
import hashlib
|
||||||
|
import aiohttp
|
||||||
|
|
||||||
api = None
|
api = None
|
||||||
api_task = None
|
api_task = None
|
||||||
prompt_metadata = {}
|
prompt_metadata = {}
|
||||||
|
cd_enable_log = os.environ.get('CD_ENABLE_LOG', 'false').lower() == 'true'
|
||||||
|
cd_enable_run_log = os.environ.get('CD_ENABLE_RUN_LOG', 'false').lower() == 'true'
|
||||||
|
|
||||||
def post_prompt(json_data):
|
def post_prompt(json_data):
|
||||||
prompt_server = server.PromptServer.instance
|
prompt_server = server.PromptServer.instance
|
||||||
@@ -97,6 +101,7 @@ async def comfy_deploy_run(request):
|
|||||||
prompt_metadata[prompt_id] = {
|
prompt_metadata[prompt_id] = {
|
||||||
'status_endpoint': data.get('status_endpoint'),
|
'status_endpoint': data.get('status_endpoint'),
|
||||||
'file_upload_endpoint': data.get('file_upload_endpoint'),
|
'file_upload_endpoint': data.get('file_upload_endpoint'),
|
||||||
|
'workflow_api': workflow_api
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -113,6 +118,8 @@ async def comfy_deploy_run(request):
|
|||||||
"stack_trace": stack_trace
|
"stack_trace": stack_trace
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
# When there are critical errors, the prompt is actually not run
|
||||||
|
await update_run(prompt_id, Status.FAILED)
|
||||||
return web.Response(status=500, reason=f"{error_type}: {e}, {stack_trace_short}")
|
return web.Response(status=500, reason=f"{error_type}: {e}, {stack_trace_short}")
|
||||||
|
|
||||||
status = 200
|
status = 200
|
||||||
@@ -141,6 +148,138 @@ async def comfy_deploy_run(request):
|
|||||||
|
|
||||||
sockets = dict()
|
sockets = dict()
|
||||||
|
|
||||||
|
def get_comfyui_path_from_file_path(file_path):
|
||||||
|
file_path_parts = file_path.split("\\")
|
||||||
|
|
||||||
|
if file_path_parts[0] == "input":
|
||||||
|
print("matching input")
|
||||||
|
file_path = os.path.join(folder_paths.get_directory_by_type("input"), *file_path_parts[1:])
|
||||||
|
elif file_path_parts[0] == "models":
|
||||||
|
print("matching models")
|
||||||
|
file_path = folder_paths.get_full_path(file_path_parts[1], os.path.join(*file_path_parts[2:]))
|
||||||
|
|
||||||
|
print(file_path)
|
||||||
|
|
||||||
|
return file_path
|
||||||
|
|
||||||
|
# Form ComfyUI Manager
|
||||||
|
def compute_sha256_checksum(filepath):
|
||||||
|
filepath = get_comfyui_path_from_file_path(filepath)
|
||||||
|
"""Compute the SHA256 checksum of a file, in chunks"""
|
||||||
|
sha256 = hashlib.sha256()
|
||||||
|
with open(filepath, 'rb') as f:
|
||||||
|
for chunk in iter(lambda: f.read(4096), b''):
|
||||||
|
sha256.update(chunk)
|
||||||
|
return sha256.hexdigest()
|
||||||
|
|
||||||
|
# This is start uploading the files to Comfy Deploy
|
||||||
|
@server.PromptServer.instance.routes.post('/comfyui-deploy/upload-file')
|
||||||
|
async def upload_file(request):
|
||||||
|
data = await request.json()
|
||||||
|
|
||||||
|
file_path = data.get("file_path")
|
||||||
|
|
||||||
|
print("Original file path", file_path)
|
||||||
|
|
||||||
|
file_path = get_comfyui_path_from_file_path(file_path)
|
||||||
|
|
||||||
|
# return web.json_response({
|
||||||
|
# "error": f"File not uploaded"
|
||||||
|
# }, status=500)
|
||||||
|
|
||||||
|
token = data.get("token")
|
||||||
|
get_url = data.get("url")
|
||||||
|
|
||||||
|
try:
|
||||||
|
base = folder_paths.base_path
|
||||||
|
file_path = os.path.join(base, file_path)
|
||||||
|
|
||||||
|
if os.path.exists(file_path):
|
||||||
|
file_size = os.path.getsize(file_path)
|
||||||
|
file_extension = os.path.splitext(file_path)[1]
|
||||||
|
|
||||||
|
if file_extension in ['.jpg', '.jpeg']:
|
||||||
|
file_type = 'image/jpeg'
|
||||||
|
elif file_extension == '.png':
|
||||||
|
file_type = 'image/png'
|
||||||
|
elif file_extension == '.webp':
|
||||||
|
file_type = 'image/webp'
|
||||||
|
else:
|
||||||
|
file_type = 'application/octet-stream' # Default to binary file type if unknown
|
||||||
|
else:
|
||||||
|
return web.json_response({
|
||||||
|
"error": f"File not found: {file_path}"
|
||||||
|
}, status=404)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return web.json_response({
|
||||||
|
"error": str(e)
|
||||||
|
}, status=500)
|
||||||
|
|
||||||
|
if get_url:
|
||||||
|
try:
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
headers = {'Authorization': f'Bearer {token}'}
|
||||||
|
params = {'file_size': file_size, 'type': file_type}
|
||||||
|
async with session.get(get_url, params=params, headers=headers) as response:
|
||||||
|
if response.status == 200:
|
||||||
|
content = await response.json()
|
||||||
|
upload_url = content["upload_url"]
|
||||||
|
|
||||||
|
with open(file_path, 'rb') as f:
|
||||||
|
headers = {
|
||||||
|
"Content-Type": file_type,
|
||||||
|
"x-amz-acl": "public-read",
|
||||||
|
"Content-Length": str(file_size)
|
||||||
|
}
|
||||||
|
async with session.put(upload_url, data=f, headers=headers) as upload_response:
|
||||||
|
if upload_response.status == 200:
|
||||||
|
return web.json_response({
|
||||||
|
"message": "File uploaded successfully",
|
||||||
|
"download_url": content["download_url"]
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
return web.json_response({
|
||||||
|
"error": f"Failed to upload file to {upload_url}. Status code: {upload_response.status}"
|
||||||
|
}, status=upload_response.status)
|
||||||
|
else:
|
||||||
|
return web.json_response({
|
||||||
|
"error": f"Failed to fetch data from {get_url}. Status code: {response.status}"
|
||||||
|
}, status=response.status)
|
||||||
|
except Exception as e:
|
||||||
|
return web.json_response({
|
||||||
|
"error": f"An error occurred while fetching data from {get_url}: {str(e)}"
|
||||||
|
}, status=500)
|
||||||
|
|
||||||
|
return web.json_response({
|
||||||
|
"error": f"File not uploaded"
|
||||||
|
}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@server.PromptServer.instance.routes.get('/comfyui-deploy/get-file-hash')
|
||||||
|
async def get_file_hash(request):
|
||||||
|
file_path = request.rel_url.query.get('file_path', '')
|
||||||
|
|
||||||
|
if file_path is None:
|
||||||
|
return web.json_response({
|
||||||
|
"error": "file_path is required"
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
try:
|
||||||
|
base = folder_paths.base_path
|
||||||
|
file_path = os.path.join(base, file_path)
|
||||||
|
# print("file_path", file_path)
|
||||||
|
file_hash = compute_sha256_checksum(
|
||||||
|
file_path
|
||||||
|
)
|
||||||
|
return web.json_response({
|
||||||
|
"file_hash": file_hash
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
return web.json_response({
|
||||||
|
"error": str(e)
|
||||||
|
}, status=500)
|
||||||
|
|
||||||
@server.PromptServer.instance.routes.get('/comfyui-deploy/ws')
|
@server.PromptServer.instance.routes.get('/comfyui-deploy/ws')
|
||||||
async def websocket_handler(request):
|
async def websocket_handler(request):
|
||||||
ws = web.WebSocketResponse()
|
ws = web.WebSocketResponse()
|
||||||
@@ -157,7 +296,9 @@ async def websocket_handler(request):
|
|||||||
try:
|
try:
|
||||||
# Send initial state to the new client
|
# Send initial state to the new client
|
||||||
await send("status", { 'sid': sid }, sid)
|
await send("status", { 'sid': sid }, sid)
|
||||||
await send_first_time_log(sid)
|
|
||||||
|
if cd_enable_log:
|
||||||
|
await send_first_time_log(sid)
|
||||||
|
|
||||||
async for msg in ws:
|
async for msg in ws:
|
||||||
if msg.type == aiohttp.WSMsgType.ERROR:
|
if msg.type == aiohttp.WSMsgType.ERROR:
|
||||||
@@ -203,7 +344,10 @@ async def send_json_override(self, event, data, sid=None):
|
|||||||
prompt_id = data.get('prompt_id')
|
prompt_id = data.get('prompt_id')
|
||||||
|
|
||||||
# now we send everything
|
# now we send everything
|
||||||
await asyncio.wait([send(event, data), self.send_json_original(event, data, sid)])
|
await asyncio.wait([
|
||||||
|
asyncio.create_task(send(event, data)),
|
||||||
|
asyncio.create_task(self.send_json_original(event, data, sid))
|
||||||
|
])
|
||||||
|
|
||||||
if event == 'execution_start':
|
if event == 'execution_start':
|
||||||
update_run(prompt_id, Status.RUNNING)
|
update_run(prompt_id, Status.RUNNING)
|
||||||
@@ -214,6 +358,34 @@ async def send_json_override(self, event, data, sid=None):
|
|||||||
if not have_pending_upload(prompt_id):
|
if not have_pending_upload(prompt_id):
|
||||||
update_run(prompt_id, Status.SUCCESS)
|
update_run(prompt_id, Status.SUCCESS)
|
||||||
|
|
||||||
|
if event == 'executing' and data.get('node') is not None:
|
||||||
|
node = data.get('node')
|
||||||
|
|
||||||
|
if prompt_id in prompt_metadata:
|
||||||
|
if 'progress' not in prompt_metadata[prompt_id]:
|
||||||
|
prompt_metadata[prompt_id]["progress"] = set()
|
||||||
|
|
||||||
|
prompt_metadata[prompt_id]["progress"].add(node)
|
||||||
|
calculated_progress = len(prompt_metadata[prompt_id]["progress"]) / len(prompt_metadata[prompt_id]['workflow_api'])
|
||||||
|
# print("calculated_progress", calculated_progress)
|
||||||
|
|
||||||
|
if 'last_updated_node' in prompt_metadata[prompt_id] and prompt_metadata[prompt_id]['last_updated_node'] == node:
|
||||||
|
return
|
||||||
|
prompt_metadata[prompt_id]['last_updated_node'] = node
|
||||||
|
class_type = prompt_metadata[prompt_id]['workflow_api'][node]['class_type']
|
||||||
|
print("updating run live status", class_type)
|
||||||
|
await update_run_live_status(prompt_id, "Executing " + class_type, calculated_progress)
|
||||||
|
|
||||||
|
if event == 'execution_cached' and data.get('nodes') is not None:
|
||||||
|
if prompt_id in prompt_metadata:
|
||||||
|
if 'progress' not in prompt_metadata[prompt_id]:
|
||||||
|
prompt_metadata[prompt_id]["progress"] = set()
|
||||||
|
|
||||||
|
if 'nodes' in data:
|
||||||
|
for node in data.get('nodes', []):
|
||||||
|
prompt_metadata[prompt_id]["progress"].add(node)
|
||||||
|
# prompt_metadata[prompt_id]["progress"].update(data.get('nodes'))
|
||||||
|
|
||||||
if event == 'execution_error':
|
if event == 'execution_error':
|
||||||
# Careful this might not be fully awaited.
|
# Careful this might not be fully awaited.
|
||||||
await update_run_with_output(prompt_id, data)
|
await update_run_with_output(prompt_id, data)
|
||||||
@@ -233,7 +405,30 @@ class Status(Enum):
|
|||||||
FAILED = "failed"
|
FAILED = "failed"
|
||||||
UPLOADING = "uploading"
|
UPLOADING = "uploading"
|
||||||
|
|
||||||
|
# Global variable to keep track of the last read line number
|
||||||
|
last_read_line_number = 0
|
||||||
|
|
||||||
|
async def update_run_live_status(prompt_id, live_status, calculated_progress: float):
|
||||||
|
if prompt_id not in prompt_metadata:
|
||||||
|
return
|
||||||
|
|
||||||
|
print("progress", calculated_progress)
|
||||||
|
|
||||||
|
status_endpoint = prompt_metadata[prompt_id]['status_endpoint']
|
||||||
|
body = {
|
||||||
|
"run_id": prompt_id,
|
||||||
|
"live_status": live_status,
|
||||||
|
"progress": calculated_progress
|
||||||
|
}
|
||||||
|
# requests.post(status_endpoint, json=body)
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.post(status_endpoint, json=body) as response:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def update_run(prompt_id, status: Status):
|
def update_run(prompt_id, status: Status):
|
||||||
|
global last_read_line_number
|
||||||
|
|
||||||
if prompt_id not in prompt_metadata:
|
if prompt_id not in prompt_metadata:
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -248,16 +443,50 @@ def update_run(prompt_id, status: Status):
|
|||||||
"run_id": prompt_id,
|
"run_id": prompt_id,
|
||||||
"status": status.value,
|
"status": status.value,
|
||||||
}
|
}
|
||||||
prompt_metadata[prompt_id]['status'] = status
|
|
||||||
print(f"Status: {status.value}")
|
print(f"Status: {status.value}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
requests.post(status_endpoint, json=body)
|
requests.post(status_endpoint, json=body)
|
||||||
|
|
||||||
|
if cd_enable_run_log and (status == Status.SUCCESS or status == Status.FAILED):
|
||||||
|
try:
|
||||||
|
with open(comfyui_file_path, 'r') as log_file:
|
||||||
|
# log_data = log_file.read()
|
||||||
|
# Move to the last read line
|
||||||
|
all_log_data = log_file.read() # Read all log data
|
||||||
|
print("All log data before skipping:", all_log_data) # Log all data before skipping
|
||||||
|
log_file.seek(0) # Reset file pointer to the beginning
|
||||||
|
|
||||||
|
for _ in range(last_read_line_number):
|
||||||
|
next(log_file)
|
||||||
|
log_data = log_file.read()
|
||||||
|
# Update the last read line number
|
||||||
|
last_read_line_number += log_data.count('\n')
|
||||||
|
print("last_read_line_number", last_read_line_number)
|
||||||
|
print("log_data", log_data)
|
||||||
|
print("log_data.count(n)", log_data.count('\n'))
|
||||||
|
|
||||||
|
body = {
|
||||||
|
"run_id": prompt_id,
|
||||||
|
"log_data": [
|
||||||
|
{
|
||||||
|
"logs": log_data,
|
||||||
|
# "timestamp": time.time(),
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
requests.post(status_endpoint, json=body)
|
||||||
|
except Exception as log_error:
|
||||||
|
print(f"Error reading log file: {log_error}")
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
error_type = type(e).__name__
|
error_type = type(e).__name__
|
||||||
stack_trace = traceback.format_exc().strip()
|
stack_trace = traceback.format_exc().strip()
|
||||||
print(f"Error occurred while updating run: {e} {stack_trace}")
|
print(f"Error occurred while updating run: {e} {stack_trace}")
|
||||||
|
finally:
|
||||||
|
prompt_metadata[prompt_id]['status'] = status
|
||||||
|
|
||||||
|
|
||||||
async def upload_file(prompt_id, filename, subfolder=None, content_type="image/png", type="output"):
|
async def upload_file(prompt_id, filename, subfolder=None, content_type="image/png", type="output"):
|
||||||
"""
|
"""
|
||||||
@@ -307,7 +536,9 @@ async def upload_file(prompt_id, filename, subfolder=None, content_type="image/p
|
|||||||
"Content-Length": str(len(data)),
|
"Content-Length": str(len(data)),
|
||||||
}
|
}
|
||||||
response = requests.put(ok.get("url"), headers=headers, data=data)
|
response = requests.put(ok.get("url"), headers=headers, data=data)
|
||||||
print("upload file response", response.status_code)
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.put(ok.get("url"), headers=headers, data=data) as response:
|
||||||
|
print("upload file response", response.status)
|
||||||
|
|
||||||
def have_pending_upload(prompt_id):
|
def have_pending_upload(prompt_id):
|
||||||
if 'prompt_id' in prompt_metadata and 'uploading_nodes' in prompt_metadata[prompt_id] and len(prompt_metadata[prompt_id]['uploading_nodes']) > 0:
|
if 'prompt_id' in prompt_metadata and 'uploading_nodes' in prompt_metadata[prompt_id] and len(prompt_metadata[prompt_id]['uploading_nodes']) > 0:
|
||||||
@@ -384,20 +615,25 @@ async def update_file_status(prompt_id, data, uploading, have_error=False, node_
|
|||||||
"prompt_id": prompt_id,
|
"prompt_id": prompt_id,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
async def handle_upload(prompt_id, data, key, content_type_key, default_content_type):
|
||||||
|
items = data.get(key, [])
|
||||||
|
for item in items:
|
||||||
|
await upload_file(
|
||||||
|
prompt_id,
|
||||||
|
item.get("filename"),
|
||||||
|
subfolder=item.get("subfolder"),
|
||||||
|
type=item.get("type"),
|
||||||
|
content_type=item.get(content_type_key, default_content_type)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Upload files in the background
|
# Upload files in the background
|
||||||
async def upload_in_background(prompt_id, data, node_id=None, have_upload=True):
|
async def upload_in_background(prompt_id, data, node_id=None, have_upload=True):
|
||||||
try:
|
try:
|
||||||
images = data.get('images', [])
|
await handle_upload(prompt_id, data, 'images', "content_type", "image/png")
|
||||||
for image in images:
|
await handle_upload(prompt_id, data, 'files', "content_type", "image/png")
|
||||||
await upload_file(prompt_id, image.get("filename"), subfolder=image.get("subfolder"), type=image.get("type"), content_type=image.get("content_type", "image/png"))
|
# This will also be mp4
|
||||||
|
await handle_upload(prompt_id, data, 'gifs', "format", "image/gif")
|
||||||
files = data.get('files', [])
|
|
||||||
for file in files:
|
|
||||||
await upload_file(prompt_id, file.get("filename"), subfolder=file.get("subfolder"), type=file.get("type"), content_type=file.get("content_type", "image/png"))
|
|
||||||
|
|
||||||
gifs = data.get('gifs', [])
|
|
||||||
for gif in gifs:
|
|
||||||
await upload_file(prompt_id, gif.get("filename"), subfolder=gif.get("subfolder"), type=gif.get("type"), content_type=gif.get("format", "image/gif"))
|
|
||||||
|
|
||||||
if have_upload:
|
if have_upload:
|
||||||
await update_file_status(prompt_id, data, False, node_id=node_id)
|
await update_file_status(prompt_id, data, False, node_id=node_id)
|
||||||
@@ -438,6 +674,7 @@ prompt_server.send_json = send_json_override.__get__(prompt_server, server.Promp
|
|||||||
root_path = os.path.dirname(os.path.abspath(__file__))
|
root_path = os.path.dirname(os.path.abspath(__file__))
|
||||||
two_dirs_up = os.path.dirname(os.path.dirname(root_path))
|
two_dirs_up = os.path.dirname(os.path.dirname(root_path))
|
||||||
log_file_path = os.path.join(two_dirs_up, 'comfy-deploy.log')
|
log_file_path = os.path.join(two_dirs_up, 'comfy-deploy.log')
|
||||||
|
comfyui_file_path = os.path.join(two_dirs_up, 'comfyui.log')
|
||||||
|
|
||||||
last_read_line = 0
|
last_read_line = 0
|
||||||
|
|
||||||
@@ -477,4 +714,5 @@ def run_in_new_thread(coroutine):
|
|||||||
t.start()
|
t.start()
|
||||||
asyncio.run_coroutine_threadsafe(coroutine, new_loop)
|
asyncio.run_coroutine_threadsafe(coroutine, new_loop)
|
||||||
|
|
||||||
run_in_new_thread(watch_file_changes(log_file_path, send_logs_to_websocket))
|
if cd_enable_log:
|
||||||
|
run_in_new_thread(watch_file_changes(log_file_path, send_logs_to_websocket))
|
||||||
|
|||||||
@@ -7,45 +7,56 @@ import threading
|
|||||||
import logging
|
import logging
|
||||||
from logging.handlers import RotatingFileHandler
|
from logging.handlers import RotatingFileHandler
|
||||||
|
|
||||||
handler = RotatingFileHandler('comfy-deploy.log', maxBytes=500000, backupCount=5)
|
# Running with export CD_ENABLE_LOG=true; python main.py
|
||||||
|
|
||||||
original_stdout = sys.stdout
|
# Check for 'cd-enable-log' flag in input arguments
|
||||||
original_stderr = sys.stderr
|
# cd_enable_log = '--cd-enable-log' in sys.argv
|
||||||
|
cd_enable_log = os.environ.get('CD_ENABLE_LOG', 'false').lower() == 'true'
|
||||||
|
|
||||||
class StreamToLogger():
|
def setup():
|
||||||
def __init__(self, log_level):
|
handler = RotatingFileHandler('comfy-deploy.log', maxBytes=500000, backupCount=5)
|
||||||
self.log_level = log_level
|
|
||||||
|
|
||||||
def write(self, buf):
|
original_stdout = sys.stdout
|
||||||
if (self.log_level == logging.INFO):
|
original_stderr = sys.stderr
|
||||||
original_stdout.write(buf)
|
|
||||||
original_stdout.flush()
|
|
||||||
elif (self.log_level == logging.ERROR):
|
|
||||||
original_stderr.write(buf)
|
|
||||||
original_stderr.flush()
|
|
||||||
|
|
||||||
for line in buf.rstrip().splitlines():
|
class StreamToLogger():
|
||||||
handler.handle(
|
def __init__(self, log_level):
|
||||||
logging.LogRecord(
|
self.log_level = log_level
|
||||||
name="comfy-deploy",
|
|
||||||
level=self.log_level,
|
def write(self, buf):
|
||||||
pathname="prestartup_script.py",
|
if (self.log_level == logging.INFO):
|
||||||
lineno=1,
|
original_stdout.write(buf)
|
||||||
msg=line.rstrip(),
|
original_stdout.flush()
|
||||||
args=None,
|
elif (self.log_level == logging.ERROR):
|
||||||
exc_info=None
|
original_stderr.write(buf)
|
||||||
|
original_stderr.flush()
|
||||||
|
|
||||||
|
for line in buf.rstrip().splitlines():
|
||||||
|
handler.handle(
|
||||||
|
logging.LogRecord(
|
||||||
|
name="comfy-deploy",
|
||||||
|
level=self.log_level,
|
||||||
|
pathname="prestartup_script.py",
|
||||||
|
lineno=1,
|
||||||
|
msg=line.rstrip(),
|
||||||
|
args=None,
|
||||||
|
exc_info=None
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
|
||||||
|
|
||||||
def flush(self):
|
def flush(self):
|
||||||
if (self.log_level == logging.INFO):
|
if (self.log_level == logging.INFO):
|
||||||
original_stdout.flush()
|
original_stdout.flush()
|
||||||
elif (self.log_level == logging.ERROR):
|
elif (self.log_level == logging.ERROR):
|
||||||
original_stderr.flush()
|
original_stderr.flush()
|
||||||
|
|
||||||
# Redirect stdout and stderr to the logger
|
# Redirect stdout and stderr to the logger
|
||||||
sys.stdout = StreamToLogger(logging.INFO)
|
sys.stdout = StreamToLogger(logging.INFO)
|
||||||
sys.stderr = StreamToLogger(logging.ERROR)
|
sys.stderr = StreamToLogger(logging.ERROR)
|
||||||
|
|
||||||
|
if cd_enable_log:
|
||||||
|
print("** Comfy Deploy logging enabled")
|
||||||
|
setup()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Get the absolute path of the script's directory
|
# Get the absolute path of the script's directory
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { app } from "./app.js";
|
import { app } from "./app.js";
|
||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
import { ComfyWidgets, LGraphNode } from "./widgets.js";
|
import { ComfyWidgets, LGraphNode } from "./widgets.js";
|
||||||
|
import { generateDependencyGraph } from "https://esm.sh/[email protected]";
|
||||||
|
|
||||||
/** @typedef {import('../../../web/types/comfy.js').ComfyExtension} ComfyExtension*/
|
/** @typedef {import('../../../web/types/comfy.js').ComfyExtension} ComfyExtension*/
|
||||||
/** @type {ComfyExtension} */
|
/** @type {ComfyExtension} */
|
||||||
@@ -9,6 +10,76 @@ const ext = {
|
|||||||
|
|
||||||
init(app) {
|
init(app) {
|
||||||
addButton();
|
addButton();
|
||||||
|
|
||||||
|
const queryParams = new URLSearchParams(window.location.search);
|
||||||
|
const workflow_version_id = queryParams.get("workflow_version_id");
|
||||||
|
const auth_token = queryParams.get("auth_token");
|
||||||
|
const org_display = queryParams.get("org_display");
|
||||||
|
const origin = queryParams.get("origin");
|
||||||
|
|
||||||
|
const data = getData();
|
||||||
|
let endpoint = data.endpoint;
|
||||||
|
let apiKey = data.apiKey;
|
||||||
|
|
||||||
|
// If there is auth token override it
|
||||||
|
if (auth_token) {
|
||||||
|
apiKey = auth_token;
|
||||||
|
endpoint = origin;
|
||||||
|
saveData({
|
||||||
|
displayName: org_display,
|
||||||
|
endpoint: origin,
|
||||||
|
apiKey: auth_token,
|
||||||
|
displayName: org_display,
|
||||||
|
environment: "cloud",
|
||||||
|
});
|
||||||
|
localStorage.setItem("comfy_deploy_env", "cloud");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!workflow_version_id) {
|
||||||
|
console.error("No workflow_version_id provided in query parameters.");
|
||||||
|
} else {
|
||||||
|
loadingDialog.showLoading(
|
||||||
|
"Loading workflow from " + org_display,
|
||||||
|
"Please wait...",
|
||||||
|
);
|
||||||
|
fetch(endpoint + "/api/workflow-version/" + workflow_version_id, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + apiKey,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.then(async (res) => {
|
||||||
|
const data = await res.json();
|
||||||
|
const { workflow, workflow_id, error } = data;
|
||||||
|
if (error) {
|
||||||
|
infoDialog.showMessage("Unable to load this workflow", error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adding a delay to wait for the intial graph to load
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
|
|
||||||
|
workflow?.nodes.forEach((x) => {
|
||||||
|
if (x?.type === "ComfyDeploy") {
|
||||||
|
x.widgets_values[1] = workflow_id;
|
||||||
|
// x.widgets_values[2] = workflow_version.version;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** @type {LGraph} */
|
||||||
|
app.loadGraphData(workflow);
|
||||||
|
})
|
||||||
|
.catch((e) => infoDialog.showMessage("Error", e.message))
|
||||||
|
.finally(() => {
|
||||||
|
loadingDialog.close();
|
||||||
|
window.history.replaceState(
|
||||||
|
{},
|
||||||
|
document.title,
|
||||||
|
window.location.pathname,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
registerCustomNodes() {
|
registerCustomNodes() {
|
||||||
@@ -108,6 +179,92 @@ function showError(title, message) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createDynamicUIHtml(data) {
|
||||||
|
console.log(data);
|
||||||
|
let html =
|
||||||
|
'<div style="min-width: 600px; max-width: 1024px; margin: 14px auto; display: flex; flex-direction: column; gap: 24px;">';
|
||||||
|
const bgcolor = "var(--comfy-input-bg)";
|
||||||
|
const evenBg = "var(--border-color)";
|
||||||
|
const textColor = "var(--input-text)";
|
||||||
|
|
||||||
|
// Custom Nodes
|
||||||
|
html += `<div style="background-color: ${bgcolor}; padding: 24px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">`;
|
||||||
|
html +=
|
||||||
|
'<h2 style="margin-top: 0px; font-size: 24px; font-weight: bold; margin-bottom: 16px;">Custom Nodes</h2>';
|
||||||
|
|
||||||
|
if (data.missing_nodes?.length > 0) {
|
||||||
|
html += `
|
||||||
|
<div style="border-bottom: 1px solid #e2e8f0; padding: 4px 12px; background-color: ${evenBg}">
|
||||||
|
<h3 style="font-size: 14px; font-weight: semibold; margin-bottom: 8px;">Missing Nodes</h3>
|
||||||
|
<p style="font-size: 12px;">These nodes are not found with any matching custom_nodes in the ComfyUI Manager Database</p>
|
||||||
|
${data.missing_nodes
|
||||||
|
.map((node) => {
|
||||||
|
return `<p style="font-size: 14px; color: #d69e2e;">${node}</p>`;
|
||||||
|
})
|
||||||
|
.join("")}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.values(data.custom_nodes).forEach((node) => {
|
||||||
|
html += `
|
||||||
|
<div style="border-bottom: 1px solid #e2e8f0; padding-top: 16px;">
|
||||||
|
<a href="${
|
||||||
|
node.url
|
||||||
|
}" target="_blank" style="font-size: 18px; font-weight: semibold; color: white; text-decoration: none;">${
|
||||||
|
node.name
|
||||||
|
}</a>
|
||||||
|
<p style="font-size: 14px; color: #4b5563;">${node.hash}</p>
|
||||||
|
${
|
||||||
|
node.warning
|
||||||
|
? `<p style="font-size: 14px; color: #d69e2e;">${node.warning}</p>`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
html += "</div>";
|
||||||
|
|
||||||
|
// Models
|
||||||
|
html += `<div style="background-color: ${bgcolor}; padding: 24px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">`;
|
||||||
|
html +=
|
||||||
|
'<h2 style="margin-top: 0px; font-size: 24px; font-weight: bold; margin-bottom: 16px;">Models</h2>';
|
||||||
|
|
||||||
|
Object.entries(data.models).forEach(([section, items]) => {
|
||||||
|
html += `
|
||||||
|
<div style="border-bottom: 1px solid #e2e8f0; padding-top: 8px; padding-bottom: 8px;">
|
||||||
|
<h3 style="font-size: 18px; font-weight: semibold; margin-bottom: 8px;">${
|
||||||
|
section.charAt(0).toUpperCase() + section.slice(1)
|
||||||
|
}</h3>`;
|
||||||
|
items.forEach((item) => {
|
||||||
|
html += `<p style="font-size: 14px; color: ${textColor};">${item.name}</p>`;
|
||||||
|
});
|
||||||
|
html += "</div>";
|
||||||
|
});
|
||||||
|
html += "</div>";
|
||||||
|
|
||||||
|
// Models
|
||||||
|
html += `<div style="background-color: ${bgcolor}; padding: 24px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">`;
|
||||||
|
html +=
|
||||||
|
'<h2 style="margin-top: 0px; font-size: 24px; font-weight: bold; margin-bottom: 16px;">Files</h2>';
|
||||||
|
|
||||||
|
Object.entries(data.files).forEach(([section, items]) => {
|
||||||
|
html += `
|
||||||
|
<div style="border-bottom: 1px solid #e2e8f0; padding-top: 8px; padding-bottom: 8px;">
|
||||||
|
<h3 style="font-size: 18px; font-weight: semibold; margin-bottom: 8px;">${
|
||||||
|
section.charAt(0).toUpperCase() + section.slice(1)
|
||||||
|
}</h3>`;
|
||||||
|
items.forEach((item) => {
|
||||||
|
html += `<p style="font-size: 14px; color: ${textColor};">${item.name}</p>`;
|
||||||
|
});
|
||||||
|
html += "</div>";
|
||||||
|
});
|
||||||
|
html += "</div>";
|
||||||
|
|
||||||
|
html += "</div>";
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|
||||||
function addButton() {
|
function addButton() {
|
||||||
const menu = document.querySelector(".comfy-menu");
|
const menu = document.querySelector(".comfy-menu");
|
||||||
|
|
||||||
@@ -119,8 +276,33 @@ function addButton() {
|
|||||||
/** @type {LGraph} */
|
/** @type {LGraph} */
|
||||||
const graph = app.graph;
|
const graph = app.graph;
|
||||||
|
|
||||||
|
let { endpoint, apiKey, displayName } = getData();
|
||||||
|
|
||||||
|
if (!endpoint || !apiKey || apiKey === "" || endpoint === "") {
|
||||||
|
configDialog.show();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = await confirmDialog.confirm(
|
||||||
|
"Confirm deployment -> " +
|
||||||
|
displayName +
|
||||||
|
"<br><br><small><div style='font-weight: normal;'>" +
|
||||||
|
endpoint +
|
||||||
|
"<div><br>",
|
||||||
|
`A new version will be deployed, are you confirm? <br><br><input id="include-deps" type="checkbox" checked>Include dependence</input>`,
|
||||||
|
);
|
||||||
|
if (!ok) return;
|
||||||
|
|
||||||
|
const includeDeps = document.getElementById("include-deps").checked;
|
||||||
|
|
||||||
|
if (endpoint.endsWith("/")) {
|
||||||
|
endpoint = endpoint.slice(0, -1);
|
||||||
|
}
|
||||||
|
loadingDialog.showLoading("Generating snapshot", "Please wait...");
|
||||||
|
|
||||||
const snapshot = await fetch("/snapshot/get_current").then((x) => x.json());
|
const snapshot = await fetch("/snapshot/get_current").then((x) => x.json());
|
||||||
console.log(snapshot);
|
// console.log(snapshot);
|
||||||
|
loadingDialog.close();
|
||||||
|
|
||||||
if (!snapshot) {
|
if (!snapshot) {
|
||||||
showError(
|
showError(
|
||||||
@@ -154,52 +336,122 @@ function addButton() {
|
|||||||
|
|
||||||
const deployMetaNode = deployMeta[0];
|
const deployMetaNode = deployMeta[0];
|
||||||
|
|
||||||
console.log(deployMetaNode);
|
|
||||||
|
|
||||||
const workflow_name = deployMetaNode.widgets[0].value;
|
const workflow_name = deployMetaNode.widgets[0].value;
|
||||||
const workflow_id = deployMetaNode.widgets[1].value;
|
const workflow_id = deployMetaNode.widgets[1].value;
|
||||||
|
|
||||||
console.log(workflow_name, workflow_id);
|
|
||||||
|
|
||||||
const prompt = await app.graphToPrompt();
|
const prompt = await app.graphToPrompt();
|
||||||
console.log(graph);
|
let deps = undefined;
|
||||||
console.log(prompt);
|
|
||||||
|
|
||||||
// const endpoint = localStorage.getItem("endpoint") ?? "";
|
if (includeDeps) {
|
||||||
// const apiKey = localStorage.getItem("apiKey");
|
loadingDialog.showLoading("Fetching existing version", "Please wait...");
|
||||||
|
|
||||||
const { endpoint, apiKey } = getData();
|
const existing_workflow = await fetch(
|
||||||
|
endpoint + "/api/workflow/" + workflow_id,
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + apiKey,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.then((x) => x.json())
|
||||||
|
.catch(() => {
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
|
||||||
if (!endpoint || !apiKey || apiKey === "" || endpoint === "") {
|
loadingDialog.close();
|
||||||
configDialog.show();
|
|
||||||
return;
|
loadingDialog.showLoading(
|
||||||
|
"Generating dependency graph",
|
||||||
|
"Please wait...",
|
||||||
|
);
|
||||||
|
deps = await generateDependencyGraph({
|
||||||
|
workflow_api: prompt.output,
|
||||||
|
snapshot: snapshot,
|
||||||
|
computeFileHash: async (file) => {
|
||||||
|
console.log(file);
|
||||||
|
loadingDialog.showLoading("Generating hash", file);
|
||||||
|
const hash = await fetch(
|
||||||
|
`/comfyui-deploy/get-file-hash?file_path=${encodeURIComponent(
|
||||||
|
file,
|
||||||
|
)}`,
|
||||||
|
).then((x) => x.json());
|
||||||
|
loadingDialog.showLoading("Generating hash", file);
|
||||||
|
console.log(hash);
|
||||||
|
return hash.file_hash;
|
||||||
|
},
|
||||||
|
handleFileUpload: async (file, hash, prevhash) => {
|
||||||
|
console.log("Uploading ", file);
|
||||||
|
loadingDialog.showLoading("Uploading file", file);
|
||||||
|
try {
|
||||||
|
const { download_url } = await fetch(
|
||||||
|
`/comfyui-deploy/upload-file`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
file_path: file,
|
||||||
|
token: apiKey,
|
||||||
|
url: endpoint + "/api/upload-url",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.then((x) => x.json())
|
||||||
|
.catch(() => {
|
||||||
|
loadingDialog.close();
|
||||||
|
confirmDialog.confirm("Error", "Unable to upload file " + file);
|
||||||
|
});
|
||||||
|
loadingDialog.showLoading("Uploaded file", file);
|
||||||
|
console.log(download_url);
|
||||||
|
return download_url;
|
||||||
|
} catch (error) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
existingDependencies: existing_workflow.dependencies,
|
||||||
|
});
|
||||||
|
|
||||||
|
loadingDialog.close();
|
||||||
|
|
||||||
|
const depsOk = await confirmDialog.confirm(
|
||||||
|
"Check dependencies",
|
||||||
|
// JSON.stringify(deps, null, 2),
|
||||||
|
createDynamicUIHtml(deps),
|
||||||
|
);
|
||||||
|
if (!depsOk) return;
|
||||||
|
|
||||||
|
console.log(deps);
|
||||||
}
|
}
|
||||||
|
|
||||||
const ok = await confirmDialog.confirm("Confirm deployment", "A new version will be deployed, are you conform?")
|
loadingDialog.showLoading("Deploying...");
|
||||||
if (!ok) return;
|
|
||||||
|
|
||||||
title.innerText = "Deploying...";
|
title.innerText = "Deploying...";
|
||||||
title.style.color = "orange";
|
title.style.color = "orange";
|
||||||
|
|
||||||
console.log(prompt);
|
// console.log(prompt);
|
||||||
|
|
||||||
// TODO trim the ending / from endpoint is there is
|
// TODO trim the ending / from endpoint is there is
|
||||||
if (endpoint.endsWith("/")) {
|
if (endpoint.endsWith("/")) {
|
||||||
endpoint = endpoint.slice(0, -1);
|
endpoint = endpoint.slice(0, -1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const apiRoute = endpoint + "/api/upload";
|
// console.log(prompt.workflow);
|
||||||
|
|
||||||
|
const apiRoute = endpoint + "/api/workflow";
|
||||||
// const userId = apiKey
|
// const userId = apiKey
|
||||||
try {
|
try {
|
||||||
|
const body = {
|
||||||
|
workflow_name,
|
||||||
|
workflow_id,
|
||||||
|
workflow: prompt.workflow,
|
||||||
|
workflow_api: prompt.output,
|
||||||
|
snapshot: snapshot,
|
||||||
|
dependencies: deps,
|
||||||
|
};
|
||||||
|
console.log(body);
|
||||||
let data = await fetch(apiRoute, {
|
let data = await fetch(apiRoute, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(body),
|
||||||
workflow_name,
|
|
||||||
workflow_id,
|
|
||||||
workflow: prompt.workflow,
|
|
||||||
workflow_api: prompt.output,
|
|
||||||
snapshot: snapshot,
|
|
||||||
}),
|
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
Authorization: "Bearer " + apiKey,
|
Authorization: "Bearer " + apiKey,
|
||||||
@@ -214,6 +466,8 @@ function addButton() {
|
|||||||
data = await data.json();
|
data = await data.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
loadingDialog.close();
|
||||||
|
|
||||||
title.textContent = "Done";
|
title.textContent = "Done";
|
||||||
title.style.color = "green";
|
title.style.color = "green";
|
||||||
|
|
||||||
@@ -230,6 +484,7 @@ function addButton() {
|
|||||||
title.style.color = "white";
|
title.style.color = "white";
|
||||||
}, 1000);
|
}, 1000);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
loadingDialog.close();
|
||||||
app.ui.dialog.show(e);
|
app.ui.dialog.show(e);
|
||||||
console.error(e);
|
console.error(e);
|
||||||
title.textContent = "Error";
|
title.textContent = "Error";
|
||||||
@@ -275,14 +530,16 @@ export class InfoDialog extends ComfyDialog {
|
|||||||
this.element.classList.add("comfy-normal-modal");
|
this.element.classList.add("comfy-normal-modal");
|
||||||
this.element.style.paddingBottom = "20px";
|
this.element.style.paddingBottom = "20px";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
button = undefined;
|
||||||
|
|
||||||
createButtons() {
|
createButtons() {
|
||||||
return [
|
this.button = $el("button", {
|
||||||
$el("button", {
|
type: "button",
|
||||||
type: "button",
|
textContent: "Close",
|
||||||
textContent: "Close",
|
onclick: () => this.close(),
|
||||||
onclick: () => this.close(),
|
});
|
||||||
}),
|
return [this.button];
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
close() {
|
close() {
|
||||||
@@ -301,6 +558,72 @@ export class InfoDialog extends ComfyDialog {
|
|||||||
this.element.style.display = "flex";
|
this.element.style.display = "flex";
|
||||||
this.element.style.zIndex = 1001;
|
this.element.style.zIndex = 1001;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
showMessage(title, message) {
|
||||||
|
this.show(`
|
||||||
|
<div style="width: 100%; max-width: 600px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||||
|
<h3 style="margin: 0px;">${title}</h3>
|
||||||
|
<label>
|
||||||
|
${message}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
loadingIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><g fill="none" stroke="#888888" stroke-linecap="round" stroke-width="2"><path stroke-dasharray="60" stroke-dashoffset="60" stroke-opacity=".3" d="M12 3C16.9706 3 21 7.02944 21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3Z"><animate fill="freeze" attributeName="stroke-dashoffset" dur="1.3s" values="60;0"/></path><path stroke-dasharray="15" stroke-dashoffset="15" d="M12 3C16.9706 3 21 7.02944 21 12"><animate fill="freeze" attributeName="stroke-dashoffset" dur="0.3s" values="15;0"/><animateTransform attributeName="transform" dur="1.5s" repeatCount="indefinite" type="rotate" values="0 12 12;360 12 12"/></path></g></svg>`;
|
||||||
|
|
||||||
|
showLoading(title, message) {
|
||||||
|
this.show(`
|
||||||
|
<div style="width: 400px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||||
|
<h3 style="margin: 0px; display: flex; align-items: center; justify-content: center;">${title} ${this.loadingIcon}</h3>
|
||||||
|
<label>
|
||||||
|
${message}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LoadingDialog extends ComfyDialog {
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
this.element.classList.add("comfy-normal-modal");
|
||||||
|
// this.element.style.paddingBottom = "20px";
|
||||||
|
}
|
||||||
|
|
||||||
|
createButtons() {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
this.element.style.display = "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
show(html) {
|
||||||
|
this.textElement.style["white-space"] = "normal";
|
||||||
|
this.textElement.style.color = "white";
|
||||||
|
this.textElement.style.marginTop = "0px";
|
||||||
|
if (typeof html === "string") {
|
||||||
|
this.textElement.innerHTML = html;
|
||||||
|
} else {
|
||||||
|
this.textElement.replaceChildren(html);
|
||||||
|
}
|
||||||
|
this.element.style.display = "flex";
|
||||||
|
this.element.style.zIndex = 1001;
|
||||||
|
}
|
||||||
|
|
||||||
|
loadingIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><g fill="none" stroke="#888888" stroke-linecap="round" stroke-width="2"><path stroke-dasharray="60" stroke-dashoffset="60" stroke-opacity=".3" d="M12 3C16.9706 3 21 7.02944 21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3Z"><animate fill="freeze" attributeName="stroke-dashoffset" dur="1.3s" values="60;0"/></path><path stroke-dasharray="15" stroke-dashoffset="15" d="M12 3C16.9706 3 21 7.02944 21 12"><animate fill="freeze" attributeName="stroke-dashoffset" dur="0.3s" values="15;0"/><animateTransform attributeName="transform" dur="1.5s" repeatCount="indefinite" type="rotate" values="0 12 12;360 12 12"/></path></g></svg>`;
|
||||||
|
|
||||||
|
showLoading(title, message) {
|
||||||
|
this.show(`
|
||||||
|
<div style="width: 400px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||||
|
<h3 style="margin: 0px; display: flex; align-items: center; justify-content: center; gap: 12px;">${title} ${
|
||||||
|
this.loadingIcon
|
||||||
|
}</h3>
|
||||||
|
${message ? `<label>${message}</label>` : ""}
|
||||||
|
</div>
|
||||||
|
`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class InputDialog extends InfoDialog {
|
export class InputDialog extends InfoDialog {
|
||||||
@@ -367,7 +690,6 @@ export class InputDialog extends InfoDialog {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export class ConfirmDialog extends InfoDialog {
|
export class ConfirmDialog extends InfoDialog {
|
||||||
callback = undefined;
|
callback = undefined;
|
||||||
|
|
||||||
@@ -417,7 +739,7 @@ export class ConfirmDialog extends InfoDialog {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
this.callback = resolve;
|
this.callback = resolve;
|
||||||
this.show(`
|
this.show(`
|
||||||
<div style="width: 400px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
<div style="width: 100%; max-width: 600px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||||
<h3 style="margin: 0px;">${title}</h3>
|
<h3 style="margin: 0px;">${title}</h3>
|
||||||
<label>
|
<label>
|
||||||
${message}
|
${message}
|
||||||
@@ -429,9 +751,15 @@ export class ConfirmDialog extends InfoDialog {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const inputDialog = new InputDialog();
|
export const inputDialog = new InputDialog();
|
||||||
|
export const loadingDialog = new LoadingDialog();
|
||||||
export const infoDialog = new InfoDialog();
|
export const infoDialog = new InfoDialog();
|
||||||
export const confirmDialog = new ConfirmDialog();
|
export const confirmDialog = new ConfirmDialog();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves deployment data from local storage or defaults.
|
||||||
|
* @param {string} [environment] - The environment to get the data for.
|
||||||
|
* @returns {{endpoint: string, apiKey: string, displayName: string, environment?: string}} The deployment data.
|
||||||
|
*/
|
||||||
function getData(environment) {
|
function getData(environment) {
|
||||||
const deployOption =
|
const deployOption =
|
||||||
environment || localStorage.getItem("comfy_deploy_env") || "cloud";
|
environment || localStorage.getItem("comfy_deploy_env") || "cloud";
|
||||||
@@ -454,8 +782,21 @@ function getData(environment) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves deployment data from local storage or defaults.
|
||||||
|
* @param {{endpoint: string, apiKey: string, displayName: string, environment?: string}} [data] - The environment to get the data for.
|
||||||
|
*/
|
||||||
|
function saveData(data) {
|
||||||
|
localStorage.setItem(
|
||||||
|
"comfy_deploy_env_data_" + data.environment,
|
||||||
|
JSON.stringify(data),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export class ConfigDialog extends ComfyDialog {
|
export class ConfigDialog extends ComfyDialog {
|
||||||
container = null;
|
container = null;
|
||||||
|
poll = null;
|
||||||
|
timeout = null;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
@@ -498,22 +839,24 @@ export class ConfigDialog extends ComfyDialog {
|
|||||||
|
|
||||||
close() {
|
close() {
|
||||||
this.element.style.display = "none";
|
this.element.style.display = "none";
|
||||||
|
clearInterval(this.poll);
|
||||||
|
clearTimeout(this.timeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
save() {
|
save(api_key, displayName) {
|
||||||
|
if (!displayName) displayName = getData().displayName;
|
||||||
|
|
||||||
const deployOption = this.container.querySelector("#deployOption").value;
|
const deployOption = this.container.querySelector("#deployOption").value;
|
||||||
localStorage.setItem("comfy_deploy_env", deployOption);
|
localStorage.setItem("comfy_deploy_env", deployOption);
|
||||||
|
|
||||||
const endpoint = this.container.querySelector("#endpoint").value;
|
const endpoint = this.container.querySelector("#endpoint").value;
|
||||||
const apiKey = this.container.querySelector("#apiKey").value;
|
const apiKey = api_key ?? this.container.querySelector("#apiKey").value;
|
||||||
const data = {
|
saveData({
|
||||||
endpoint,
|
endpoint,
|
||||||
apiKey,
|
apiKey,
|
||||||
};
|
displayName,
|
||||||
localStorage.setItem(
|
environment: deployOption,
|
||||||
"comfy_deploy_env_data_" + deployOption,
|
});
|
||||||
JSON.stringify(data),
|
|
||||||
);
|
|
||||||
this.close();
|
this.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,12 +870,8 @@ export class ConfigDialog extends ComfyDialog {
|
|||||||
<h3 style="margin: 0px;">Comfy Deploy Config</h3>
|
<h3 style="margin: 0px;">Comfy Deploy Config</h3>
|
||||||
<label style="color: white; width: 100%;">
|
<label style="color: white; width: 100%;">
|
||||||
<select id="deployOption" style="margin: 8px 0px; width: 100%; height:30px; box-sizing: border-box;" >
|
<select id="deployOption" style="margin: 8px 0px; width: 100%; height:30px; box-sizing: border-box;" >
|
||||||
<option value="cloud" ${
|
<option value="cloud" ${data.environment === "cloud" ? "selected" : ""}>Cloud</option>
|
||||||
data.environment === "cloud" ? "selected" : ""
|
<option value="local" ${data.environment === "local" ? "selected" : ""}>Local</option>
|
||||||
}>Cloud</option>
|
|
||||||
<option value="local" ${
|
|
||||||
data.environment === "local" ? "selected" : ""
|
|
||||||
}>Local</option>
|
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label style="color: white; width: 100%;">
|
<label style="color: white; width: 100%;">
|
||||||
@@ -542,16 +881,61 @@ export class ConfigDialog extends ComfyDialog {
|
|||||||
}">
|
}">
|
||||||
</label>
|
</label>
|
||||||
<label style="color: white;">
|
<label style="color: white;">
|
||||||
API Key:
|
API Key: ${data.displayName ?? ""}
|
||||||
<input id="apiKey" style="margin-top: 8px; width: 100%; height:40px; box-sizing: border-box; padding: 0px 6px;" type="password" value="${
|
<input id="apiKey" style="margin-top: 8px; width: 100%; height:40px; box-sizing: border-box; padding: 0px 6px;" type="password" value="${
|
||||||
data.apiKey
|
data.apiKey
|
||||||
}">
|
}">
|
||||||
|
<button id="loginButton" style="margin-top: 8px; width: 100%; height:40px; box-sizing: border-box; padding: 0px 6px;">
|
||||||
|
${
|
||||||
|
data.apiKey ? "Re-login with ComfyDeploy" : "Login with ComfyDeploy"
|
||||||
|
}
|
||||||
|
</button>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
const button = this.container.querySelector("#loginButton");
|
||||||
|
button.onclick = () => {
|
||||||
|
const uuid =
|
||||||
|
Math.random().toString(36).substring(2, 15) +
|
||||||
|
Math.random().toString(36).substring(2, 15);
|
||||||
|
window.open(data.endpoint + "/auth-request/" + uuid, "_blank");
|
||||||
|
|
||||||
|
this.timeout = setTimeout(() => {
|
||||||
|
clearInterval(poll);
|
||||||
|
infoDialog.showMessage(
|
||||||
|
"Timeout",
|
||||||
|
"Wait too long for the response, please try re-login",
|
||||||
|
);
|
||||||
|
}, 30000); // Stop polling after 30 seconds
|
||||||
|
|
||||||
|
this.poll = setInterval(() => {
|
||||||
|
fetch(data.endpoint + "/api/auth-response/" + uuid)
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((json) => {
|
||||||
|
if (json.api_key) {
|
||||||
|
this.save(json.api_key, json.name);
|
||||||
|
this.container.querySelector("#apiKey").value = json.api_key;
|
||||||
|
infoDialog.show();
|
||||||
|
clearInterval(this.poll);
|
||||||
|
clearTimeout(this.timeout);
|
||||||
|
infoDialog.showMessage(
|
||||||
|
"Authenticated",
|
||||||
|
"You will be able to upload workflow to " + json.name,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error("Error:", error);
|
||||||
|
clearInterval(this.poll);
|
||||||
|
clearTimeout(this.timeout);
|
||||||
|
infoDialog.showMessage("Error", error);
|
||||||
|
});
|
||||||
|
}, 2000);
|
||||||
|
};
|
||||||
|
|
||||||
const apiKeyInput = this.container.querySelector("#apiKey");
|
const apiKeyInput = this.container.querySelector("#apiKey");
|
||||||
apiKeyInput.addEventListener("paste", function (e) {
|
apiKeyInput.addEventListener("paste", (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS "comfyui_deploy"."auth_requests" (
|
||||||
|
"request_id" text PRIMARY KEY NOT NULL,
|
||||||
|
"user_id" text,
|
||||||
|
"org_id" text,
|
||||||
|
"api_hash" text,
|
||||||
|
"created_at" timestamp DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
CREATE TABLE IF NOT EXISTS "comfyui_deploy"."user_usage" (
|
|
||||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
|
||||||
"user_id" text NOT NULL,
|
|
||||||
"usage_time" real DEFAULT 0 NOT NULL,
|
|
||||||
"created_at" timestamp DEFAULT now() NOT NULL,
|
|
||||||
"updated_at" timestamp DEFAULT now() NOT NULL
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
DO $$ BEGIN
|
|
||||||
ALTER TABLE "comfyui_deploy"."user_usage" ADD CONSTRAINT "user_usage_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "comfyui_deploy"."users"("id") ON DELETE cascade ON UPDATE no action;
|
|
||||||
EXCEPTION
|
|
||||||
WHEN duplicate_object THEN null;
|
|
||||||
END $$;
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "comfyui_deploy"."auth_requests" ADD COLUMN "expired_date" timestamp;
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE "comfyui_deploy"."user_usage" RENAME COLUMN "updated_at" TO "ended_at";--> statement-breakpoint
|
|
||||||
ALTER TABLE "comfyui_deploy"."user_usage" ADD COLUMN "org_id" text;
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"id": "91bb0461-452a-4e59-abf4-8757fcd75a89",
|
"id": "97662b25-3992-4859-9bdc-560e2a70daea",
|
||||||
"prevId": "1425ee00-66fb-4541-8da7-19b217944545",
|
"prevId": "1425ee00-66fb-4541-8da7-19b217944545",
|
||||||
"version": "5",
|
"version": "5",
|
||||||
"dialect": "pg",
|
"dialect": "pg",
|
||||||
@@ -88,6 +88,54 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"auth_requests": {
|
||||||
|
"name": "auth_requests",
|
||||||
|
"schema": "comfyui_deploy",
|
||||||
|
"columns": {
|
||||||
|
"request_id": {
|
||||||
|
"name": "request_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"org_id": {
|
||||||
|
"name": "org_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"api_hash": {
|
||||||
|
"name": "api_hash",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
},
|
||||||
|
"updated_at": {
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
"deployments": {
|
"deployments": {
|
||||||
"name": "deployments",
|
"name": "deployments",
|
||||||
"schema": "comfyui_deploy",
|
"schema": "comfyui_deploy",
|
||||||
@@ -360,64 +408,6 @@
|
|||||||
"compositePrimaryKeys": {},
|
"compositePrimaryKeys": {},
|
||||||
"uniqueConstraints": {}
|
"uniqueConstraints": {}
|
||||||
},
|
},
|
||||||
"user_usage": {
|
|
||||||
"name": "user_usage",
|
|
||||||
"schema": "comfyui_deploy",
|
|
||||||
"columns": {
|
|
||||||
"id": {
|
|
||||||
"name": "id",
|
|
||||||
"type": "uuid",
|
|
||||||
"primaryKey": true,
|
|
||||||
"notNull": true,
|
|
||||||
"default": "gen_random_uuid()"
|
|
||||||
},
|
|
||||||
"user_id": {
|
|
||||||
"name": "user_id",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true
|
|
||||||
},
|
|
||||||
"usage_time": {
|
|
||||||
"name": "usage_time",
|
|
||||||
"type": "real",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"default": 0
|
|
||||||
},
|
|
||||||
"created_at": {
|
|
||||||
"name": "created_at",
|
|
||||||
"type": "timestamp",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"default": "now()"
|
|
||||||
},
|
|
||||||
"updated_at": {
|
|
||||||
"name": "updated_at",
|
|
||||||
"type": "timestamp",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"default": "now()"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"indexes": {},
|
|
||||||
"foreignKeys": {
|
|
||||||
"user_usage_user_id_users_id_fk": {
|
|
||||||
"name": "user_usage_user_id_users_id_fk",
|
|
||||||
"tableFrom": "user_usage",
|
|
||||||
"tableTo": "users",
|
|
||||||
"columnsFrom": [
|
|
||||||
"user_id"
|
|
||||||
],
|
|
||||||
"columnsTo": [
|
|
||||||
"id"
|
|
||||||
],
|
|
||||||
"onDelete": "cascade",
|
|
||||||
"onUpdate": "no action"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"compositePrimaryKeys": {},
|
|
||||||
"uniqueConstraints": {}
|
|
||||||
},
|
|
||||||
"users": {
|
"users": {
|
||||||
"name": "users",
|
"name": "users",
|
||||||
"schema": "comfyui_deploy",
|
"schema": "comfyui_deploy",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"id": "fad17dc9-86c5-4081-8e73-47c113f48936",
|
"id": "8d654f92-7f7e-420f-bbd3-73b6b27adf35",
|
||||||
"prevId": "91bb0461-452a-4e59-abf4-8757fcd75a89",
|
"prevId": "97662b25-3992-4859-9bdc-560e2a70daea",
|
||||||
"version": "5",
|
"version": "5",
|
||||||
"dialect": "pg",
|
"dialect": "pg",
|
||||||
"tables": {
|
"tables": {
|
||||||
@@ -88,6 +88,60 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"auth_requests": {
|
||||||
|
"name": "auth_requests",
|
||||||
|
"schema": "comfyui_deploy",
|
||||||
|
"columns": {
|
||||||
|
"request_id": {
|
||||||
|
"name": "request_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"org_id": {
|
||||||
|
"name": "org_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"api_hash": {
|
||||||
|
"name": "api_hash",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
},
|
||||||
|
"expired_date": {
|
||||||
|
"name": "expired_date",
|
||||||
|
"type": "timestamp",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"updated_at": {
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
"deployments": {
|
"deployments": {
|
||||||
"name": "deployments",
|
"name": "deployments",
|
||||||
"schema": "comfyui_deploy",
|
"schema": "comfyui_deploy",
|
||||||
@@ -360,70 +414,6 @@
|
|||||||
"compositePrimaryKeys": {},
|
"compositePrimaryKeys": {},
|
||||||
"uniqueConstraints": {}
|
"uniqueConstraints": {}
|
||||||
},
|
},
|
||||||
"user_usage": {
|
|
||||||
"name": "user_usage",
|
|
||||||
"schema": "comfyui_deploy",
|
|
||||||
"columns": {
|
|
||||||
"id": {
|
|
||||||
"name": "id",
|
|
||||||
"type": "uuid",
|
|
||||||
"primaryKey": true,
|
|
||||||
"notNull": true,
|
|
||||||
"default": "gen_random_uuid()"
|
|
||||||
},
|
|
||||||
"org_id": {
|
|
||||||
"name": "org_id",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": false
|
|
||||||
},
|
|
||||||
"user_id": {
|
|
||||||
"name": "user_id",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true
|
|
||||||
},
|
|
||||||
"usage_time": {
|
|
||||||
"name": "usage_time",
|
|
||||||
"type": "real",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"default": 0
|
|
||||||
},
|
|
||||||
"created_at": {
|
|
||||||
"name": "created_at",
|
|
||||||
"type": "timestamp",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"default": "now()"
|
|
||||||
},
|
|
||||||
"ended_at": {
|
|
||||||
"name": "ended_at",
|
|
||||||
"type": "timestamp",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"default": "now()"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"indexes": {},
|
|
||||||
"foreignKeys": {
|
|
||||||
"user_usage_user_id_users_id_fk": {
|
|
||||||
"name": "user_usage_user_id_users_id_fk",
|
|
||||||
"tableFrom": "user_usage",
|
|
||||||
"tableTo": "users",
|
|
||||||
"columnsFrom": [
|
|
||||||
"user_id"
|
|
||||||
],
|
|
||||||
"columnsTo": [
|
|
||||||
"id"
|
|
||||||
],
|
|
||||||
"onDelete": "cascade",
|
|
||||||
"onUpdate": "no action"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"compositePrimaryKeys": {},
|
|
||||||
"uniqueConstraints": {}
|
|
||||||
},
|
|
||||||
"users": {
|
"users": {
|
||||||
"name": "users",
|
"name": "users",
|
||||||
"schema": "comfyui_deploy",
|
"schema": "comfyui_deploy",
|
||||||
@@ -835,8 +825,6 @@
|
|||||||
"_meta": {
|
"_meta": {
|
||||||
"schemas": {},
|
"schemas": {},
|
||||||
"tables": {},
|
"tables": {},
|
||||||
"columns": {
|
"columns": {}
|
||||||
"\"comfyui_deploy\".\"user_usage\".\"updated_at\"": "\"comfyui_deploy\".\"user_usage\".\"ended_at\""
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -236,15 +236,15 @@
|
|||||||
{
|
{
|
||||||
"idx": 33,
|
"idx": 33,
|
||||||
"version": "5",
|
"version": "5",
|
||||||
"when": 1705824362978,
|
"when": 1705853314500,
|
||||||
"tag": "0033_fantastic_marvel_boy",
|
"tag": "0033_awesome_human_fly",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"idx": 34,
|
"idx": 34,
|
||||||
"version": "5",
|
"version": "5",
|
||||||
"when": 1705840184127,
|
"when": 1705902960991,
|
||||||
"tag": "0034_previous_viper",
|
"tag": "0034_even_lady_ursula",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -14,8 +14,12 @@ if (sslMode === "false") sslMode = false;
|
|||||||
|
|
||||||
let connectionString = process.env.POSTGRES_URL!;
|
let connectionString = process.env.POSTGRES_URL!;
|
||||||
|
|
||||||
const isDevContainer = process.env.VSCODE_DEV_CONTAINER !== undefined;
|
const isDevContainer = process.env.REMOTE_CONTAINERS !== undefined;
|
||||||
if (isDevContainer) connectionString = connectionString.replace("localhost","host.docker.internal")
|
if (isDevContainer)
|
||||||
|
connectionString = connectionString.replace(
|
||||||
|
"localhost",
|
||||||
|
"host.docker.internal",
|
||||||
|
);
|
||||||
|
|
||||||
const sql = postgres(connectionString, { max: 1, ssl: sslMode as any });
|
const sql = postgres(connectionString, { max: 1, ssl: sslMode as any });
|
||||||
const db = drizzle(sql, {
|
const db = drizzle(sql, {
|
||||||
@@ -23,16 +27,16 @@ const db = drizzle(sql, {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let retries = 5;
|
let retries = 5;
|
||||||
while(retries) {
|
while (retries) {
|
||||||
try {
|
try {
|
||||||
await sql`SELECT NOW()`;
|
await sql`SELECT NOW()`;
|
||||||
console.log('Database is live');
|
console.log("Database is live");
|
||||||
break;
|
break;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Database is not live yet', error);
|
console.error("Database is not live yet", error);
|
||||||
retries -= 1;
|
retries -= 1;
|
||||||
console.log(`Retries left: ${retries}`);
|
console.log(`Retries left: ${retries}`);
|
||||||
await new Promise(res => setTimeout(res, 1000));
|
await new Promise((res) => setTimeout(res, 1000));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,6 @@
|
|||||||
"@hono/zod-openapi": "^0.9.5",
|
"@hono/zod-openapi": "^0.9.5",
|
||||||
"@hono/zod-validator": "^0.1.11",
|
"@hono/zod-validator": "^0.1.11",
|
||||||
"@hookform/resolvers": "^3.3.2",
|
"@hookform/resolvers": "^3.3.2",
|
||||||
"@lemonsqueezy/lemonsqueezy.js": "^1.2.5",
|
|
||||||
"@mdx-js/loader": "^3.0.0",
|
"@mdx-js/loader": "^3.0.0",
|
||||||
"@mdx-js/react": "^3.0.0",
|
"@mdx-js/react": "^3.0.0",
|
||||||
"@neondatabase/serverless": "^0.6.0",
|
"@neondatabase/serverless": "^0.6.0",
|
||||||
@@ -73,6 +72,7 @@
|
|||||||
"mdx-annotations": "^0.1.4",
|
"mdx-annotations": "^0.1.4",
|
||||||
"million": "latest",
|
"million": "latest",
|
||||||
"mitata": "^0.1.6",
|
"mitata": "^0.1.6",
|
||||||
|
"ms": "^2.1.3",
|
||||||
"nanoid": "^5.0.4",
|
"nanoid": "^5.0.4",
|
||||||
"next": "14.1",
|
"next": "14.1",
|
||||||
"next-plausible": "^3.12.0",
|
"next-plausible": "^3.12.0",
|
||||||
|
|||||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 29 KiB |
@@ -1,4 +1,3 @@
|
|||||||
import { app } from "../../../../routes/app";
|
|
||||||
import { registerCreateRunRoute } from "@/routes/registerCreateRunRoute";
|
import { registerCreateRunRoute } from "@/routes/registerCreateRunRoute";
|
||||||
import { registerGetOutputRoute } from "@/routes/registerGetOutputRoute";
|
import { registerGetOutputRoute } from "@/routes/registerGetOutputRoute";
|
||||||
import { registerUploadRoute } from "@/routes/registerUploadRoute";
|
import { registerUploadRoute } from "@/routes/registerUploadRoute";
|
||||||
@@ -6,7 +5,11 @@ import { isKeyRevoked } from "@/server/curdApiKeys";
|
|||||||
import { parseJWT } from "@/server/parseJWT";
|
import { parseJWT } from "@/server/parseJWT";
|
||||||
import type { Context, Next } from "hono";
|
import type { Context, Next } from "hono";
|
||||||
import { handle } from "hono/vercel";
|
import { handle } from "hono/vercel";
|
||||||
|
import { app } from "../../../../routes/app";
|
||||||
|
import { registerWorkflowUploadRoute } from "@/routes/registerWorkflowUploadRoute";
|
||||||
|
import { registerGetAuthResponse } from "@/routes/registerGetAuthResponse";
|
||||||
|
import { registerGetWorkflowRoute } from "@/routes/registerGetWorkflow";
|
||||||
|
import { cors } from "hono/cors";
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
export const maxDuration = 300; // 5 minutes
|
export const maxDuration = 300; // 5 minutes
|
||||||
|
|
||||||
@@ -16,14 +19,24 @@ declare module "hono" {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkAuth(c: Context, next: Next) {
|
async function checkAuth(c: Context, next: Next, headers?: HeadersInit) {
|
||||||
const token = c.req.raw.headers.get("Authorization")?.split(" ")?.[1]; // Assuming token is sent as "Bearer your_token"
|
const token = c.req.raw.headers.get("Authorization")?.split(" ")?.[1]; // Assuming token is sent as "Bearer your_token"
|
||||||
const userData = token ? parseJWT(token) : undefined;
|
const userData = token ? parseJWT(token) : undefined;
|
||||||
if (!userData || token === undefined) {
|
if (!userData || token === undefined) {
|
||||||
return c.text("Invalid or expired token", 401);
|
return c.text("Invalid or expired token", {
|
||||||
} else {
|
status: 401,
|
||||||
|
headers: headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the key has expiration, this is a temporary key and not in our db, so we can skip checking
|
||||||
|
if (userData.exp === undefined) {
|
||||||
const revokedKey = await isKeyRevoked(token);
|
const revokedKey = await isKeyRevoked(token);
|
||||||
if (revokedKey) return c.text("Revoked token", 401);
|
if (revokedKey)
|
||||||
|
return c.text("Revoked token", {
|
||||||
|
status: 401,
|
||||||
|
headers: headers,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
c.set("apiKeyTokenData", userData);
|
c.set("apiKeyTokenData", userData);
|
||||||
@@ -31,18 +44,35 @@ async function checkAuth(c: Context, next: Next) {
|
|||||||
await next();
|
await next();
|
||||||
}
|
}
|
||||||
|
|
||||||
app.use("/run", async (c, next) => {
|
app.use("/run", checkAuth);
|
||||||
return checkAuth(c, next);
|
app.use("/upload-url", checkAuth);
|
||||||
|
|
||||||
|
const corsHandler = cors({
|
||||||
|
origin: "*",
|
||||||
|
allowHeaders: ["Authorization", "Content-Type"],
|
||||||
|
allowMethods: ["POST", "GET", "OPTIONS"],
|
||||||
|
exposeHeaders: ["Content-Length"],
|
||||||
|
maxAge: 600,
|
||||||
|
credentials: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
app.use("/upload-url", async (c, next) => {
|
// CORS Check
|
||||||
return checkAuth(c, next);
|
app.use("/workflow", corsHandler, checkAuth);
|
||||||
});
|
app.use("/workflow-version/*", corsHandler, checkAuth);
|
||||||
|
|
||||||
|
// create run endpoint
|
||||||
registerCreateRunRoute(app);
|
registerCreateRunRoute(app);
|
||||||
registerGetOutputRoute(app);
|
registerGetOutputRoute(app);
|
||||||
|
|
||||||
|
// file upload endpoint
|
||||||
registerUploadRoute(app);
|
registerUploadRoute(app);
|
||||||
|
|
||||||
|
// Anon
|
||||||
|
registerGetAuthResponse(app);
|
||||||
|
|
||||||
|
registerWorkflowUploadRoute(app);
|
||||||
|
registerGetWorkflowRoute(app);
|
||||||
|
|
||||||
// The OpenAPI documentation will be available at /doc
|
// The OpenAPI documentation will be available at /doc
|
||||||
app.doc("/doc", {
|
app.doc("/doc", {
|
||||||
openapi: "3.0.0",
|
openapi: "3.0.0",
|
||||||
@@ -69,3 +99,4 @@ const handler = handle(app);
|
|||||||
|
|
||||||
export const GET = handler;
|
export const GET = handler;
|
||||||
export const POST = handler;
|
export const POST = handler;
|
||||||
|
export const OPTIONS = handler;
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { parseDataSafe } from "../../../../lib/parseDataSafe";
|
|
||||||
import { handleResourceUpload } from "@/server/resource";
|
import { handleResourceUpload } from "@/server/resource";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
import { parseDataSafe } from "../../../../lib/parseDataSafe";
|
||||||
|
|
||||||
const Request = z.object({
|
const Request = z.object({
|
||||||
file_name: z.string(),
|
file_name: z.string(),
|
||||||
run_id: z.string(),
|
run_id: z.string(),
|
||||||
|
|
||||||
type: z.string(),
|
type: z.string(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -29,7 +30,7 @@ export async function GET(request: Request) {
|
|||||||
{
|
{
|
||||||
url: uploadUrl,
|
url: uploadUrl,
|
||||||
},
|
},
|
||||||
{ status: 200 }
|
{ status: 200 },
|
||||||
);
|
);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const errorMessage =
|
const errorMessage =
|
||||||
@@ -38,7 +39,7 @@ export async function GET(request: Request) {
|
|||||||
{
|
{
|
||||||
error: errorMessage,
|
error: errorMessage,
|
||||||
},
|
},
|
||||||
{ status: 500 }
|
{ status: 500 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,6 @@
|
|||||||
import { parseDataSafe } from "../../../../lib/parseDataSafe";
|
import { parseDataSafe } from "../../../../lib/parseDataSafe";
|
||||||
import { db } from "@/db/db";
|
import { db } from "@/db/db";
|
||||||
import {
|
import { workflowRunOutputs, workflowRunsTable } from "@/db/schema";
|
||||||
userUsageTable,
|
|
||||||
workflowRunOutputs,
|
|
||||||
workflowRunsTable,
|
|
||||||
workflowTable,
|
|
||||||
} from "@/db/schema";
|
|
||||||
import { getDuration } from "@/lib/getRelativeTime";
|
|
||||||
import { getSubscription, setUsage } from "@/server/linkToPricing";
|
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
@@ -34,6 +27,7 @@ export async function POST(request: Request) {
|
|||||||
data: output_data,
|
data: output_data,
|
||||||
});
|
});
|
||||||
} else if (status) {
|
} else if (status) {
|
||||||
|
// console.log("status", status);
|
||||||
const workflow_run = await db
|
const workflow_run = await db
|
||||||
.update(workflowRunsTable)
|
.update(workflowRunsTable)
|
||||||
.set({
|
.set({
|
||||||
@@ -41,15 +35,8 @@ export async function POST(request: Request) {
|
|||||||
ended_at:
|
ended_at:
|
||||||
status === "success" || status === "failed" ? new Date() : null,
|
status === "success" || status === "failed" ? new Date() : null,
|
||||||
})
|
})
|
||||||
.where(eq(workflowRunsTable.id, run_id));
|
.where(eq(workflowRunsTable.id, run_id))
|
||||||
|
.returning();
|
||||||
// get data from workflowRunsTable
|
|
||||||
const userUsageTime = await importUserUsageData(run_id);
|
|
||||||
|
|
||||||
if (userUsageTime) {
|
|
||||||
// get the usage_time from userUsage
|
|
||||||
await addSubscriptionUnit(userUsageTime);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// const workflow_version = await db.query.workflowVersionTable.findFirst({
|
// const workflow_version = await db.query.workflowVersionTable.findFirst({
|
||||||
@@ -67,47 +54,3 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function addSubscriptionUnit(userUsageTime: number) {
|
|
||||||
const subscription = await getSubscription();
|
|
||||||
|
|
||||||
// round up userUsageTime to the nearest integer
|
|
||||||
const roundedUsageTime = Math.ceil(userUsageTime);
|
|
||||||
|
|
||||||
if (subscription) {
|
|
||||||
const usage = await setUsage(
|
|
||||||
subscription.data[0].attributes.first_subscription_item.id,
|
|
||||||
roundedUsageTime
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function importUserUsageData(run_id: string) {
|
|
||||||
const workflowRuns = await db.query.workflowRunsTable.findFirst({
|
|
||||||
where: eq(workflowRunsTable.id, run_id),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!workflowRuns?.workflow_id) return;
|
|
||||||
|
|
||||||
// find if workflowTable id column contains workflowRunsTable workflow_id
|
|
||||||
const workflow = await db.query.workflowTable.findFirst({
|
|
||||||
where: eq(workflowTable.id, workflowRuns.workflow_id),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (workflowRuns?.ended_at === null || workflow == null) return;
|
|
||||||
|
|
||||||
const usageTime = parseFloat(
|
|
||||||
getDuration((workflowRuns?.ended_at - workflowRuns?.started_at) / 1000)
|
|
||||||
);
|
|
||||||
|
|
||||||
// add data to userUsageTable
|
|
||||||
const user_usage = await db.insert(userUsageTable).values({
|
|
||||||
user_id: workflow.user_id,
|
|
||||||
created_at: workflowRuns.ended_at,
|
|
||||||
org_id: workflow.org_id,
|
|
||||||
ended_at: workflowRuns.ended_at,
|
|
||||||
usage_time: usageTime,
|
|
||||||
});
|
|
||||||
|
|
||||||
return usageTime;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,17 +1,14 @@
|
|||||||
import { createNewWorkflow } from "../../../../server/createNewWorkflow";
|
import { snapshotType, workflowAPIType, workflowType } from "@/db/schema";
|
||||||
import { parseJWT } from "../../../../server/parseJWT";
|
|
||||||
import { db } from "@/db/db";
|
|
||||||
import {
|
|
||||||
snapshotType,
|
|
||||||
workflowAPIType,
|
|
||||||
workflowTable,
|
|
||||||
workflowType,
|
|
||||||
workflowVersionTable,
|
|
||||||
} from "@/db/schema";
|
|
||||||
import { parseDataSafe } from "@/lib/parseDataSafe";
|
import { parseDataSafe } from "@/lib/parseDataSafe";
|
||||||
import { eq, sql } from "drizzle-orm";
|
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
createNewWorkflow,
|
||||||
|
createNewWorkflowVersion,
|
||||||
|
} from "../../../../server/createNewWorkflow";
|
||||||
|
import { parseJWT } from "../../../../server/parseJWT";
|
||||||
|
|
||||||
|
// This is will be deprecated
|
||||||
|
|
||||||
const corsHeaders = {
|
const corsHeaders = {
|
||||||
"Access-Control-Allow-Origin": "*",
|
"Access-Control-Allow-Origin": "*",
|
||||||
@@ -55,7 +52,7 @@ export async function POST(request: Request) {
|
|||||||
const [data, error] = await parseDataSafe(
|
const [data, error] = await parseDataSafe(
|
||||||
UploadRequest,
|
UploadRequest,
|
||||||
request,
|
request,
|
||||||
corsHeaders
|
corsHeaders,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!data || error) return error;
|
if (!data || error) return error;
|
||||||
@@ -75,7 +72,7 @@ export async function POST(request: Request) {
|
|||||||
|
|
||||||
// Case 1 new workflow
|
// Case 1 new workflow
|
||||||
try {
|
try {
|
||||||
if ((!workflow_id || workflow_id.length == 0) && workflow_name) {
|
if ((!workflow_id || workflow_id.length === 0) && workflow_name) {
|
||||||
// Create a new parent workflow
|
// Create a new parent workflow
|
||||||
const { workflow_id: _workflow_id, version: _version } =
|
const { workflow_id: _workflow_id, version: _version } =
|
||||||
await createNewWorkflow({
|
await createNewWorkflow({
|
||||||
@@ -91,56 +88,17 @@ export async function POST(request: Request) {
|
|||||||
|
|
||||||
workflow_id = _workflow_id;
|
workflow_id = _workflow_id;
|
||||||
version = _version;
|
version = _version;
|
||||||
|
|
||||||
// const workflow_parent = await db
|
|
||||||
// .insert(workflowTable)
|
|
||||||
// .values({
|
|
||||||
// user_id,
|
|
||||||
// name: workflow_name,
|
|
||||||
// org_id: org_id,
|
|
||||||
// })
|
|
||||||
// .returning();
|
|
||||||
|
|
||||||
// workflow_id = workflow_parent[0].id;
|
|
||||||
|
|
||||||
// // Create a new version
|
|
||||||
// const data = await db
|
|
||||||
// .insert(workflowVersionTable)
|
|
||||||
// .values({
|
|
||||||
// workflow_id: workflow_id,
|
|
||||||
// workflow,
|
|
||||||
// workflow_api,
|
|
||||||
// version: 1,
|
|
||||||
// snapshot: snapshot,
|
|
||||||
// })
|
|
||||||
// .returning();
|
|
||||||
// version = data[0].version;
|
|
||||||
} else if (workflow_id) {
|
} else if (workflow_id) {
|
||||||
// Case 2 update workflow
|
// Case 2 update workflow
|
||||||
const data = await db
|
const { version: _version } = await createNewWorkflowVersion({
|
||||||
.insert(workflowVersionTable)
|
workflow_id: workflow_id,
|
||||||
.values({
|
workflowData: {
|
||||||
workflow_id,
|
workflow,
|
||||||
workflow: workflow,
|
|
||||||
workflow_api,
|
workflow_api,
|
||||||
// version: sql`${workflowVersionTable.version} + 1`,
|
snapshot,
|
||||||
snapshot: snapshot,
|
},
|
||||||
version: sql`(
|
});
|
||||||
SELECT COALESCE(MAX(version), 0) + 1
|
version = _version;
|
||||||
FROM ${workflowVersionTable}
|
|
||||||
WHERE workflow_id = ${workflow_id}
|
|
||||||
)`,
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
version = data[0].version;
|
|
||||||
|
|
||||||
await db
|
|
||||||
.update(workflowTable)
|
|
||||||
.set({
|
|
||||||
updated_at: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(workflowTable.id, workflow_id))
|
|
||||||
.returning();
|
|
||||||
} else {
|
} else {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
@@ -150,7 +108,7 @@ export async function POST(request: Request) {
|
|||||||
status: 500,
|
status: 500,
|
||||||
statusText: "Invalid request",
|
statusText: "Invalid request",
|
||||||
headers: corsHeaders,
|
headers: corsHeaders,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -162,7 +120,7 @@ export async function POST(request: Request) {
|
|||||||
status: 500,
|
status: 500,
|
||||||
statusText: "Invalid request",
|
statusText: "Invalid request",
|
||||||
headers: corsHeaders,
|
headers: corsHeaders,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,6 +132,6 @@ export async function POST(request: Request) {
|
|||||||
{
|
{
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: corsHeaders,
|
headers: corsHeaders,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { ButtonAction } from "@/components/ButtonActionLoader";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { createAuthRequest } from "@/server/curdApiKeys";
|
||||||
|
import { auth } from "@clerk/nextjs";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { getOrgOrUserDisplayName } from "../../../../server/getOrgOrUserDisplayName";
|
||||||
|
import { db } from "@/db/db";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { authRequestsTable } from "@/db/schema";
|
||||||
|
|
||||||
|
export default async function Home({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: { request_id: string };
|
||||||
|
}) {
|
||||||
|
const { userId, orgId } = await auth();
|
||||||
|
|
||||||
|
if (!userId) redirect("/");
|
||||||
|
|
||||||
|
if (!params.request_id)
|
||||||
|
return (
|
||||||
|
<div className="h-full w-full flex flex-col gap-2 items-center justify-center">
|
||||||
|
No valid request_id
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const existingResult = await db.query.authRequestsTable.findFirst({
|
||||||
|
where: eq(authRequestsTable.request_id, params.request_id),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existingResult?.api_hash) {
|
||||||
|
return (
|
||||||
|
<div className="h-full w-full flex flex-col gap-2 items-center justify-center">
|
||||||
|
Request already consumed.
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const userName = await getOrgOrUserDisplayName(orgId, userId);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-full w-full flex flex-col gap-2 items-center justify-center">
|
||||||
|
<div className="text-lg">Grant API Access to {userName}</div>
|
||||||
|
<Button asChild>
|
||||||
|
<ButtonAction
|
||||||
|
routerAction="do-nothing"
|
||||||
|
action={createAuthRequest.bind(null, params.request_id)}
|
||||||
|
>
|
||||||
|
Grant Access
|
||||||
|
</ButtonAction>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return <Examples />;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
type exampleWorkflow = {
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
previewURL: string;
|
||||||
|
image: {
|
||||||
|
src: string,
|
||||||
|
alt: string,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const exampleWorkflows: exampleWorkflow[] = [
|
||||||
|
{
|
||||||
|
title: "Txt2Img SDXL",
|
||||||
|
description: "The basic workflow, type a prompt and generate images based on that.",
|
||||||
|
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-txt2img-sdxl',
|
||||||
|
image: {
|
||||||
|
src: '/example-workflows/txt2img.webp',
|
||||||
|
alt: 'IPAdapter workflow',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Txt2Img LCM SDXL",
|
||||||
|
description: "Images in a couple of seconds, increase the speed of each generation using LCM Lora.",
|
||||||
|
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-lcm-sdxl',
|
||||||
|
image: {
|
||||||
|
src: '/example-workflows/txt2img-lcm.webp',
|
||||||
|
alt: 'txt2img LCM SDXL',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "IPAdapter SDXL",
|
||||||
|
description: "Load images and use them as reference for new generations.",
|
||||||
|
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-ip-adapter-sdxl',
|
||||||
|
image: {
|
||||||
|
src: '/example-workflows/ipadapter.webp',
|
||||||
|
alt: 'IPAdapter workflow',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Upscale and Add Detail SDXL",
|
||||||
|
description: "Upscale and Add Details to your creations.",
|
||||||
|
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-upscale-and-add-detail-sdxl',
|
||||||
|
image: {
|
||||||
|
src: '/example-workflows/upscale.webp',
|
||||||
|
alt: 'Upscale and Add Detail SDXL',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Txt2Img SDXL Turbo",
|
||||||
|
description: "Try SDXL turbo and generate images since 1 step in seconds.",
|
||||||
|
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-txt2img-sdxl-turbo',
|
||||||
|
image: {
|
||||||
|
src: '/example-workflows/txt2img-sdxl-turbo.webp',
|
||||||
|
alt: 'Txt2Img SDXL Turbo',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Img2Img SDXL Controlnet",
|
||||||
|
description: "This workflow uses canny. Generate lines of you original image and create variations.",
|
||||||
|
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-img2-img-sdxl-controlnet',
|
||||||
|
image: {
|
||||||
|
src: '/example-workflows/txt2img-controlnet.webp',
|
||||||
|
alt: 'Img2Img SDXL Controlnet',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Automatic Inpainting (SEG)",
|
||||||
|
description: "Type what do you want to select and change that area with your prompt.",
|
||||||
|
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-automatic-inpainting-clip-seg',
|
||||||
|
image: {
|
||||||
|
src: '/example-workflows/automatic-inpainting-seg.webp',
|
||||||
|
alt: 'Img2Img SDXL Controlnet',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
|
||||||
|
async function Examples() {
|
||||||
|
return (
|
||||||
|
<div className="w-full py-4">
|
||||||
|
<section className="mx-auto flex max-w-[980px] flex-col items-center gap-2 py-8 md:py-12 md:pb-8 lg:py-24 lg:pb-20">
|
||||||
|
<h1 className="scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl text-center">
|
||||||
|
Check out some examples
|
||||||
|
</h1>
|
||||||
|
<p className="max-w-[560px] text-center text-lg text-muted-foreground">Text to Image, Image to Image, IPAdapter, and more. Here are some examples that you can use to deploy your workflow.</p>
|
||||||
|
</section>
|
||||||
|
<section className="flex justify-center flex-wrap gap-5">
|
||||||
|
{exampleWorkflows.map(workflow => {
|
||||||
|
return <Card className="w-[350px]">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{workflow.title}</CardTitle>
|
||||||
|
<CardDescription>{workflow.description}</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Image src={workflow.image.src} alt={workflow.image.alt} width={350} height={230} />
|
||||||
|
</CardContent>
|
||||||
|
<CardFooter className="flex justify-end gap-2">
|
||||||
|
<Button asChild>
|
||||||
|
<Link href={workflow.previewURL}>View Workflow</Link>
|
||||||
|
</Button>
|
||||||
|
</CardFooter>
|
||||||
|
</Card>;
|
||||||
|
})}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -80,7 +80,9 @@
|
|||||||
/* @apply rounded-lg p-2 overflow-x-scroll */
|
/* @apply rounded-lg p-2 overflow-x-scroll */
|
||||||
@apply p-2 max-w-full overflow-auto w-full
|
@apply p-2 max-w-full overflow-auto w-full
|
||||||
}
|
}
|
||||||
|
.vsc-controller{
|
||||||
|
position: absolute;
|
||||||
|
}
|
||||||
@layer base {
|
@layer base {
|
||||||
* {
|
* {
|
||||||
@apply border-border;
|
@apply border-border;
|
||||||
|
|||||||
@@ -1,81 +0,0 @@
|
|||||||
const people = [
|
|
||||||
{
|
|
||||||
name: "Nvidia T4 GPU",
|
|
||||||
gpu: "1x",
|
|
||||||
ram: "16GB",
|
|
||||||
price: "$0.000225/sec",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Nvidia A40 GPU",
|
|
||||||
gpu: "1x",
|
|
||||||
ram: "48GB",
|
|
||||||
price: "$0.000575/sec",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export function GpuPricingPlan() {
|
|
||||||
return (
|
|
||||||
<div className="flex justify-center w-full py-8">
|
|
||||||
<div className="w-full max-w-4xl">
|
|
||||||
<table className="min-w-full divide-y divide-gray-300">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th
|
|
||||||
scope="col"
|
|
||||||
className="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6"
|
|
||||||
>
|
|
||||||
GPU
|
|
||||||
</th>
|
|
||||||
<th
|
|
||||||
scope="col"
|
|
||||||
className="hidden px-3 py-3.5 text-left text-sm font-semibold text-gray-900 lg:table-cell"
|
|
||||||
>
|
|
||||||
No.
|
|
||||||
</th>
|
|
||||||
<th
|
|
||||||
scope="col"
|
|
||||||
className="hidden px-3 py-3.5 text-left text-sm font-semibold text-gray-900 sm:table-cell"
|
|
||||||
>
|
|
||||||
RAM
|
|
||||||
</th>
|
|
||||||
<th
|
|
||||||
scope="col"
|
|
||||||
className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
|
|
||||||
>
|
|
||||||
Price
|
|
||||||
</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-gray-200 bg-white">
|
|
||||||
{people.map((person) => (
|
|
||||||
<tr key={person.ram} className="even:bg-gray-50">
|
|
||||||
<td className="w-full max-w-0 py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:w-auto sm:max-w-none sm:pl-6">
|
|
||||||
{person.name}
|
|
||||||
<dl className="font-normal lg:hidden">
|
|
||||||
<dt className="sr-only">No.</dt>
|
|
||||||
<dd className="mt-1 truncate text-gray-700">
|
|
||||||
{person.gpu}
|
|
||||||
</dd>
|
|
||||||
<dt className="sr-only sm:hidden">RAM</dt>
|
|
||||||
<dd className="mt-1 truncate text-gray-500 sm:hidden">
|
|
||||||
{person.ram}
|
|
||||||
</dd>
|
|
||||||
</dl>
|
|
||||||
</td>
|
|
||||||
<td className="hidden px-3 py-4 text-sm text-gray-500 lg:table-cell">
|
|
||||||
{person.gpu}
|
|
||||||
</td>
|
|
||||||
<td className="hidden px-3 py-4 text-sm text-gray-500 sm:table-cell">
|
|
||||||
{person.ram}
|
|
||||||
</td>
|
|
||||||
<td className="px-3 py-4 text-sm text-gray-500">
|
|
||||||
{person.price}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
import { checkMarkIcon, crossMarkIcon } from "../const/Icon";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { getPricing } from "@/server/linkToPricing";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
type Tier = {
|
|
||||||
name: string;
|
|
||||||
id: string;
|
|
||||||
href: string;
|
|
||||||
priceMonthly: string;
|
|
||||||
description: string;
|
|
||||||
features: string[];
|
|
||||||
featured: boolean;
|
|
||||||
priority?: TierPriority;
|
|
||||||
};
|
|
||||||
|
|
||||||
enum TierPriority {
|
|
||||||
Free = "free",
|
|
||||||
Pro = "pro",
|
|
||||||
Enterprise = "enterprise",
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function PricingList() {
|
|
||||||
const [productTiers, setProductTiers] = useState<Tier[]>();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
(async () => {
|
|
||||||
const product = await getPricing();
|
|
||||||
|
|
||||||
if (!product) return;
|
|
||||||
|
|
||||||
const newProductTiers: Tier[] = product.data.map((item) => {
|
|
||||||
// Create a new DOMParser instance
|
|
||||||
const parser = new DOMParser();
|
|
||||||
// Parse the description HTML string to a new document
|
|
||||||
const doc = parser.parseFromString(
|
|
||||||
item.attributes.description,
|
|
||||||
"text/html"
|
|
||||||
);
|
|
||||||
// Extract the description and features
|
|
||||||
const description = doc.querySelector("p")?.textContent || "";
|
|
||||||
const features = Array.from(doc.querySelectorAll("ul > li")).map(
|
|
||||||
(li) => li.textContent || ""
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: item.attributes.name,
|
|
||||||
id: item.id,
|
|
||||||
href: item.attributes.buy_now_url,
|
|
||||||
priceMonthly:
|
|
||||||
item.attributes.price_formatted.split("/")[0] == "Usage-based"
|
|
||||||
? "$20.00"
|
|
||||||
: item.attributes.price_formatted.split("/")[0],
|
|
||||||
description: description,
|
|
||||||
features: features,
|
|
||||||
|
|
||||||
// if name contains pro, it's featured
|
|
||||||
featured: item.attributes.name.toLowerCase().includes("pro"),
|
|
||||||
|
|
||||||
// give priority if name contain in enum
|
|
||||||
priority: Object.values(TierPriority).find((priority) =>
|
|
||||||
item.attributes.name.toLowerCase().includes(priority)
|
|
||||||
),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// sort newProductTiers by priority
|
|
||||||
newProductTiers.sort((a, b) => {
|
|
||||||
if (!a.priority) return 1;
|
|
||||||
if (!b.priority) return -1;
|
|
||||||
return (
|
|
||||||
Object.values(TierPriority).indexOf(a.priority) -
|
|
||||||
Object.values(TierPriority).indexOf(b.priority)
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
setProductTiers(newProductTiers);
|
|
||||||
})();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="relative isolate px-6 py-24 lg:px-8">
|
|
||||||
<div className="mx-auto max-w-2xl text-center lg:max-w-4xl">
|
|
||||||
<h2 className="text-base font-semibold leading-7 text-indigo-600">
|
|
||||||
Pricing
|
|
||||||
</h2>
|
|
||||||
<p className="mt-2 text-4xl font-bold tracking-tight text-gray-900 sm:text-5xl">
|
|
||||||
The right price for you, whoever you are
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<p className="mx-auto mt-6 max-w-2xl text-center text-lg leading-8 text-gray-600">
|
|
||||||
Qui iusto aut est earum eos quae. Eligendi est at nam aliquid ad quo
|
|
||||||
reprehenderit in aliquid fugiat dolorum voluptatibus.
|
|
||||||
</p>
|
|
||||||
<div className="mx-auto mt-16 grid max-w-lg grid-cols-1 items-center gap-y-6 sm:mt-20 sm:gap-y-0 lg:max-w-4xl lg:grid-cols-2 xl:max-w-6xl xl:grid-cols-3">
|
|
||||||
{productTiers &&
|
|
||||||
productTiers.map((tier, tierIdx) => (
|
|
||||||
<div
|
|
||||||
key={tier.id}
|
|
||||||
className={cn(
|
|
||||||
tier.featured
|
|
||||||
? "relative bg-white shadow-2xl"
|
|
||||||
: "bg-white/60 sm:mx-8 lg:mx-0",
|
|
||||||
tier.featured
|
|
||||||
? ""
|
|
||||||
: tierIdx === 0
|
|
||||||
? "rounded-t-3xl sm:rounded-b-none lg:rounded-tr-none lg:rounded-bl-3xl"
|
|
||||||
: "sm:rounded-t-none lg:rounded-tr-3xl lg:rounded-bl-none",
|
|
||||||
"rounded-3xl p-8 ring-1 ring-gray-900/10 sm:p-10"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<h3
|
|
||||||
id={tier.id}
|
|
||||||
className="text-base font-semibold leading-7 text-indigo-600"
|
|
||||||
>
|
|
||||||
{tier.name}
|
|
||||||
</h3>
|
|
||||||
<p className="mt-4 flex items-baseline gap-x-2">
|
|
||||||
<span className="text-5xl font-bold tracking-tight text-gray-900">
|
|
||||||
{tier.priceMonthly}
|
|
||||||
</span>
|
|
||||||
<span className="text-base text-gray-500">/month</span>
|
|
||||||
</p>
|
|
||||||
<p className="mt-6 text-base leading-7 text-gray-600">
|
|
||||||
{tier.description}
|
|
||||||
</p>
|
|
||||||
<ul
|
|
||||||
role="list"
|
|
||||||
className="mt-8 space-y-3 text-sm leading-6 text-gray-600 sm:mt-10"
|
|
||||||
>
|
|
||||||
{tier.features.map((feature) => (
|
|
||||||
<li key={feature} className="flex gap-x-3">
|
|
||||||
<div className="flex justify-center items-center">
|
|
||||||
{feature.includes("[x]") ? crossMarkIcon : checkMarkIcon}
|
|
||||||
</div>
|
|
||||||
{feature.replace("[x]", "")}
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
<a
|
|
||||||
href={tier.href}
|
|
||||||
aria-describedby={tier.id}
|
|
||||||
className={cn(
|
|
||||||
tier.featured
|
|
||||||
? "bg-indigo-600 text-white shadow hover:bg-indigo-500"
|
|
||||||
: "text-indigo-600 ring-1 ring-inset ring-indigo-200 hover:ring-indigo-300",
|
|
||||||
"mt-8 block rounded-md py-2.5 px-3.5 text-center text-sm font-semibold focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 sm:mt-10"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Get started today
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
export const checkMarkIcon = (
|
|
||||||
<svg
|
|
||||||
className="h-5 w-5 flex-shrink-0 text-green-500"
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
viewBox="0 0 20 20"
|
|
||||||
fill="currentColor"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
fillRule="evenodd"
|
|
||||||
d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z"
|
|
||||||
clipRule="evenodd"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
export const crossMarkIcon = (
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
x="0px"
|
|
||||||
y="0px"
|
|
||||||
width="20"
|
|
||||||
height="20"
|
|
||||||
viewBox="0 0 48 48"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
fill="#F44336"
|
|
||||||
d="M21.5 4.5H26.501V43.5H21.5z"
|
|
||||||
transform="rotate(45.001 24 24)"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="#F44336"
|
|
||||||
d="M21.5 4.5H26.5V43.501H21.5z"
|
|
||||||
transform="rotate(135.008 24 24)"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { GpuPricingPlan } from "@/app/(app)/pricing/components/gpuPricingTable";
|
|
||||||
import PricingList from "@/app/(app)/pricing/components/pricePlanList";
|
|
||||||
|
|
||||||
export default function Home() {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<PricingList />
|
|
||||||
<GpuPricingPlan />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -2,12 +2,13 @@ import { CreateShareButton } from "@/components/CreateShareButton";
|
|||||||
import { MachinesWSMain } from "@/components/MachinesWS";
|
import { MachinesWSMain } from "@/components/MachinesWS";
|
||||||
import { VersionDetails } from "@/components/VersionDetails";
|
import { VersionDetails } from "@/components/VersionDetails";
|
||||||
import {
|
import {
|
||||||
CopyWorkflowVersion,
|
CopyWorkflowVersion,
|
||||||
CreateDeploymentButton,
|
CreateDeploymentButton,
|
||||||
MachineSelect,
|
MachineSelect,
|
||||||
RunWorkflowButton,
|
OpenEditButton,
|
||||||
VersionSelect,
|
RunWorkflowButton,
|
||||||
ViewWorkflowDetailsButton,
|
VersionSelect,
|
||||||
|
ViewWorkflowDetailsButton,
|
||||||
} from "@/components/VersionSelect";
|
} from "@/components/VersionSelect";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
@@ -48,6 +49,7 @@ export default async function Page({
|
|||||||
<CreateShareButton workflow={workflow} machines={machines} />
|
<CreateShareButton workflow={workflow} machines={machines} />
|
||||||
<CopyWorkflowVersion workflow={workflow} />
|
<CopyWorkflowVersion workflow={workflow} />
|
||||||
<ViewWorkflowDetailsButton workflow={workflow} />
|
<ViewWorkflowDetailsButton workflow={workflow} />
|
||||||
|
<OpenEditButton workflow={workflow} machines={machines} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<VersionDetails workflow={workflow} />
|
<VersionDetails workflow={workflow} />
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { setInitialUserData } from "../../../lib/setInitialUserData";
|
import { setInitialUserData } from "../../../lib/setInitialUserData";
|
||||||
import { getAllUserWorkflow } from "../../../server/getAllUserWorkflow";
|
import { getAllUserWorkflow } from "../../../server/crudWorkflow";
|
||||||
import { WorkflowList } from "@/components/WorkflowList";
|
import { WorkflowList } from "@/components/WorkflowList";
|
||||||
import { db } from "@/db/db";
|
import { db } from "@/db/db";
|
||||||
import { usersTable } from "@/db/schema";
|
import { usersTable } from "@/db/schema";
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ import { LoadingIcon } from "@/components/LoadingIcon";
|
|||||||
import { callServerPromise } from "@/components/callServerPromise";
|
import { callServerPromise } from "@/components/callServerPromise";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/components/ui/dropdown-menu";
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { useAuth, useClerk } from "@clerk/nextjs";
|
import { useAuth, useClerk } from "@clerk/nextjs";
|
||||||
import { MoreVertical } from "lucide-react";
|
import { MoreVertical } from "lucide-react";
|
||||||
@@ -15,80 +15,79 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
export function ButtonAction({
|
export function ButtonAction({
|
||||||
action,
|
action,
|
||||||
children,
|
children,
|
||||||
routerAction = "back",
|
routerAction = "back",
|
||||||
...rest
|
...rest
|
||||||
}: {
|
}: {
|
||||||
action: () => Promise<any>;
|
action: () => Promise<any>;
|
||||||
routerAction?: "refresh" | "back";
|
routerAction?: "refresh" | "back" | "do-nothing";
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const [pending, setPending] = useState(false);
|
const [pending, setPending] = useState(false);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (pending) return;
|
if (pending) return;
|
||||||
|
|
||||||
setPending(true);
|
setPending(true);
|
||||||
await callServerPromise(action());
|
await callServerPromise(action());
|
||||||
setPending(false);
|
setPending(false);
|
||||||
|
|
||||||
if (routerAction === "back") {
|
if (routerAction === "back") {
|
||||||
router.back();
|
router.back();
|
||||||
router.refresh();
|
router.refresh();
|
||||||
}
|
} else if (routerAction === "refresh") router.refresh();
|
||||||
else if (routerAction === "refresh") router.refresh();
|
}}
|
||||||
}}
|
{...rest}
|
||||||
{...rest}
|
>
|
||||||
>
|
{children} {pending && <LoadingIcon />}
|
||||||
{children} {pending && <LoadingIcon />}
|
</button>
|
||||||
</button>
|
);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ButtonActionMenu(props: {
|
export function ButtonActionMenu(props: {
|
||||||
title?: string;
|
title?: string;
|
||||||
actions: {
|
actions: {
|
||||||
title: string;
|
title: string;
|
||||||
action: () => Promise<any>;
|
action: () => Promise<any>;
|
||||||
}[];
|
}[];
|
||||||
}) {
|
}) {
|
||||||
const user = useAuth();
|
const user = useAuth();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const clerk = useClerk();
|
const clerk = useClerk();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button className="gap-2" variant="outline" disabled={isLoading}>
|
<Button className="gap-2" variant="outline" disabled={isLoading}>
|
||||||
{props.title}
|
{props.title}
|
||||||
{isLoading ? <LoadingIcon /> : <MoreVertical size={14} />}
|
{isLoading ? <LoadingIcon /> : <MoreVertical size={14} />}
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent className="w-56">
|
<DropdownMenuContent className="w-56">
|
||||||
{props.actions.map((action) => (
|
{props.actions.map((action) => (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
key={action.title}
|
key={action.title}
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (!user.isSignedIn) {
|
if (!user.isSignedIn) {
|
||||||
clerk.openSignIn({
|
clerk.openSignIn({
|
||||||
redirectUrl: window.location.href,
|
redirectUrl: window.location.href,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
await callServerPromise(action.action());
|
await callServerPromise(action.action());
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{action.title}
|
{action.title}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
))}
|
))}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export function CreateShareButton({
|
|||||||
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const workflow_version_id = workflow?.versions.find(
|
const workflow_version_id = workflow?.versions.find(
|
||||||
(x) => x.version === version,
|
(x) => x.version == version,
|
||||||
)?.id;
|
)?.id;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { CodeBlock } from "@/components/CodeBlock";
|
import { CodeBlock } from "@/components/CodeBlock";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
DialogDescription,
|
DialogDescription,
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
DialogTrigger,
|
DialogTrigger,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
import { TableRow } from "@/components/ui/table";
|
import { TableRow } from "@/components/ui/table";
|
||||||
@@ -83,145 +83,145 @@ const run = await client.getRun(run_id);
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
export function DeploymentDisplay({
|
export function DeploymentDisplay({
|
||||||
deployment,
|
deployment,
|
||||||
domain,
|
domain,
|
||||||
}: {
|
}: {
|
||||||
deployment: Awaited<ReturnType<typeof findAllDeployments>>[0];
|
deployment: Awaited<ReturnType<typeof findAllDeployments>>[0];
|
||||||
domain: string;
|
domain: string;
|
||||||
}) {
|
}) {
|
||||||
const workflowInput = getInputsFromWorkflow(deployment.version);
|
const workflowInput = getInputsFromWorkflow(deployment.version);
|
||||||
|
|
||||||
if (deployment.environment === "public-share") {
|
if (deployment.environment === "public-share") {
|
||||||
return <SharePageDeploymentRow deployment={deployment} />;
|
return <SharePageDeploymentRow deployment={deployment} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog>
|
<Dialog>
|
||||||
<DialogTrigger asChild className="appearance-none hover:cursor-pointer">
|
<DialogTrigger asChild className="appearance-none hover:cursor-pointer">
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<DeploymentRow deployment={deployment} />
|
<DeploymentRow deployment={deployment} />
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
<DialogContent className="max-w-3xl">
|
<DialogContent className="max-w-3xl">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle className="capitalize">
|
<DialogTitle className="capitalize">
|
||||||
{deployment.environment} Deployment
|
{deployment.environment} Deployment
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription>Code for your deployment client</DialogDescription>
|
<DialogDescription>Code for your deployment client</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<ScrollArea className="max-h-[600px] pr-4">
|
<ScrollArea className="max-h-[600px] pr-4">
|
||||||
<Tabs defaultValue="client" className="w-full gap-2 text-sm">
|
<Tabs defaultValue="client" className="w-full gap-2 text-sm">
|
||||||
<TabsList className="grid w-fit grid-cols-3 mb-2">
|
<TabsList className="grid w-fit grid-cols-3 mb-2">
|
||||||
<TabsTrigger value="client">Server Client</TabsTrigger>
|
<TabsTrigger value="client">Server Client</TabsTrigger>
|
||||||
<TabsTrigger value="js">NodeJS Fetch</TabsTrigger>
|
<TabsTrigger value="js">NodeJS Fetch</TabsTrigger>
|
||||||
<TabsTrigger value="curl">CURL</TabsTrigger>
|
<TabsTrigger value="curl">CURL</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
<TabsContent className="flex flex-col gap-2 !mt-0" value="client">
|
<TabsContent className="flex flex-col gap-2 !mt-0" value="client">
|
||||||
<div>
|
<div>
|
||||||
Copy and paste the ComfyDeployClient form
|
Copy and paste the ComfyDeployClient form
|
||||||
<a
|
<a
|
||||||
href="https://github.com/BennyKok/comfyui-deploy-next-example/blob/main/src/lib/comfy-deploy.ts"
|
href="https://github.com/BennyKok/comfyui-deploy-next-example/blob/main/src/lib/comfy-deploy.ts"
|
||||||
className="text-blue-500 hover:underline"
|
className="text-blue-500 hover:underline"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noreferrer"
|
rel="noreferrer"
|
||||||
>
|
>
|
||||||
here
|
here
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
<CodeBlock
|
<CodeBlock
|
||||||
lang="js"
|
lang="js"
|
||||||
code={formatCode(
|
code={formatCode(
|
||||||
domain == "https://www.comfydeploy.com"
|
domain == "https://www.comfydeploy.com"
|
||||||
? jsClientSetupTemplateHostedVersion
|
? jsClientSetupTemplateHostedVersion
|
||||||
: jsClientSetupTemplate,
|
: jsClientSetupTemplate,
|
||||||
deployment,
|
deployment,
|
||||||
domain,
|
domain,
|
||||||
workflowInput,
|
workflowInput,
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
Create a run via deployment id
|
Create a run via deployment id
|
||||||
<CodeBlock
|
<CodeBlock
|
||||||
lang="js"
|
lang="js"
|
||||||
code={formatCode(
|
code={formatCode(
|
||||||
workflowInput && workflowInput.length > 0
|
workflowInput && workflowInput.length > 0
|
||||||
? jsClientCreateRunTemplate
|
? jsClientCreateRunTemplate
|
||||||
: jsClientCreateRunNoInputsTemplate,
|
: jsClientCreateRunNoInputsTemplate,
|
||||||
deployment,
|
deployment,
|
||||||
domain,
|
domain,
|
||||||
workflowInput,
|
workflowInput,
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
Check the status of the run, and retrieve the outputs
|
Check the status of the run, and retrieve the outputs
|
||||||
<CodeBlock
|
<CodeBlock
|
||||||
lang="js"
|
lang="js"
|
||||||
code={formatCode(
|
code={formatCode(
|
||||||
clientTemplate_checkStatus,
|
clientTemplate_checkStatus,
|
||||||
deployment,
|
deployment,
|
||||||
domain,
|
domain,
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
<TabsContent className="flex flex-col gap-2 !mt-0" value="js">
|
<TabsContent className="flex flex-col gap-2 !mt-0" value="js">
|
||||||
Trigger the workflow
|
Trigger the workflow
|
||||||
<CodeBlock
|
<CodeBlock
|
||||||
lang="js"
|
lang="js"
|
||||||
code={formatCode(jsTemplate, deployment, domain, workflowInput)}
|
code={formatCode(jsTemplate, deployment, domain, workflowInput)}
|
||||||
/>
|
/>
|
||||||
Check the status of the run, and retrieve the outputs
|
Check the status of the run, and retrieve the outputs
|
||||||
<CodeBlock
|
<CodeBlock
|
||||||
lang="js"
|
lang="js"
|
||||||
code={formatCode(jsTemplate_checkStatus, deployment, domain)}
|
code={formatCode(jsTemplate_checkStatus, deployment, domain)}
|
||||||
/>
|
/>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
<TabsContent className="flex flex-col gap-2 !mt-2" value="curl">
|
<TabsContent className="flex flex-col gap-2 !mt-2" value="curl">
|
||||||
<CodeBlock
|
<CodeBlock
|
||||||
lang="bash"
|
lang="bash"
|
||||||
code={formatCode(curlTemplate, deployment, domain)}
|
code={formatCode(curlTemplate, deployment, domain)}
|
||||||
/>
|
/>
|
||||||
<CodeBlock
|
<CodeBlock
|
||||||
lang="bash"
|
lang="bash"
|
||||||
code={formatCode(curlTemplate_checkStatus, deployment, domain)}
|
code={formatCode(curlTemplate_checkStatus, deployment, domain)}
|
||||||
/>
|
/>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatCode(
|
function formatCode(
|
||||||
codeTemplate: string,
|
codeTemplate: string,
|
||||||
deployment: Awaited<ReturnType<typeof findAllDeployments>>[0],
|
deployment: Awaited<ReturnType<typeof findAllDeployments>>[0],
|
||||||
domain: string,
|
domain: string,
|
||||||
inputs?: ReturnType<typeof getInputsFromWorkflow>,
|
inputs?: ReturnType<typeof getInputsFromWorkflow>,
|
||||||
inputsTabs?: number,
|
inputsTabs?: number,
|
||||||
) {
|
) {
|
||||||
if (inputs && inputs.length > 0) {
|
if (inputs && inputs.length > 0) {
|
||||||
codeTemplate = codeTemplate.replace(
|
codeTemplate = codeTemplate.replace(
|
||||||
"inputs: {}",
|
"inputs: {}",
|
||||||
`inputs: ${JSON.stringify(
|
`inputs: ${JSON.stringify(
|
||||||
Object.fromEntries(
|
Object.fromEntries(
|
||||||
inputs.map((x) => {
|
inputs.map((x) => {
|
||||||
return [x?.input_id, ""];
|
return [x?.input_id, ""];
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
null,
|
null,
|
||||||
2,
|
2,
|
||||||
)
|
)
|
||||||
.split("\n")
|
.split("\n")
|
||||||
.map((line, index) => (index === 0 ? line : ` ${line}`)) // Add two spaces indentation except for the first line
|
.map((line, index) => (index === 0 ? line : ` ${line}`)) // Add two spaces indentation except for the first line
|
||||||
.join("\n")}`,
|
.join("\n")}`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
codeTemplate = codeTemplate.replace(
|
codeTemplate = codeTemplate.replace(
|
||||||
`
|
`
|
||||||
inputs: {}`,
|
inputs: {}`,
|
||||||
"",
|
"",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return codeTemplate
|
return codeTemplate
|
||||||
.replace("<URL>", `${domain ?? "http://localhost:3000"}/api/run`)
|
.replace("<URL>", `${domain ?? "http://localhost:3000"}/api/run`)
|
||||||
.replace("<ID>", deployment.id)
|
.replace("<ID>", deployment.id)
|
||||||
.replace("<URLONLY>", domain ?? "http://localhost:3000");
|
.replace("<URLONLY>", domain ?? "http://localhost:3000");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ import {
|
|||||||
} from "@clerk/nextjs";
|
} from "@clerk/nextjs";
|
||||||
import { Github, Menu } from "lucide-react";
|
import { Github, Menu } from "lucide-react";
|
||||||
import meta from "next-gen/config";
|
import meta from "next-gen/config";
|
||||||
import { useFeatureFlagEnabled } from "posthog-js/react";
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useMediaQuery } from "usehooks-ts";
|
import { useMediaQuery } from "usehooks-ts";
|
||||||
|
|
||||||
@@ -30,18 +29,15 @@ export function Navbar() {
|
|||||||
const { organization } = useOrganization();
|
const { organization } = useOrganization();
|
||||||
const _isDesktop = useMediaQuery("(min-width: 1024px)");
|
const _isDesktop = useMediaQuery("(min-width: 1024px)");
|
||||||
const [isDesktop, setIsDesktop] = useState(true);
|
const [isDesktop, setIsDesktop] = useState(true);
|
||||||
|
const [isSheetOpen, setSheetOpen] = useState(false);
|
||||||
const pricingPlanFlagEnable = useFeatureFlagEnabled("pricing-plan");
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setIsDesktop(_isDesktop);
|
setIsDesktop(_isDesktop);
|
||||||
}, [_isDesktop]);
|
}, [_isDesktop]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="flex flex-row items-center gap-4">
|
<div className="flex flex-row items-center gap-4">
|
||||||
{!isDesktop && (
|
{!isDesktop && (
|
||||||
<Sheet>
|
<Sheet open={isSheetOpen} onOpenChange={(open) => setSheetOpen(open)}>
|
||||||
<SheetTrigger asChild>
|
<SheetTrigger asChild>
|
||||||
<button className="flex items-center justify-center w-8 h-8 p-2">
|
<button className="flex items-center justify-center w-8 h-8 p-2">
|
||||||
<Menu />
|
<Menu />
|
||||||
@@ -52,7 +48,10 @@ export function Navbar() {
|
|||||||
<SheetTitle className="text-start">Comfy Deploy</SheetTitle>
|
<SheetTitle className="text-start">Comfy Deploy</SheetTitle>
|
||||||
</SheetHeader>
|
</SheetHeader>
|
||||||
<div className="grid h-full grid-rows-[1fr_auto]">
|
<div className="grid h-full grid-rows-[1fr_auto]">
|
||||||
<NavbarMenu className=" h-full" />
|
<NavbarMenu
|
||||||
|
className=" h-full"
|
||||||
|
closeSheet={() => setSheetOpen(false)}
|
||||||
|
/>
|
||||||
{/* <OrganizationSwitcher
|
{/* <OrganizationSwitcher
|
||||||
appearance={{
|
appearance={{
|
||||||
elements: {
|
elements: {
|
||||||
@@ -90,15 +89,6 @@ export function Navbar() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex flex-row items-center gap-2">
|
<div className="flex flex-row items-center gap-2">
|
||||||
{isDesktop && <NavbarMenu />}
|
{isDesktop && <NavbarMenu />}
|
||||||
{pricingPlanFlagEnable && (
|
|
||||||
<Button
|
|
||||||
asChild
|
|
||||||
variant="link"
|
|
||||||
className="rounded-full aspect-square p-2 mr-4"
|
|
||||||
>
|
|
||||||
<a href="/pricing">Pricing</a>
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
<Button
|
||||||
asChild
|
asChild
|
||||||
variant="link"
|
variant="link"
|
||||||
@@ -112,11 +102,7 @@ export function Navbar() {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
className="rounded-full aspect-square p-2"
|
className="rounded-full aspect-square p-2"
|
||||||
>
|
>
|
||||||
<a
|
<a target="_blank" href="https://github.com/BennyKok/comfyui-deploy" rel="noreferrer">
|
||||||
target="_blank"
|
|
||||||
href="https://github.com/BennyKok/comfyui-deploy"
|
|
||||||
rel="noreferrer"
|
|
||||||
>
|
|
||||||
<Github />
|
<Github />
|
||||||
</a>
|
</a>
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -9,7 +9,13 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useMediaQuery } from "usehooks-ts";
|
import { useMediaQuery } from "usehooks-ts";
|
||||||
|
|
||||||
export function NavbarMenu({ className }: { className?: string }) {
|
export function NavbarMenu({
|
||||||
|
className,
|
||||||
|
closeSheet,
|
||||||
|
}: {
|
||||||
|
className?: string;
|
||||||
|
closeSheet?: () => void;
|
||||||
|
}) {
|
||||||
const _isDesktop = useMediaQuery("(min-width: 1024px)");
|
const _isDesktop = useMediaQuery("(min-width: 1024px)");
|
||||||
const [isDesktop, setIsDesktop] = useState(true);
|
const [isDesktop, setIsDesktop] = useState(true);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -34,6 +40,10 @@ export function NavbarMenu({ className }: { className?: string }) {
|
|||||||
name: "API Keys",
|
name: "API Keys",
|
||||||
path: "/api-keys",
|
path: "/api-keys",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "Examples",
|
||||||
|
path: "/examples"
|
||||||
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -42,9 +52,9 @@ export function NavbarMenu({ className }: { className?: string }) {
|
|||||||
{isDesktop && (
|
{isDesktop && (
|
||||||
<Tabs
|
<Tabs
|
||||||
defaultValue={pathname}
|
defaultValue={pathname}
|
||||||
className="w-[300px] flex pointer-events-auto"
|
className="w-fit flex pointer-events-auto"
|
||||||
>
|
>
|
||||||
<TabsList className="grid w-full grid-cols-3">
|
<TabsList className="w-full">
|
||||||
{pages.map((page) => (
|
{pages.map((page) => (
|
||||||
<TabsTrigger
|
<TabsTrigger
|
||||||
key={page.name}
|
key={page.name}
|
||||||
@@ -68,6 +78,9 @@ export function NavbarMenu({ className }: { className?: string }) {
|
|||||||
<Link
|
<Link
|
||||||
key={page.name}
|
key={page.name}
|
||||||
href={page.path}
|
href={page.path}
|
||||||
|
onClick={() => {
|
||||||
|
if (!!closeSheet) closeSheet();
|
||||||
|
}}
|
||||||
className="p-2 hover:bg-gray-100/20 hover:underline"
|
className="p-2 hover:bg-gray-100/20 hover:underline"
|
||||||
>
|
>
|
||||||
{page.name}
|
{page.name}
|
||||||
|
|||||||
@@ -5,6 +5,20 @@ export async function OutputRender(props: {
|
|||||||
run_id: string;
|
run_id: string;
|
||||||
filename: string;
|
filename: string;
|
||||||
}) {
|
}) {
|
||||||
|
if (props.filename.endsWith(".mp4") || props.filename.endsWith(".webm")) {
|
||||||
|
const url = await getFileDownloadUrl(
|
||||||
|
`outputs/runs/${props.run_id}/${props.filename}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<video controls autoPlay className="w-[400px]">
|
||||||
|
<source src={url} type="video/mp4" />
|
||||||
|
<source src={url} type="video/webm" />
|
||||||
|
Your browser does not support the video tag.
|
||||||
|
</video>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
props.filename.endsWith(".png") ||
|
props.filename.endsWith(".png") ||
|
||||||
props.filename.endsWith(".gif") ||
|
props.filename.endsWith(".gif") ||
|
||||||
@@ -12,13 +26,13 @@ export async function OutputRender(props: {
|
|||||||
props.filename.endsWith(".jpeg")
|
props.filename.endsWith(".jpeg")
|
||||||
) {
|
) {
|
||||||
const url = await getFileDownloadUrl(
|
const url = await getFileDownloadUrl(
|
||||||
`outputs/runs/${props.run_id}/${props.filename}`
|
`outputs/runs/${props.run_id}/${props.filename}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
return <img className="max-w-[200px]" alt={props.filename} src={url} />;
|
return <img className="max-w-[200px]" alt={props.filename} src={url} />;
|
||||||
} else {
|
} else {
|
||||||
const url = await getFileDownloadUrl(
|
const url = await getFileDownloadUrl(
|
||||||
`outputs/runs/${props.run_id}/${props.filename}`
|
`outputs/runs/${props.run_id}/${props.filename}`,
|
||||||
);
|
);
|
||||||
// console.log(url);
|
// console.log(url);
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,14 @@ import { checkStatus, createRun } from "@/server/createRun";
|
|||||||
import { createDeployments } from "@/server/curdDeploments";
|
import { createDeployments } from "@/server/curdDeploments";
|
||||||
import type { getMachines } from "@/server/curdMachine";
|
import type { getMachines } from "@/server/curdMachine";
|
||||||
import type { findFirstTableWithVersion } from "@/server/findFirstTableWithVersion";
|
import type { findFirstTableWithVersion } from "@/server/findFirstTableWithVersion";
|
||||||
import { Copy, ExternalLink, Info, MoreVertical, Play } from "lucide-react";
|
import {
|
||||||
|
Copy,
|
||||||
|
Edit,
|
||||||
|
ExternalLink,
|
||||||
|
Info,
|
||||||
|
MoreVertical,
|
||||||
|
Play,
|
||||||
|
} from "lucide-react";
|
||||||
import { parseAsInteger, useQueryState } from "next-usequerystate";
|
import { parseAsInteger, useQueryState } from "next-usequerystate";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
@@ -51,6 +58,9 @@ import { create } from "zustand";
|
|||||||
import { workflowVersionInputsToZod } from "../lib/workflowVersionInputsToZod";
|
import { workflowVersionInputsToZod } from "../lib/workflowVersionInputsToZod";
|
||||||
import { callServerPromise } from "./callServerPromise";
|
import { callServerPromise } from "./callServerPromise";
|
||||||
import fetcher from "./fetcher";
|
import fetcher from "./fetcher";
|
||||||
|
import { ButtonAction } from "@/components/ButtonActionLoader";
|
||||||
|
import { editWorkflowOnMachine } from "@/server/editWorkflowOnMachine";
|
||||||
|
import { VisualizeImagesGrid } from "@/components/VisualizeImagesGrid";
|
||||||
|
|
||||||
export function VersionSelect({
|
export function VersionSelect({
|
||||||
workflow,
|
workflow,
|
||||||
@@ -115,30 +125,66 @@ export function MachineSelect({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useSelectedMachine(
|
type SelectedMachineStore = {
|
||||||
machines: Awaited<ReturnType<typeof getMachines>>,
|
selectedMachine: string | undefined;
|
||||||
) {
|
setSelectedMachine: (machine: string) => void;
|
||||||
const a = useQueryState("machine", {
|
};
|
||||||
defaultValue: machines?.[0]?.id ?? "",
|
|
||||||
});
|
|
||||||
|
|
||||||
return a;
|
export const selectedMachineStore = create<SelectedMachineStore>((set) => ({
|
||||||
|
selectedMachine: undefined,
|
||||||
|
setSelectedMachine: (machine) => set(() => ({ selectedMachine: machine })),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export function useSelectedMachine(
|
||||||
|
machines: Awaited<ReturnType<typeof getMachines>>,
|
||||||
|
): [string, (v: string) => void] {
|
||||||
|
const { selectedMachine, setSelectedMachine } = selectedMachineStore();
|
||||||
|
return [selectedMachine ?? machines?.[0]?.id ?? "", setSelectedMachine];
|
||||||
|
|
||||||
|
// const searchParams = useSearchParams();
|
||||||
|
// const pathname = usePathname();
|
||||||
|
// const router = useRouter();
|
||||||
|
|
||||||
|
// const createQueryString = useCallback(
|
||||||
|
// (name: string, value: string) => {
|
||||||
|
// const params = new URLSearchParams(searchParams.toString());
|
||||||
|
// params.set(name, value);
|
||||||
|
|
||||||
|
// return params.toString();
|
||||||
|
// },
|
||||||
|
// [searchParams],
|
||||||
|
// );
|
||||||
|
|
||||||
|
// return [
|
||||||
|
// searchParams.get("machine") ?? machines?.[0]?.id ?? "",
|
||||||
|
// (v: string) => {
|
||||||
|
// // window.history.pushState(
|
||||||
|
// // "new url",
|
||||||
|
// // "",
|
||||||
|
// // pathname + "?" + createQueryString("machine", v),
|
||||||
|
// // );
|
||||||
|
// // router.push(pathname + "?" + createQueryString("machine", v));
|
||||||
|
// router.replace(pathname + "?" + createQueryString("machine", v));
|
||||||
|
// },
|
||||||
|
// ];
|
||||||
}
|
}
|
||||||
|
|
||||||
type PublicRunStore = {
|
type PublicRunStore = {
|
||||||
image: string;
|
image: {
|
||||||
|
url: string;
|
||||||
|
}[] | null;
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
runId: string;
|
runId: string;
|
||||||
status: string;
|
status: string;
|
||||||
|
|
||||||
setImage: (image: string) => void;
|
setImage: (image: { url: string; }[]) => void;
|
||||||
setLoading: (loading: boolean) => void;
|
setLoading: (loading: boolean) => void;
|
||||||
setRunId: (runId: string) => void;
|
setRunId: (runId: string) => void;
|
||||||
setStatus: (status: string) => void;
|
setStatus: (status: string) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const publicRunStore = create<PublicRunStore>((set) => ({
|
export const publicRunStore = create<PublicRunStore>((set) => ({
|
||||||
image: "",
|
image: null,
|
||||||
loading: false,
|
loading: false,
|
||||||
runId: "",
|
runId: "",
|
||||||
status: "",
|
status: "",
|
||||||
@@ -162,7 +208,10 @@ export function PublicRunOutputs(props: {
|
|||||||
console.log(res?.status);
|
console.log(res?.status);
|
||||||
if (res) setStatus(res.status);
|
if (res) setStatus(res.status);
|
||||||
if (res && res.status === "success") {
|
if (res && res.status === "success") {
|
||||||
setImage(res.outputs[0]?.data.images[0].url);
|
const imageURLs = res.outputs[0]?.data.images.map((item: { url: string; }) => {
|
||||||
|
return { url: item.url };
|
||||||
|
});
|
||||||
|
setImage(imageURLs);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
clearInterval(interval);
|
clearInterval(interval);
|
||||||
}
|
}
|
||||||
@@ -171,30 +220,25 @@ export function PublicRunOutputs(props: {
|
|||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, [runId]);
|
}, [runId]);
|
||||||
|
|
||||||
return (
|
if (loading) {
|
||||||
<div className="border border-gray-200 w-full square h-[400px] rounded-lg relative">
|
return (
|
||||||
{!loading && !image && props.preview && props.preview.length > 0 && (
|
<div className="border border-gray-200 w-full h-[400px] square rounded-lg relative p-4 ">
|
||||||
<>
|
|
||||||
<img
|
|
||||||
className="w-full h-full object-contain"
|
|
||||||
src={props.preview[0]?.url}
|
|
||||||
alt="Generated image"
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{!loading && image && (
|
|
||||||
<img
|
|
||||||
className="w-full h-full object-contain"
|
|
||||||
src={image}
|
|
||||||
alt="Generated image"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{loading && (
|
|
||||||
<div className="absolute top-0 left-0 w-full h-full flex items-center justify-center gap-2">
|
<div className="absolute top-0 left-0 w-full h-full flex items-center justify-center gap-2">
|
||||||
{status} <LoadingIcon />
|
{status} <LoadingIcon />
|
||||||
</div>
|
</div>
|
||||||
|
<Skeleton className="w-full h-full" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border border-gray-200 w-full min-h-[400px] square rounded-lg relative p-4 ">
|
||||||
|
{!image && props.preview && props.preview.length > 0 &&
|
||||||
|
<VisualizeImagesGrid images={props.preview} />
|
||||||
|
}
|
||||||
|
{image && (
|
||||||
|
<VisualizeImagesGrid images={image} />
|
||||||
)}
|
)}
|
||||||
{loading && <Skeleton className="w-full h-full" />}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -219,7 +263,7 @@ export function RunWorkflowButton({
|
|||||||
const schema = useMemo(() => {
|
const schema = useMemo(() => {
|
||||||
const workflow_version = getWorkflowVersionFromVersionIndex(
|
const workflow_version = getWorkflowVersionFromVersionIndex(
|
||||||
workflow,
|
workflow,
|
||||||
version
|
version,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!workflow_version) return null;
|
if (!workflow_version) return null;
|
||||||
@@ -233,7 +277,7 @@ export function RunWorkflowButton({
|
|||||||
const val = Object.keys(values).length > 0 ? values : undefined;
|
const val = Object.keys(values).length > 0 ? values : undefined;
|
||||||
|
|
||||||
const workflow_version_id = workflow?.versions.find(
|
const workflow_version_id = workflow?.versions.find(
|
||||||
(x) => x.version === version
|
(x) => x.version === version,
|
||||||
)?.id;
|
)?.id;
|
||||||
console.log(workflow_version_id);
|
console.log(workflow_version_id);
|
||||||
if (!workflow_version_id) return;
|
if (!workflow_version_id) return;
|
||||||
@@ -248,7 +292,7 @@ export function RunWorkflowButton({
|
|||||||
machine_id: machine,
|
machine_id: machine,
|
||||||
inputs: val,
|
inputs: val,
|
||||||
runOrigin: "manual",
|
runOrigin: "manual",
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
// console.log(res.json());
|
// console.log(res.json());
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
@@ -285,7 +329,7 @@ export function RunWorkflowButton({
|
|||||||
className="px-1"
|
className="px-1"
|
||||||
>
|
>
|
||||||
<div className="flex justify-end">
|
<div className="flex justify-end">
|
||||||
<AutoFormSubmit>
|
<AutoFormSubmit disabled={isLoading}>
|
||||||
Run
|
Run
|
||||||
{isLoading ? <LoadingIcon /> : <Play size={14} />}
|
{isLoading ? <LoadingIcon /> : <Play size={14} />}
|
||||||
</AutoFormSubmit>
|
</AutoFormSubmit>
|
||||||
@@ -317,7 +361,7 @@ export function CreateDeploymentButton({
|
|||||||
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const workflow_version_id = workflow?.versions.find(
|
const workflow_version_id = workflow?.versions.find(
|
||||||
(x) => x.version === version
|
(x) => x.version === version,
|
||||||
)?.id;
|
)?.id;
|
||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -337,8 +381,8 @@ export function CreateDeploymentButton({
|
|||||||
workflow.id,
|
workflow.id,
|
||||||
workflow_version_id,
|
workflow_version_id,
|
||||||
machine,
|
machine,
|
||||||
"production"
|
"production",
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}}
|
}}
|
||||||
@@ -355,8 +399,8 @@ export function CreateDeploymentButton({
|
|||||||
workflow.id,
|
workflow.id,
|
||||||
workflow_version_id,
|
workflow_version_id,
|
||||||
machine,
|
machine,
|
||||||
"staging"
|
"staging",
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}}
|
}}
|
||||||
@@ -368,6 +412,49 @@ export function CreateDeploymentButton({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function OpenEditButton({
|
||||||
|
workflow,
|
||||||
|
machines,
|
||||||
|
}: {
|
||||||
|
workflow: Awaited<ReturnType<typeof findFirstTableWithVersion>>;
|
||||||
|
machines: Awaited<ReturnType<typeof getMachines>>;
|
||||||
|
}) {
|
||||||
|
const [version] = useQueryState("version", {
|
||||||
|
defaultValue: workflow?.versions[0].version ?? 1,
|
||||||
|
...parseAsInteger,
|
||||||
|
});
|
||||||
|
const [machine] = useSelectedMachine(machines);
|
||||||
|
const workflow_version_id = workflow?.versions.find(
|
||||||
|
(x) => x.version == version,
|
||||||
|
)?.id;
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
workflow_version_id &&
|
||||||
|
machine && (
|
||||||
|
<Button
|
||||||
|
className="gap-2"
|
||||||
|
onClick={async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
const url = await callServerPromise(
|
||||||
|
editWorkflowOnMachine(workflow_version_id, machine),
|
||||||
|
);
|
||||||
|
if (url && typeof url !== "object") {
|
||||||
|
window.open(url, "_blank");
|
||||||
|
} else if (url && typeof url === "object" && url.error) {
|
||||||
|
console.error(url.error);
|
||||||
|
}
|
||||||
|
setIsLoading(false);
|
||||||
|
}}
|
||||||
|
// asChild
|
||||||
|
variant="outline"
|
||||||
|
>
|
||||||
|
Edit {isLoading ? <LoadingIcon /> : <Edit size={14} />}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function CopyWorkflowVersion({
|
export function CopyWorkflowVersion({
|
||||||
workflow,
|
workflow,
|
||||||
}: {
|
}: {
|
||||||
@@ -378,7 +465,7 @@ export function CopyWorkflowVersion({
|
|||||||
...parseAsInteger,
|
...parseAsInteger,
|
||||||
});
|
});
|
||||||
const workflow_version = workflow?.versions.find(
|
const workflow_version = workflow?.versions.find(
|
||||||
(x) => x.version === version
|
(x) => x.version === version,
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -402,7 +489,7 @@ export function CopyWorkflowVersion({
|
|||||||
});
|
});
|
||||||
|
|
||||||
navigator.clipboard.writeText(
|
navigator.clipboard.writeText(
|
||||||
JSON.stringify(workflow_version?.workflow)
|
JSON.stringify(workflow_version?.workflow),
|
||||||
);
|
);
|
||||||
toast("Copied to clipboard");
|
toast("Copied to clipboard");
|
||||||
}}
|
}}
|
||||||
@@ -412,7 +499,7 @@ export function CopyWorkflowVersion({
|
|||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
navigator.clipboard.writeText(
|
navigator.clipboard.writeText(
|
||||||
JSON.stringify(workflow_version?.workflow_api)
|
JSON.stringify(workflow_version?.workflow_api),
|
||||||
);
|
);
|
||||||
toast("Copied to clipboard");
|
toast("Copied to clipboard");
|
||||||
}}
|
}}
|
||||||
@@ -426,7 +513,7 @@ export function CopyWorkflowVersion({
|
|||||||
|
|
||||||
export function getWorkflowVersionFromVersionIndex(
|
export function getWorkflowVersionFromVersionIndex(
|
||||||
workflow: Awaited<ReturnType<typeof findFirstTableWithVersion>>,
|
workflow: Awaited<ReturnType<typeof findFirstTableWithVersion>>,
|
||||||
version: number
|
version: number,
|
||||||
) {
|
) {
|
||||||
const workflow_version = workflow?.versions.find((x) => x.version == version);
|
const workflow_version = workflow?.versions.find((x) => x.version == version);
|
||||||
|
|
||||||
@@ -452,7 +539,7 @@ export function ViewWorkflowDetailsButton({
|
|||||||
isLoading: isNodesIndexLoading,
|
isLoading: isNodesIndexLoading,
|
||||||
} = useSWR(
|
} = useSWR(
|
||||||
"https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json",
|
"https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json",
|
||||||
fetcher
|
fetcher,
|
||||||
);
|
);
|
||||||
|
|
||||||
const groupedByAuxName = useMemo(() => {
|
const groupedByAuxName = useMemo(() => {
|
||||||
@@ -462,7 +549,7 @@ export function ViewWorkflowDetailsButton({
|
|||||||
|
|
||||||
const workflow_version = getWorkflowVersionFromVersionIndex(
|
const workflow_version = getWorkflowVersionFromVersionIndex(
|
||||||
workflow,
|
workflow,
|
||||||
version
|
version,
|
||||||
);
|
);
|
||||||
|
|
||||||
const api = workflow_version?.workflow_api;
|
const api = workflow_version?.workflow_api;
|
||||||
@@ -473,7 +560,7 @@ export function ViewWorkflowDetailsButton({
|
|||||||
.map(([_, value]) => {
|
.map(([_, value]) => {
|
||||||
const classType = value.class_type;
|
const classType = value.class_type;
|
||||||
const classTypeData = Object.entries(data).find(([_, nodeArray]) =>
|
const classTypeData = Object.entries(data).find(([_, nodeArray]) =>
|
||||||
nodeArray[0].includes(classType)
|
nodeArray[0].includes(classType),
|
||||||
);
|
);
|
||||||
return classTypeData ? { node: value, classTypeData } : null;
|
return classTypeData ? { node: value, classTypeData } : null;
|
||||||
})
|
})
|
||||||
@@ -503,7 +590,7 @@ export function ViewWorkflowDetailsButton({
|
|||||||
node: z.infer<typeof workflowAPINodeType>[];
|
node: z.infer<typeof workflowAPINodeType>[];
|
||||||
url: string;
|
url: string;
|
||||||
}
|
}
|
||||||
>
|
>,
|
||||||
);
|
);
|
||||||
|
|
||||||
// console.log(groupedByAuxName);
|
// console.log(groupedByAuxName);
|
||||||
@@ -544,7 +631,8 @@ export function ViewWorkflowDetailsButton({
|
|||||||
<a
|
<a
|
||||||
href={group.url}
|
href={group.url}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
className="hover:underline" rel="noreferrer"
|
className="hover:underline"
|
||||||
|
rel="noreferrer"
|
||||||
>
|
>
|
||||||
{key}
|
{key}
|
||||||
<ExternalLink
|
<ExternalLink
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
type imagesType = {
|
||||||
|
url: string;
|
||||||
|
width?: number;
|
||||||
|
height?: number;
|
||||||
|
};
|
||||||
|
type VisualizeImagesGridProps = {
|
||||||
|
images: imagesType[];
|
||||||
|
layout?: 'justify-between' | 'justify-center' | 'justify-start' | 'justify-end';
|
||||||
|
};
|
||||||
|
export function VisualizeImagesGrid({ images, layout }: VisualizeImagesGridProps) {
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex gap-4 flex-wrap ${layout || 'justify-center'}`}>
|
||||||
|
<>
|
||||||
|
{images && images.length > 0 &&
|
||||||
|
images.map(item => {
|
||||||
|
if (!item) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (item?.url.endsWith(".mp4") || item?.url.endsWith(".webm")) {
|
||||||
|
return (
|
||||||
|
<video key={item?.url} controls autoPlay className="rounded-xl" style={{ maxHeight: item.height || 370, maxWidth: item.width || "auto" }}>
|
||||||
|
<source src={item?.url} type="video/mp4" />
|
||||||
|
<source src={item?.url} type="video/webm" />
|
||||||
|
Your browser does not support the video tag.
|
||||||
|
</video>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return <img
|
||||||
|
key={item?.url}
|
||||||
|
className="object-contain overflow-hidden rounded-xl"
|
||||||
|
src={item?.url}
|
||||||
|
alt="Generated image"
|
||||||
|
style={{ maxHeight: item.height || 370, maxWidth: item.width || "auto" }}
|
||||||
|
/>;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -21,8 +21,8 @@ import {
|
|||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "@/components/ui/table";
|
} from "@/components/ui/table";
|
||||||
|
import { getAllUserWorkflow } from "@/server/crudWorkflow";
|
||||||
import { deleteWorkflow } from "@/server/deleteWorkflow";
|
import { deleteWorkflow } from "@/server/deleteWorkflow";
|
||||||
import type { getAllUserWorkflow } from "@/server/getAllUserWorkflow";
|
|
||||||
import type {
|
import type {
|
||||||
ColumnDef,
|
ColumnDef,
|
||||||
ColumnFiltersState,
|
ColumnFiltersState,
|
||||||
@@ -169,7 +169,7 @@ export const columns: ColumnDef<WorkflowItemList>[] = [
|
|||||||
export function WorkflowList({ data }: { data: WorkflowItemList[] }) {
|
export function WorkflowList({ data }: { data: WorkflowItemList[] }) {
|
||||||
const [sorting, setSorting] = React.useState<SortingState>([]);
|
const [sorting, setSorting] = React.useState<SortingState>([]);
|
||||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
|
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
|
||||||
[]
|
[],
|
||||||
);
|
);
|
||||||
const [columnVisibility, setColumnVisibility] =
|
const [columnVisibility, setColumnVisibility] =
|
||||||
React.useState<VisibilityState>({});
|
React.useState<VisibilityState>({});
|
||||||
@@ -218,7 +218,7 @@ export function WorkflowList({ data }: { data: WorkflowItemList[] }) {
|
|||||||
? null
|
? null
|
||||||
: flexRender(
|
: flexRender(
|
||||||
header.column.columnDef.header,
|
header.column.columnDef.header,
|
||||||
header.getContext()
|
header.getContext(),
|
||||||
)}
|
)}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
);
|
);
|
||||||
@@ -237,7 +237,7 @@ export function WorkflowList({ data }: { data: WorkflowItemList[] }) {
|
|||||||
<TableCell key={cell.id}>
|
<TableCell key={cell.id}>
|
||||||
{flexRender(
|
{flexRender(
|
||||||
cell.column.columnDef.cell,
|
cell.column.columnDef.cell,
|
||||||
cell.getContext()
|
cell.getContext(),
|
||||||
)}
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
export const customInputNodes: Record<string, string> = {
|
export const customInputNodes: Record<string, string> = {
|
||||||
ComfyUIDeployExternalText: "string",
|
ComfyUIDeployExternalText: "string",
|
||||||
ComfyUIDeployExternalImage: "string - (public image url)",
|
ComfyUIDeployExternalImage: "string - (public image url)",
|
||||||
ComfyUIDeployExternalImageAlpha: "string - (public image url)",
|
ComfyUIDeployExternalImageAlpha: "string - (public image url)",
|
||||||
ComfyUIDeployExternalNumber: "float",
|
ComfyUIDeployExternalNumber: "float",
|
||||||
ComfyUIDeployExternalNumberInt: "integer",
|
ComfyUIDeployExternalNumberInt: "integer",
|
||||||
ComfyUIDeployExternalLora: "string - (public lora download url)",
|
ComfyUIDeployExternalLora: "string - (public lora download url)",
|
||||||
ComfyUIDeployExternalCheckpoints:
|
ComfyUIDeployExternalCheckpoint: "string - (public checkpoints download url)",
|
||||||
"string - (public checkpoints download url)",
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as schema from "./schema";
|
import { Pool, neonConfig } from "@neondatabase/serverless";
|
||||||
import { neonConfig, Pool } from "@neondatabase/serverless";
|
|
||||||
import { drizzle as neonDrizzle } from "drizzle-orm/neon-serverless";
|
import { drizzle as neonDrizzle } from "drizzle-orm/neon-serverless";
|
||||||
|
import * as schema from "./schema";
|
||||||
|
|
||||||
const isDevContainer = process.env.REMOTE_CONTAINERS !== undefined;
|
const isDevContainer = process.env.REMOTE_CONTAINERS !== undefined;
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ if (process.env.VERCEL_ENV !== "production") {
|
|||||||
// Set the WebSocket proxy to work with the local instance
|
// Set the WebSocket proxy to work with the local instance
|
||||||
if (isDevContainer) {
|
if (isDevContainer) {
|
||||||
// Running inside a VS Code devcontainer
|
// Running inside a VS Code devcontainer
|
||||||
neonConfig.wsProxy = (host) => `host.docker.internal:5481/v1`;
|
neonConfig.wsProxy = (host) => "host.docker.internal:5481/v1";
|
||||||
} else {
|
} else {
|
||||||
// Not running inside a VS Code devcontainer
|
// Not running inside a VS Code devcontainer
|
||||||
neonConfig.wsProxy = (host) => `${host}:5481/v1`;
|
neonConfig.wsProxy = (host) => `${host}:5481/v1`;
|
||||||
@@ -26,5 +26,5 @@ export const db = neonDrizzle(
|
|||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
schema,
|
schema,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -8,9 +8,8 @@ import {
|
|||||||
text,
|
text,
|
||||||
timestamp,
|
timestamp,
|
||||||
uuid,
|
uuid,
|
||||||
real,
|
|
||||||
} from "drizzle-orm/pg-core";
|
} from "drizzle-orm/pg-core";
|
||||||
import { createInsertSchema } from "drizzle-zod";
|
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
export const dbSchema = pgSchema("comfyui_deploy");
|
export const dbSchema = pgSchema("comfyui_deploy");
|
||||||
@@ -36,6 +35,8 @@ export const workflowTable = dbSchema.table("workflows", {
|
|||||||
updated_at: timestamp("updated_at").defaultNow().notNull(),
|
updated_at: timestamp("updated_at").defaultNow().notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const workflowSchema = createSelectSchema(workflowTable);
|
||||||
|
|
||||||
export const workflowRelations = relations(workflowTable, ({ many, one }) => ({
|
export const workflowRelations = relations(workflowTable, ({ many, one }) => ({
|
||||||
user: one(usersTable, {
|
user: one(usersTable, {
|
||||||
fields: [workflowTable.user_id],
|
fields: [workflowTable.user_id],
|
||||||
@@ -80,6 +81,7 @@ export const workflowVersionTable = dbSchema.table("workflow_versions", {
|
|||||||
created_at: timestamp("created_at").defaultNow().notNull(),
|
created_at: timestamp("created_at").defaultNow().notNull(),
|
||||||
updated_at: timestamp("updated_at").defaultNow().notNull(),
|
updated_at: timestamp("updated_at").defaultNow().notNull(),
|
||||||
});
|
});
|
||||||
|
export const workflowVersionSchema = createSelectSchema(workflowVersionTable);
|
||||||
|
|
||||||
export const workflowVersionRelations = relations(
|
export const workflowVersionRelations = relations(
|
||||||
workflowVersionTable,
|
workflowVersionTable,
|
||||||
@@ -88,7 +90,7 @@ export const workflowVersionRelations = relations(
|
|||||||
fields: [workflowVersionTable.workflow_id],
|
fields: [workflowVersionTable.workflow_id],
|
||||||
references: [workflowTable.id],
|
references: [workflowTable.id],
|
||||||
}),
|
}),
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
export const workflowRunStatus = pgEnum("workflow_run_status", [
|
export const workflowRunStatus = pgEnum("workflow_run_status", [
|
||||||
@@ -137,7 +139,7 @@ export const workflowRunsTable = dbSchema.table("workflow_runs", {
|
|||||||
() => workflowVersionTable.id,
|
() => workflowVersionTable.id,
|
||||||
{
|
{
|
||||||
onDelete: "set null",
|
onDelete: "set null",
|
||||||
}
|
},
|
||||||
),
|
),
|
||||||
workflow_inputs:
|
workflow_inputs:
|
||||||
jsonb("workflow_inputs").$type<Record<string, string | number>>(),
|
jsonb("workflow_inputs").$type<Record<string, string | number>>(),
|
||||||
@@ -173,7 +175,7 @@ export const workflowRunRelations = relations(
|
|||||||
fields: [workflowRunsTable.workflow_id],
|
fields: [workflowRunsTable.workflow_id],
|
||||||
references: [workflowTable.id],
|
references: [workflowTable.id],
|
||||||
}),
|
}),
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// We still want to keep the workflow run record.
|
// We still want to keep the workflow run record.
|
||||||
@@ -197,7 +199,7 @@ export const workflowOutputRelations = relations(
|
|||||||
fields: [workflowRunOutputs.run_id],
|
fields: [workflowRunOutputs.run_id],
|
||||||
references: [workflowRunsTable.id],
|
references: [workflowRunsTable.id],
|
||||||
}),
|
}),
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// when user delete, also delete all the workflow versions
|
// when user delete, also delete all the workflow versions
|
||||||
@@ -230,7 +232,7 @@ export const snapshotType = z.object({
|
|||||||
z.object({
|
z.object({
|
||||||
hash: z.string(),
|
hash: z.string(),
|
||||||
disabled: z.boolean(),
|
disabled: z.boolean(),
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
file_custom_nodes: z.array(z.any()),
|
file_custom_nodes: z.array(z.any()),
|
||||||
});
|
});
|
||||||
@@ -245,7 +247,7 @@ export const showcaseMedia = z.array(
|
|||||||
z.object({
|
z.object({
|
||||||
url: z.string(),
|
url: z.string(),
|
||||||
isCover: z.boolean().default(false),
|
isCover: z.boolean().default(false),
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
export const showcaseMediaNullable = z
|
export const showcaseMediaNullable = z
|
||||||
@@ -253,7 +255,7 @@ export const showcaseMediaNullable = z
|
|||||||
z.object({
|
z.object({
|
||||||
url: z.string(),
|
url: z.string(),
|
||||||
isCover: z.boolean().default(false),
|
isCover: z.boolean().default(false),
|
||||||
})
|
}),
|
||||||
)
|
)
|
||||||
.nullable();
|
.nullable();
|
||||||
|
|
||||||
@@ -332,17 +334,14 @@ export const apiKeyTable = dbSchema.table("api_keys", {
|
|||||||
updated_at: timestamp("updated_at").defaultNow().notNull(),
|
updated_at: timestamp("updated_at").defaultNow().notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const userUsageTable = dbSchema.table("user_usage", {
|
export const authRequestsTable = dbSchema.table("auth_requests", {
|
||||||
id: uuid("id").primaryKey().defaultRandom().notNull(),
|
request_id: text("request_id").primaryKey().notNull(),
|
||||||
|
user_id: text("user_id"),
|
||||||
org_id: text("org_id"),
|
org_id: text("org_id"),
|
||||||
user_id: text("user_id")
|
api_hash: text("api_hash"),
|
||||||
.references(() => usersTable.id, {
|
|
||||||
onDelete: "cascade",
|
|
||||||
})
|
|
||||||
.notNull(),
|
|
||||||
usage_time: real("usage_time").default(0).notNull(),
|
|
||||||
created_at: timestamp("created_at").defaultNow().notNull(),
|
created_at: timestamp("created_at").defaultNow().notNull(),
|
||||||
ended_at: timestamp("ended_at").defaultNow().notNull(),
|
expired_date: timestamp("expired_date"),
|
||||||
|
updated_at: timestamp("updated_at").defaultNow().notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type UserType = InferSelectModel<typeof usersTable>;
|
export type UserType = InferSelectModel<typeof usersTable>;
|
||||||
@@ -350,4 +349,3 @@ export type WorkflowType = InferSelectModel<typeof workflowTable>;
|
|||||||
export type MachineType = InferSelectModel<typeof machinesTable>;
|
export type MachineType = InferSelectModel<typeof machinesTable>;
|
||||||
export type WorkflowVersionType = InferSelectModel<typeof workflowVersionTable>;
|
export type WorkflowVersionType = InferSelectModel<typeof workflowVersionTable>;
|
||||||
export type DeploymentType = InferSelectModel<typeof deploymentsTable>;
|
export type DeploymentType = InferSelectModel<typeof deploymentsTable>;
|
||||||
export type UserUsageType = InferSelectModel<typeof userUsageTable>;
|
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { customAlphabet } from "nanoid";
|
||||||
|
|
||||||
|
export const nanoid = customAlphabet(
|
||||||
|
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",
|
||||||
|
);
|
||||||
|
const prefixes = {
|
||||||
|
img: "img",
|
||||||
|
vid: "vid",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function newId(prefix: keyof typeof prefixes): string {
|
||||||
|
return [prefixes[prefix], nanoid(16)].join("_");
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { createRun } from "../server/createRun";
|
|
||||||
import { db } from "@/db/db";
|
import { db } from "@/db/db";
|
||||||
import { deploymentsTable } from "@/db/schema";
|
import { deploymentsTable } from "@/db/schema";
|
||||||
import type { App } from "@/routes/app";
|
import type { App } from "@/routes/app";
|
||||||
import { authError } from "@/routes/authError";
|
import { authError } from "@/routes/authError";
|
||||||
import { z, createRoute } from "@hono/zod-openapi";
|
import { createRoute, z } from "@hono/zod-openapi";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
|
import { createRun } from "../server/createRun";
|
||||||
|
|
||||||
const createRunRoute = createRoute({
|
const createRunRoute = createRoute({
|
||||||
method: "post",
|
method: "post",
|
||||||
@@ -99,7 +99,7 @@ export const registerCreateRunRoute = (app: App) => {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
status: 500,
|
status: 500,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import { db } from "@/db/db";
|
||||||
|
import { authRequestsTable } from "@/db/schema";
|
||||||
|
import type { App } from "@/routes/app";
|
||||||
|
import { authError } from "@/routes/authError";
|
||||||
|
import { z, createRoute } from "@hono/zod-openapi";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import jwt from "jsonwebtoken";
|
||||||
|
import crypto from "crypto";
|
||||||
|
import { getOrgOrUserDisplayName } from "@/server/getOrgOrUserDisplayName";
|
||||||
|
import ms from "ms";
|
||||||
|
|
||||||
|
const route = createRoute({
|
||||||
|
method: "get",
|
||||||
|
path: "/auth-response/:request_id",
|
||||||
|
tags: ["comfyui"],
|
||||||
|
summary: "Get an API Key with code",
|
||||||
|
description:
|
||||||
|
"This endpoints is specifically built for ComfyUI workflow upload.",
|
||||||
|
request: {
|
||||||
|
params: z.object({
|
||||||
|
request_id: z.string(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
200: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: z.object({
|
||||||
|
api_key: z.string(),
|
||||||
|
name: z.string(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
description: "The returned API Key",
|
||||||
|
},
|
||||||
|
201: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: z.object({
|
||||||
|
message: z.string(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
description: "The API key is not yet ready",
|
||||||
|
},
|
||||||
|
500: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: z.object({
|
||||||
|
error: z.string(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
description: "Error when fetching the API Key with code",
|
||||||
|
},
|
||||||
|
...authError,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const corsHeaders = {
|
||||||
|
"Access-Control-Allow-Origin": "*",
|
||||||
|
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
||||||
|
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const registerGetAuthResponse = (app: App) => {
|
||||||
|
return app.openapi(route, async (c) => {
|
||||||
|
const { request_id } = c.req.valid("param");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await db.query.authRequestsTable.findFirst({
|
||||||
|
where: eq(authRequestsTable.request_id, request_id),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result?.api_hash) {
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
message: "Already used.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 201,
|
||||||
|
headers: corsHeaders,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result && result.user_id) {
|
||||||
|
const expireTime = "1w";
|
||||||
|
const token = jwt.sign(
|
||||||
|
{ user_id: result.user_id, org_id: result.org_id },
|
||||||
|
process.env.JWT_SECRET!,
|
||||||
|
{
|
||||||
|
expiresIn: expireTime,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const hash = crypto.createHash("sha256").update(token).digest("hex");
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const expiryDate = new Date(now.getTime() + ms(expireTime));
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(authRequestsTable)
|
||||||
|
.set({
|
||||||
|
api_hash: hash,
|
||||||
|
expired_date: expiryDate,
|
||||||
|
})
|
||||||
|
.where(eq(authRequestsTable.request_id, request_id));
|
||||||
|
|
||||||
|
const userName = await getOrgOrUserDisplayName(
|
||||||
|
result.org_id,
|
||||||
|
result.user_id,
|
||||||
|
);
|
||||||
|
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
api_key: token,
|
||||||
|
name: userName,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 200,
|
||||||
|
headers: corsHeaders,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage =
|
||||||
|
error instanceof Error ? error.message : "Unknown error";
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error: errorMessage,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
statusText: "Invalid request",
|
||||||
|
status: 500,
|
||||||
|
headers: corsHeaders,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
message: "Not ready yet.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 201,
|
||||||
|
headers: corsHeaders,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { workflowVersionSchema, workflowVersionTable } from "@/db/schema";
|
||||||
|
import type { App } from "@/routes/app";
|
||||||
|
import { authError } from "@/routes/authError";
|
||||||
|
import { getWorkflowVersion } from "@/server/crudWorkflow";
|
||||||
|
import { z, createRoute } from "@hono/zod-openapi";
|
||||||
|
import { createSelectSchema } from "drizzle-zod";
|
||||||
|
|
||||||
|
const route = createRoute({
|
||||||
|
method: "get",
|
||||||
|
path: "/workflow-version/:version_id",
|
||||||
|
tags: ["comfyui"],
|
||||||
|
summary: "Get comfyui workflow",
|
||||||
|
description: "Use this to retrieve comfyui workflow by id",
|
||||||
|
request: {
|
||||||
|
params: z.object({
|
||||||
|
version_id: z.string(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
200: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: createSelectSchema(workflowVersionTable, {
|
||||||
|
workflow_api: (schema) =>
|
||||||
|
schema.workflow_api.openapi({
|
||||||
|
type: "object",
|
||||||
|
}),
|
||||||
|
workflow: (schema) =>
|
||||||
|
schema.workflow.openapi({
|
||||||
|
type: "object",
|
||||||
|
}),
|
||||||
|
snapshot: (schema) =>
|
||||||
|
schema.snapshot.openapi({
|
||||||
|
type: "object",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
description: "Retrieve the output",
|
||||||
|
},
|
||||||
|
500: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: z.object({
|
||||||
|
error: z.string(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
description: "Error when uploading the workflow",
|
||||||
|
},
|
||||||
|
...authError,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const registerGetWorkflowRoute = (app: App) => {
|
||||||
|
return app.openapi(route, async (c) => {
|
||||||
|
const { version_id } = c.req.valid("param");
|
||||||
|
const apiUser = c.get("apiKeyTokenData")!;
|
||||||
|
|
||||||
|
if (!apiUser.user_id)
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error: "Invalid user_id",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 500,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const workflow_version = await getWorkflowVersion(apiUser, version_id);
|
||||||
|
if (workflow_version) {
|
||||||
|
return c.json(workflow_version, {
|
||||||
|
status: 200,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error: "No version found",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 500,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage =
|
||||||
|
error instanceof Error ? error.message : "Unknown error";
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error: errorMessage,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
statusText: "Invalid request",
|
||||||
|
status: 500,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -3,20 +3,7 @@ import { authError } from "@/routes/authError";
|
|||||||
import { getFileDownloadUrl } from "@/server/getFileDownloadUrl";
|
import { getFileDownloadUrl } from "@/server/getFileDownloadUrl";
|
||||||
import { handleResourceUpload } from "@/server/resource";
|
import { handleResourceUpload } from "@/server/resource";
|
||||||
import { z, createRoute } from "@hono/zod-openapi";
|
import { z, createRoute } from "@hono/zod-openapi";
|
||||||
import { customAlphabet } from "nanoid";
|
import { newId } from "./newId";
|
||||||
|
|
||||||
export const nanoid = customAlphabet(
|
|
||||||
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
||||||
);
|
|
||||||
|
|
||||||
const prefixes = {
|
|
||||||
img: "img",
|
|
||||||
vid: "vid",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export function newId(prefix: keyof typeof prefixes): string {
|
|
||||||
return [prefixes[prefix], nanoid(16)].join("_");
|
|
||||||
}
|
|
||||||
|
|
||||||
const uploadUrlRoute = createRoute({
|
const uploadUrlRoute = createRoute({
|
||||||
method: "get",
|
method: "get",
|
||||||
@@ -96,7 +83,7 @@ export const registerUploadRoute = (app: App) => {
|
|||||||
file_id: id,
|
file_id: id,
|
||||||
download_url: await getFileDownloadUrl(filePath),
|
download_url: await getFileDownloadUrl(filePath),
|
||||||
},
|
},
|
||||||
200
|
200,
|
||||||
);
|
);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const errorMessage =
|
const errorMessage =
|
||||||
@@ -107,7 +94,7 @@ export const registerUploadRoute = (app: App) => {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
status: 500,
|
status: 500,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { db } from "@/db/db";
|
||||||
|
import {
|
||||||
|
snapshotType,
|
||||||
|
workflowAPIType,
|
||||||
|
workflowTable,
|
||||||
|
workflowType,
|
||||||
|
} from "@/db/schema";
|
||||||
|
import type { App } from "@/routes/app";
|
||||||
|
import { authError } from "@/routes/authError";
|
||||||
|
import {
|
||||||
|
createNewWorkflow,
|
||||||
|
createNewWorkflowVersion,
|
||||||
|
} from "@/server/createNewWorkflow";
|
||||||
|
import { z, createRoute } from "@hono/zod-openapi";
|
||||||
|
import { and, eq, isNull } from "drizzle-orm";
|
||||||
|
|
||||||
|
const route = createRoute({
|
||||||
|
method: "post",
|
||||||
|
path: "/workflow",
|
||||||
|
tags: ["comfyui"],
|
||||||
|
summary: "Upload workflow from ComfyUI",
|
||||||
|
description:
|
||||||
|
"This endpoints is specifically built for ComfyUI workflow upload.",
|
||||||
|
request: {
|
||||||
|
body: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: z.object({
|
||||||
|
workflow_id: z.string().optional(),
|
||||||
|
workflow_name: z.string().min(1).optional(),
|
||||||
|
workflow: workflowType,
|
||||||
|
workflow_api: workflowAPIType,
|
||||||
|
snapshot: snapshotType,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
200: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: z.object({
|
||||||
|
workflow_id: z.string(),
|
||||||
|
version: z.string(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
description: "Retrieve the output",
|
||||||
|
},
|
||||||
|
500: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: z.object({
|
||||||
|
error: z.string(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
description: "Error when uploading the workflow",
|
||||||
|
},
|
||||||
|
...authError,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const corsHeaders = {
|
||||||
|
"Access-Control-Allow-Origin": "*",
|
||||||
|
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
||||||
|
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const registerWorkflowUploadRoute = (app: App) => {
|
||||||
|
app.openapi(route, async (c) => {
|
||||||
|
const {
|
||||||
|
// user_id,
|
||||||
|
workflow,
|
||||||
|
workflow_api,
|
||||||
|
workflow_id: _workflow_id,
|
||||||
|
workflow_name,
|
||||||
|
snapshot,
|
||||||
|
} = c.req.valid("json");
|
||||||
|
const { org_id, user_id } = c.get("apiKeyTokenData")!;
|
||||||
|
|
||||||
|
if (!user_id)
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error: "Invalid user_id",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
headers: corsHeaders,
|
||||||
|
status: 500,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let workflow_id = _workflow_id;
|
||||||
|
|
||||||
|
let version = -1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ((!workflow_id || workflow_id.length === 0) && workflow_name) {
|
||||||
|
// Create a new parent workflow
|
||||||
|
const { workflow_id: _workflow_id, version: _version } =
|
||||||
|
await createNewWorkflow({
|
||||||
|
user_id: user_id,
|
||||||
|
org_id: org_id,
|
||||||
|
workflow_name: workflow_name,
|
||||||
|
workflowData: {
|
||||||
|
workflow,
|
||||||
|
workflow_api,
|
||||||
|
snapshot,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
workflow_id = _workflow_id;
|
||||||
|
version = _version;
|
||||||
|
} else if (workflow_id) {
|
||||||
|
const _workflow = await db
|
||||||
|
.select()
|
||||||
|
.from(workflowTable)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(workflowTable.id, workflow_id),
|
||||||
|
eq(workflowTable.user_id, user_id),
|
||||||
|
org_id
|
||||||
|
? eq(workflowTable.org_id, org_id)
|
||||||
|
: isNull(workflowTable.org_id),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (_workflow.length === 0) {
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error: "Invalid workflow_id",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 500,
|
||||||
|
statusText: "Invalid workflow_id",
|
||||||
|
headers: corsHeaders,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 2 update workflow
|
||||||
|
const { version: _version } = await createNewWorkflowVersion({
|
||||||
|
workflow_id: workflow_id,
|
||||||
|
workflowData: {
|
||||||
|
workflow,
|
||||||
|
workflow_api,
|
||||||
|
snapshot,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
version = _version;
|
||||||
|
} else {
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error: "Invalid request, missing either workflow_id or name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 500,
|
||||||
|
statusText: "Invalid request",
|
||||||
|
headers: corsHeaders,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage =
|
||||||
|
error instanceof Error ? error.message : "Unknown error";
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error: errorMessage,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
statusText: "Invalid request",
|
||||||
|
status: 500,
|
||||||
|
headers: corsHeaders,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
workflow_id: workflow_id,
|
||||||
|
version: version,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 200,
|
||||||
|
headers: corsHeaders,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.route("/upload-workflow").options(async (c) => {
|
||||||
|
return new Response(null, {
|
||||||
|
status: 204,
|
||||||
|
headers: corsHeaders,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
export const APIKeyBodyRequest = z.object({
|
export const APIKeyBodyRequest = z.object({
|
||||||
user_id: z.string().optional(),
|
user_id: z.string().optional().nullable(),
|
||||||
org_id: z.string().optional(),
|
org_id: z.string().optional().nullable(),
|
||||||
iat: z.number(),
|
iat: z.number(),
|
||||||
|
exp: z.number().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type APIKeyUserType = z.infer<typeof APIKeyBodyRequest>;
|
export type APIKeyUserType = z.infer<typeof APIKeyBodyRequest>;
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ export const insertCustomMachineSchema = createInsertSchema(machinesTable, {
|
|||||||
comfyui: "d0165d819afe76bd4e6bdd710eb5f3e571b6a804",
|
comfyui: "d0165d819afe76bd4e6bdd710eb5f3e571b6a804",
|
||||||
git_custom_nodes: {
|
git_custom_nodes: {
|
||||||
"https://github.com/BennyKok/comfyui-deploy.git": {
|
"https://github.com/BennyKok/comfyui-deploy.git": {
|
||||||
hash: "1e99474780951043e1b001e1877de3f2eb45cfba",
|
hash: "43fe0a384aa5fa9e141d4a264b2ed40a73b817bc",
|
||||||
disabled: false,
|
disabled: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,46 @@
|
|||||||
import { db } from "@/db/db";
|
import { db } from "@/db/db";
|
||||||
import type { WorkflowVersionType } from "@/db/schema";
|
import type { WorkflowVersionType } from "@/db/schema";
|
||||||
import { workflowTable, workflowVersionTable } from "@/db/schema";
|
import { workflowTable, workflowVersionTable } from "@/db/schema";
|
||||||
|
import { eq, sql } from "drizzle-orm";
|
||||||
|
|
||||||
|
export async function createNewWorkflowVersion({
|
||||||
|
workflow_id,
|
||||||
|
workflowData,
|
||||||
|
}: {
|
||||||
|
workflow_id: string;
|
||||||
|
workflowData: Pick<
|
||||||
|
WorkflowVersionType,
|
||||||
|
"workflow" | "workflow_api" | "snapshot"
|
||||||
|
>;
|
||||||
|
}) {
|
||||||
|
// Add a new version
|
||||||
|
const data = await db
|
||||||
|
.insert(workflowVersionTable)
|
||||||
|
.values({
|
||||||
|
workflow_id,
|
||||||
|
...workflowData,
|
||||||
|
version: sql`(
|
||||||
|
SELECT COALESCE(MAX(version), 0) + 1
|
||||||
|
FROM ${workflowVersionTable}
|
||||||
|
WHERE workflow_id = ${workflow_id}
|
||||||
|
)`,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
const version = data[0].version;
|
||||||
|
|
||||||
|
// Touch up the last updated time
|
||||||
|
await db
|
||||||
|
.update(workflowTable)
|
||||||
|
.set({
|
||||||
|
updated_at: new Date(),
|
||||||
|
})
|
||||||
|
.where(eq(workflowTable.id, workflow_id))
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
return {
|
||||||
|
version,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function createNewWorkflow({
|
export async function createNewWorkflow({
|
||||||
workflow_name,
|
workflow_name,
|
||||||
@@ -10,7 +50,7 @@ export async function createNewWorkflow({
|
|||||||
}: {
|
}: {
|
||||||
workflow_name: string;
|
workflow_name: string;
|
||||||
user_id: string;
|
user_id: string;
|
||||||
org_id?: string;
|
org_id?: string | null;
|
||||||
workflowData: Pick<
|
workflowData: Pick<
|
||||||
WorkflowVersionType,
|
WorkflowVersionType,
|
||||||
"workflow" | "workflow_api" | "snapshot"
|
"workflow" | "workflow_api" | "snapshot"
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
import { db } from "@/db/db";
|
import { db } from "@/db/db";
|
||||||
import type {
|
import type {
|
||||||
MachineType,
|
MachineType,
|
||||||
WorkflowRunOriginType,
|
WorkflowRunOriginType,
|
||||||
WorkflowVersionType,
|
WorkflowVersionType,
|
||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { machinesTable, workflowRunsTable } from "@/db/schema";
|
import { machinesTable, workflowRunsTable } from "@/db/schema";
|
||||||
import type { APIKeyUserType } from "@/server/APIKeyBodyRequest";
|
import type { APIKeyUserType } from "@/server/APIKeyBodyRequest";
|
||||||
@@ -18,226 +18,231 @@ import { v4 } from "uuid";
|
|||||||
import { withServerPromise } from "./withServerPromise";
|
import { withServerPromise } from "./withServerPromise";
|
||||||
|
|
||||||
export const createRun = withServerPromise(
|
export const createRun = withServerPromise(
|
||||||
async ({
|
async ({
|
||||||
origin,
|
origin,
|
||||||
workflow_version_id,
|
workflow_version_id,
|
||||||
machine_id,
|
machine_id,
|
||||||
inputs,
|
inputs,
|
||||||
runOrigin,
|
runOrigin,
|
||||||
apiUser,
|
apiUser,
|
||||||
}: {
|
}: {
|
||||||
origin: string;
|
origin: string;
|
||||||
workflow_version_id: string | WorkflowVersionType;
|
workflow_version_id: string | WorkflowVersionType;
|
||||||
machine_id: string | MachineType;
|
machine_id: string | MachineType;
|
||||||
inputs?: Record<string, string | number>;
|
inputs?: Record<string, string | number>;
|
||||||
runOrigin?: WorkflowRunOriginType;
|
runOrigin?: WorkflowRunOriginType;
|
||||||
apiUser?: APIKeyUserType;
|
apiUser?: APIKeyUserType;
|
||||||
}) => {
|
}) => {
|
||||||
const machine =
|
const machine =
|
||||||
typeof machine_id === "string"
|
typeof machine_id === "string"
|
||||||
? await db.query.machinesTable.findFirst({
|
? await db.query.machinesTable.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
eq(machinesTable.id, machine_id),
|
eq(machinesTable.id, machine_id),
|
||||||
eq(machinesTable.disabled, false),
|
eq(machinesTable.disabled, false),
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
: machine_id;
|
: machine_id;
|
||||||
|
|
||||||
if (!machine) {
|
if (!machine) {
|
||||||
throw new Error("Machine not found");
|
throw new Error("Machine not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const workflow_version_data =
|
const workflow_version_data =
|
||||||
typeof workflow_version_id === "string"
|
typeof workflow_version_id === "string"
|
||||||
? await db.query.workflowVersionTable.findFirst({
|
? await db.query.workflowVersionTable.findFirst({
|
||||||
where: eq(workflowRunsTable.id, workflow_version_id),
|
where: eq(workflowRunsTable.id, workflow_version_id),
|
||||||
with: {
|
with: {
|
||||||
workflow: {
|
workflow: {
|
||||||
columns: {
|
columns: {
|
||||||
org_id: true,
|
org_id: true,
|
||||||
user_id: true,
|
user_id: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
: workflow_version_id;
|
: workflow_version_id;
|
||||||
|
|
||||||
if (!workflow_version_data) {
|
if (!workflow_version_data) {
|
||||||
throw new Error("Workflow version not found");
|
throw new Error("Workflow version not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (apiUser)
|
if (apiUser)
|
||||||
if (apiUser.org_id) {
|
if (apiUser.org_id) {
|
||||||
// is org api call, check org only
|
// is org api call, check org only
|
||||||
if (apiUser.org_id != workflow_version_data.workflow.org_id) {
|
if (apiUser.org_id != workflow_version_data.workflow.org_id) {
|
||||||
throw new Error("Workflow not found");
|
throw new Error("Workflow not found");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// is user api call, check user only
|
// is user api call, check user only
|
||||||
if (
|
if (
|
||||||
apiUser.user_id != workflow_version_data.workflow.user_id &&
|
apiUser.user_id != workflow_version_data.workflow.user_id &&
|
||||||
workflow_version_data.workflow.org_id == null
|
workflow_version_data.workflow.org_id == null
|
||||||
) {
|
) {
|
||||||
throw new Error("Workflow not found");
|
throw new Error("Workflow not found");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const workflow_api = workflow_version_data.workflow_api;
|
const workflow_api = workflow_version_data.workflow_api;
|
||||||
|
|
||||||
// Replace the inputs
|
// Replace the inputs
|
||||||
if (inputs && workflow_api) {
|
if (inputs && workflow_api) {
|
||||||
for (const key in inputs) {
|
for (const key in inputs) {
|
||||||
Object.entries(workflow_api).forEach(([_, node]) => {
|
Object.entries(workflow_api).forEach(([_, node]) => {
|
||||||
if (node.inputs["input_id"] === key) {
|
if (node.inputs["input_id"] === key) {
|
||||||
node.inputs["input_id"] = inputs[key];
|
node.inputs["input_id"] = inputs[key];
|
||||||
}
|
// Fix for external text default value
|
||||||
});
|
if (node.class_type == "ComfyUIDeployExternalText") {
|
||||||
}
|
node.inputs["default_value"] = inputs[key];
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let prompt_id: string | undefined = undefined;
|
});
|
||||||
const shareData = {
|
}
|
||||||
workflow_api: workflow_api,
|
}
|
||||||
status_endpoint: `${origin}/api/update-run`,
|
|
||||||
file_upload_endpoint: `${origin}/api/file-upload`,
|
|
||||||
};
|
|
||||||
|
|
||||||
prompt_id = v4();
|
let prompt_id: string | undefined = undefined;
|
||||||
|
const shareData = {
|
||||||
|
workflow_api: workflow_api,
|
||||||
|
status_endpoint: `${origin}/api/update-run`,
|
||||||
|
file_upload_endpoint: `${origin}/api/file-upload`,
|
||||||
|
};
|
||||||
|
|
||||||
// Add to our db
|
prompt_id = v4();
|
||||||
const workflow_run = await db
|
|
||||||
.insert(workflowRunsTable)
|
|
||||||
.values({
|
|
||||||
id: prompt_id,
|
|
||||||
workflow_id: workflow_version_data.workflow_id,
|
|
||||||
workflow_version_id: workflow_version_data.id,
|
|
||||||
workflow_inputs: inputs,
|
|
||||||
machine_id: machine.id,
|
|
||||||
origin: runOrigin,
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
revalidatePath(`/${workflow_version_data.workflow_id}`);
|
// Add to our db
|
||||||
|
const workflow_run = await db
|
||||||
|
.insert(workflowRunsTable)
|
||||||
|
.values({
|
||||||
|
id: prompt_id,
|
||||||
|
workflow_id: workflow_version_data.workflow_id,
|
||||||
|
workflow_version_id: workflow_version_data.id,
|
||||||
|
workflow_inputs: inputs,
|
||||||
|
machine_id: machine.id,
|
||||||
|
origin: runOrigin,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
try {
|
revalidatePath(`/${workflow_version_data.workflow_id}`);
|
||||||
switch (machine.type) {
|
|
||||||
case "comfy-deploy-serverless":
|
|
||||||
case "modal-serverless":
|
|
||||||
const _data = {
|
|
||||||
input: {
|
|
||||||
...shareData,
|
|
||||||
prompt_id: prompt_id,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const ___result = await fetch(`${machine.endpoint}/run`, {
|
try {
|
||||||
method: "POST",
|
switch (machine.type) {
|
||||||
headers: {
|
case "comfy-deploy-serverless":
|
||||||
"Content-Type": "application/json",
|
case "modal-serverless":
|
||||||
},
|
const _data = {
|
||||||
body: JSON.stringify(_data),
|
input: {
|
||||||
cache: "no-store",
|
...shareData,
|
||||||
});
|
prompt_id: prompt_id,
|
||||||
console.log(___result);
|
},
|
||||||
if (!___result.ok)
|
};
|
||||||
throw new Error(
|
|
||||||
`Error creating run, ${
|
|
||||||
___result.statusText
|
|
||||||
} ${await ___result.text()}`,
|
|
||||||
);
|
|
||||||
console.log(_data, ___result);
|
|
||||||
break;
|
|
||||||
case "runpod-serverless":
|
|
||||||
const data = {
|
|
||||||
input: {
|
|
||||||
...shareData,
|
|
||||||
prompt_id: prompt_id,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
if (
|
const ___result = await fetch(`${machine.endpoint}/run`, {
|
||||||
!machine.auth_token &&
|
method: "POST",
|
||||||
!machine.endpoint.includes("localhost") &&
|
headers: {
|
||||||
!machine.endpoint.includes("127.0.0.1")
|
"Content-Type": "application/json",
|
||||||
) {
|
},
|
||||||
throw new Error("Machine auth token not found");
|
body: JSON.stringify(_data),
|
||||||
}
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
console.log(___result);
|
||||||
|
if (!___result.ok)
|
||||||
|
throw new Error(
|
||||||
|
`Error creating run, ${
|
||||||
|
___result.statusText
|
||||||
|
} ${await ___result.text()}`,
|
||||||
|
);
|
||||||
|
console.log(_data, ___result);
|
||||||
|
break;
|
||||||
|
case "runpod-serverless":
|
||||||
|
const data = {
|
||||||
|
input: {
|
||||||
|
...shareData,
|
||||||
|
prompt_id: prompt_id,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
const __result = await fetch(`${machine.endpoint}/run`, {
|
if (
|
||||||
method: "POST",
|
!machine.auth_token &&
|
||||||
headers: {
|
!machine.endpoint.includes("localhost") &&
|
||||||
"Content-Type": "application/json",
|
!machine.endpoint.includes("127.0.0.1")
|
||||||
Authorization: `Bearer ${machine.auth_token}`,
|
) {
|
||||||
},
|
throw new Error("Machine auth token not found");
|
||||||
body: JSON.stringify(data),
|
}
|
||||||
cache: "no-store",
|
|
||||||
});
|
|
||||||
console.log(__result);
|
|
||||||
if (!__result.ok)
|
|
||||||
throw new Error(
|
|
||||||
`Error creating run, ${
|
|
||||||
__result.statusText
|
|
||||||
} ${await __result.text()}`,
|
|
||||||
);
|
|
||||||
console.log(data, __result);
|
|
||||||
break;
|
|
||||||
case "classic":
|
|
||||||
const body = {
|
|
||||||
...shareData,
|
|
||||||
prompt_id: prompt_id,
|
|
||||||
};
|
|
||||||
// console.log(body);
|
|
||||||
const comfyui_endpoint = `${machine.endpoint}/comfyui-deploy/run`;
|
|
||||||
const _result = await fetch(comfyui_endpoint, {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
cache: "no-store",
|
|
||||||
});
|
|
||||||
// console.log(_result);
|
|
||||||
|
|
||||||
if (!_result.ok) {
|
const __result = await fetch(`${machine.endpoint}/run`, {
|
||||||
let message = `Error creating run, ${_result.statusText}`;
|
method: "POST",
|
||||||
try {
|
headers: {
|
||||||
const result = await ComfyAPI_Run.parseAsync(
|
"Content-Type": "application/json",
|
||||||
await _result.json(),
|
Authorization: `Bearer ${machine.auth_token}`,
|
||||||
);
|
},
|
||||||
message += ` ${result.node_errors}`;
|
body: JSON.stringify(data),
|
||||||
} catch (error) {}
|
cache: "no-store",
|
||||||
throw new Error(message);
|
});
|
||||||
}
|
console.log(__result);
|
||||||
// prompt_id = result.prompt_id;
|
if (!__result.ok)
|
||||||
break;
|
throw new Error(
|
||||||
}
|
`Error creating run, ${
|
||||||
} catch (e) {
|
__result.statusText
|
||||||
console.error(e);
|
} ${await __result.text()}`,
|
||||||
await db
|
);
|
||||||
.update(workflowRunsTable)
|
console.log(data, __result);
|
||||||
.set({
|
break;
|
||||||
status: "failed",
|
case "classic":
|
||||||
})
|
const body = {
|
||||||
.where(eq(workflowRunsTable.id, workflow_run[0].id));
|
...shareData,
|
||||||
throw e;
|
prompt_id: prompt_id,
|
||||||
}
|
};
|
||||||
|
// console.log(body);
|
||||||
|
const comfyui_endpoint = `${machine.endpoint}/comfyui-deploy/run`;
|
||||||
|
const _result = await fetch(comfyui_endpoint, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
// console.log(_result);
|
||||||
|
|
||||||
// It successfully started, update the started_at time
|
if (!_result.ok) {
|
||||||
|
let message = `Error creating run, ${_result.statusText}`;
|
||||||
|
try {
|
||||||
|
const result = await ComfyAPI_Run.parseAsync(
|
||||||
|
await _result.json(),
|
||||||
|
);
|
||||||
|
message += ` ${result.node_errors}`;
|
||||||
|
} catch (error) {}
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
// prompt_id = result.prompt_id;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
await db
|
||||||
|
.update(workflowRunsTable)
|
||||||
|
.set({
|
||||||
|
status: "failed",
|
||||||
|
})
|
||||||
|
.where(eq(workflowRunsTable.id, workflow_run[0].id));
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
await db
|
// It successfully started, update the started_at time
|
||||||
.update(workflowRunsTable)
|
|
||||||
.set({
|
|
||||||
started_at: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(workflowRunsTable.id, workflow_run[0].id));
|
|
||||||
|
|
||||||
return {
|
await db
|
||||||
workflow_run_id: workflow_run[0].id,
|
.update(workflowRunsTable)
|
||||||
message: "Successful workflow run",
|
.set({
|
||||||
};
|
started_at: new Date(),
|
||||||
},
|
})
|
||||||
|
.where(eq(workflowRunsTable.id, workflow_run[0].id));
|
||||||
|
|
||||||
|
return {
|
||||||
|
workflow_run_id: workflow_run[0].id,
|
||||||
|
message: "Successful workflow run",
|
||||||
|
};
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
export async function checkStatus(run_id: string) {
|
export async function checkStatus(run_id: string) {
|
||||||
const { userId } = auth();
|
const { userId } = auth();
|
||||||
if (!userId) throw new Error("User not found");
|
if (!userId) throw new Error("User not found");
|
||||||
|
|
||||||
return await getRunsData(run_id);
|
return await getRunsData(run_id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ import {
|
|||||||
workflowTable,
|
workflowTable,
|
||||||
workflowVersionTable,
|
workflowVersionTable,
|
||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
|
import { APIKeyUserType } from "@/server/APIKeyBodyRequest";
|
||||||
import { auth } from "@clerk/nextjs";
|
import { auth } from "@clerk/nextjs";
|
||||||
import { and, desc, eq, isNull } from "drizzle-orm";
|
import { and, desc, eq, isNull } from "drizzle-orm";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
export async function getAllUserWorkflow() {
|
export async function getAllUserWorkflow() {
|
||||||
const { userId, orgId } = await auth();
|
const { userId, orgId } = await auth();
|
||||||
@@ -51,3 +53,29 @@ export async function getAllUserWorkflow() {
|
|||||||
|
|
||||||
return workflow;
|
return workflow;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getWorkflowVersion(
|
||||||
|
apiUser: APIKeyUserType,
|
||||||
|
version_id: string,
|
||||||
|
) {
|
||||||
|
const { org_id, user_id } = apiUser;
|
||||||
|
|
||||||
|
if (!user_id) {
|
||||||
|
throw new Error("No user id");
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentWorkflow = await db.query.workflowTable.findFirst({
|
||||||
|
where:
|
||||||
|
org_id != undefined
|
||||||
|
? eq(workflowTable.org_id, org_id)
|
||||||
|
: and(eq(workflowTable.user_id, user_id), isNull(workflowTable.org_id)),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!parentWorkflow) {
|
||||||
|
throw new Error("No workflow found");
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.query.workflowVersionTable.findFirst({
|
||||||
|
where: eq(workflowVersionTable.id, version_id),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,23 +1,28 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { db } from "@/db/db";
|
import { db } from "@/db/db";
|
||||||
import { apiKeyTable } from "@/db/schema";
|
import { apiKeyTable, authRequestsTable } from "@/db/schema";
|
||||||
|
import { withServerPromise } from "@/server/withServerPromise";
|
||||||
import { auth } from "@clerk/nextjs";
|
import { auth } from "@clerk/nextjs";
|
||||||
import { and, desc, eq, isNull } from "drizzle-orm";
|
import { and, desc, eq, isNull } from "drizzle-orm";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
|
|
||||||
// export const nanoid = customAlphabet(
|
export const createAuthRequest = withServerPromise(
|
||||||
// "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
async (request_id: string) => {
|
||||||
// );
|
const { userId, orgId } = auth();
|
||||||
|
|
||||||
// const prefixes = {
|
const result = await db.insert(authRequestsTable).values({
|
||||||
// cd: "cd",
|
request_id: request_id,
|
||||||
// } as const;
|
user_id: userId,
|
||||||
|
org_id: orgId,
|
||||||
|
});
|
||||||
|
|
||||||
// function newId(prefix: keyof typeof prefixes): string {
|
return {
|
||||||
// return [prefixes[prefix], nanoid(16)].join("_");
|
message: "Auth request created, you may now return to your application.",
|
||||||
// }
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
export async function addNewAPIKey(name: string) {
|
export async function addNewAPIKey(name: string) {
|
||||||
const { userId, orgId } = auth();
|
const { userId, orgId } = auth();
|
||||||
@@ -29,7 +34,7 @@ export async function addNewAPIKey(name: string) {
|
|||||||
if (orgId) {
|
if (orgId) {
|
||||||
token = jwt.sign(
|
token = jwt.sign(
|
||||||
{ user_id: userId, org_id: orgId },
|
{ user_id: userId, org_id: orgId },
|
||||||
process.env.JWT_SECRET!
|
process.env.JWT_SECRET!,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
token = jwt.sign({ user_id: userId }, process.env.JWT_SECRET!);
|
token = jwt.sign({ user_id: userId }, process.env.JWT_SECRET!);
|
||||||
@@ -93,7 +98,7 @@ export async function getAPIKeys() {
|
|||||||
where: and(
|
where: and(
|
||||||
eq(apiKeyTable.user_id, userId),
|
eq(apiKeyTable.user_id, userId),
|
||||||
isNull(apiKeyTable.org_id),
|
isNull(apiKeyTable.org_id),
|
||||||
eq(apiKeyTable.revoked, false)
|
eq(apiKeyTable.revoked, false),
|
||||||
),
|
),
|
||||||
orderBy: desc(apiKeyTable.created_at),
|
orderBy: desc(apiKeyTable.created_at),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -16,270 +16,272 @@ import "server-only";
|
|||||||
import { validate as isValidUUID } from "uuid";
|
import { validate as isValidUUID } from "uuid";
|
||||||
import type { z } from "zod";
|
import type { z } from "zod";
|
||||||
export async function createDeployments(
|
export async function createDeployments(
|
||||||
workflow_id: string,
|
workflow_id: string,
|
||||||
version_id: string,
|
version_id: string,
|
||||||
machine_id: string,
|
machine_id: string,
|
||||||
environment: DeploymentType["environment"],
|
environment: DeploymentType["environment"],
|
||||||
) {
|
) {
|
||||||
const { userId, orgId } = auth();
|
const { userId, orgId } = auth();
|
||||||
if (!userId) throw new Error("No user id");
|
if (!userId) throw new Error("No user id");
|
||||||
|
|
||||||
if (!machine_id) {
|
if (!machine_id) {
|
||||||
throw new Error("No machine id provided");
|
throw new Error("No machine id provided");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Same environment and same workflow
|
// Same environment and same workflow
|
||||||
const existingDeployment = await db.query.deploymentsTable.findFirst({
|
const existingDeployment = await db.query.deploymentsTable.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
eq(deploymentsTable.workflow_id, workflow_id),
|
eq(deploymentsTable.workflow_id, workflow_id),
|
||||||
eq(deploymentsTable.environment, environment),
|
eq(deploymentsTable.environment, environment),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (existingDeployment) {
|
if (existingDeployment) {
|
||||||
await db
|
await db
|
||||||
.update(deploymentsTable)
|
.update(deploymentsTable)
|
||||||
.set({
|
.set({
|
||||||
workflow_id,
|
workflow_id,
|
||||||
workflow_version_id: version_id,
|
workflow_version_id: version_id,
|
||||||
machine_id,
|
machine_id,
|
||||||
org_id: orgId,
|
org_id: orgId,
|
||||||
})
|
})
|
||||||
.where(eq(deploymentsTable.id, existingDeployment.id));
|
.where(eq(deploymentsTable.id, existingDeployment.id));
|
||||||
} else {
|
} else {
|
||||||
const workflow = await db.query.workflowTable.findFirst({
|
const workflow = await db.query.workflowTable.findFirst({
|
||||||
where: eq(workflowTable.id, workflow_id),
|
where: eq(workflowTable.id, workflow_id),
|
||||||
with: {
|
with: {
|
||||||
user: {
|
user: {
|
||||||
columns: {
|
columns: {
|
||||||
name: true,
|
name: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!workflow) throw new Error("No workflow found");
|
if (!workflow) throw new Error("No workflow found");
|
||||||
|
|
||||||
const userName = workflow.org_id
|
const userName = workflow.org_id
|
||||||
? await clerkClient.organizations
|
? await clerkClient.organizations
|
||||||
.getOrganization({
|
.getOrganization({
|
||||||
organizationId: workflow.org_id,
|
organizationId: workflow.org_id,
|
||||||
})
|
})
|
||||||
.then((x) => x.name)
|
.then((x) => x.name)
|
||||||
: workflow.user.name;
|
: workflow.user.name;
|
||||||
|
|
||||||
await db.insert(deploymentsTable).values({
|
await db.insert(deploymentsTable).values({
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
workflow_id,
|
workflow_id,
|
||||||
workflow_version_id: version_id,
|
workflow_version_id: version_id,
|
||||||
machine_id,
|
machine_id,
|
||||||
environment,
|
environment,
|
||||||
org_id: orgId,
|
org_id: orgId,
|
||||||
share_slug: slugify(`${userName} ${workflow.name}`),
|
// only create share slug if this is public share
|
||||||
});
|
share_slug: environment == "public-share" ? slugify(`${userName} ${workflow.name}`) : null
|
||||||
}
|
});
|
||||||
revalidatePath(`/${workflow_id}`);
|
}
|
||||||
return {
|
revalidatePath(`/${workflow_id}`);
|
||||||
message: `Successfully created deployment for ${environment}`,
|
return {
|
||||||
};
|
message: `Successfully created deployment for ${environment}`,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function findAllDeployments() {
|
export async function findAllDeployments() {
|
||||||
const { userId, orgId } = auth();
|
const { userId, orgId } = auth();
|
||||||
if (!userId) throw new Error("No user id");
|
if (!userId) throw new Error("No user id");
|
||||||
|
|
||||||
const deployments = await db.query.workflowTable.findMany({
|
const deployments = await db.query.workflowTable.findMany({
|
||||||
where: and(
|
where: and(
|
||||||
orgId
|
orgId
|
||||||
? eq(workflowTable.org_id, orgId)
|
? eq(workflowTable.org_id, orgId)
|
||||||
: and(eq(workflowTable.user_id, userId), isNull(workflowTable.org_id)),
|
: and(eq(workflowTable.user_id, userId), isNull(workflowTable.org_id)),
|
||||||
),
|
),
|
||||||
columns: {
|
columns: {
|
||||||
name: true,
|
name: true,
|
||||||
},
|
},
|
||||||
with: {
|
with: {
|
||||||
deployments: {
|
deployments: {
|
||||||
columns: {
|
columns: {
|
||||||
environment: true,
|
environment: true,
|
||||||
},
|
},
|
||||||
with: {
|
with: {
|
||||||
version: {
|
version: {
|
||||||
columns: {
|
columns: {
|
||||||
id: true,
|
id: true,
|
||||||
snapshot: true,
|
snapshot: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return deployments;
|
return deployments;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function findSharedDeployment(workflow_id: string) {
|
export async function findSharedDeployment(workflow_id: string) {
|
||||||
const deploymentData = await db.query.deploymentsTable.findFirst({
|
const deploymentData = await db.query.deploymentsTable.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
eq(deploymentsTable.environment, "public-share"),
|
eq(deploymentsTable.environment, "public-share"),
|
||||||
isValidUUID(workflow_id)
|
isValidUUID(workflow_id)
|
||||||
? eq(deploymentsTable.id, workflow_id)
|
? eq(deploymentsTable.id, workflow_id)
|
||||||
: eq(deploymentsTable.share_slug, workflow_id),
|
: eq(deploymentsTable.share_slug, workflow_id),
|
||||||
),
|
),
|
||||||
with: {
|
with: {
|
||||||
user: true,
|
user: true,
|
||||||
machine: true,
|
machine: true,
|
||||||
workflow: {
|
workflow: {
|
||||||
columns: {
|
columns: {
|
||||||
name: true,
|
name: true,
|
||||||
org_id: true,
|
org_id: true,
|
||||||
user_id: true,
|
user_id: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
version: true,
|
version: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return deploymentData;
|
return deploymentData;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const removePublicShareDeployment = withServerPromise(
|
export const removePublicShareDeployment = withServerPromise(
|
||||||
async (deployment_id: string) => {
|
async (deployment_id: string) => {
|
||||||
const [removed] = await db
|
const [removed] = await db
|
||||||
.delete(deploymentsTable)
|
.delete(deploymentsTable)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(deploymentsTable.environment, "public-share"),
|
eq(deploymentsTable.environment, "public-share"),
|
||||||
eq(deploymentsTable.id, deployment_id),
|
eq(deploymentsTable.id, deployment_id),
|
||||||
),
|
),
|
||||||
).returning();
|
)
|
||||||
|
.returning();
|
||||||
|
|
||||||
// revalidatePath(
|
// revalidatePath(
|
||||||
// `/workflows/${removed.workflow_id}`
|
// `/workflows/${removed.workflow_id}`
|
||||||
// )
|
// )
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
export const cloneWorkflow = withServerPromise(
|
export const cloneWorkflow = withServerPromise(
|
||||||
async (deployment_id: string) => {
|
async (deployment_id: string) => {
|
||||||
const deployment = await db.query.deploymentsTable.findFirst({
|
const deployment = await db.query.deploymentsTable.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
eq(deploymentsTable.environment, "public-share"),
|
eq(deploymentsTable.environment, "public-share"),
|
||||||
eq(deploymentsTable.id, deployment_id),
|
eq(deploymentsTable.id, deployment_id),
|
||||||
),
|
),
|
||||||
with: {
|
with: {
|
||||||
version: true,
|
version: true,
|
||||||
workflow: true,
|
workflow: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!deployment) throw new Error("No deployment found");
|
if (!deployment) throw new Error("No deployment found");
|
||||||
|
|
||||||
const { userId, orgId } = auth();
|
const { userId, orgId } = auth();
|
||||||
|
|
||||||
if (!userId) throw new Error("No user id");
|
if (!userId) throw new Error("No user id");
|
||||||
|
|
||||||
await createNewWorkflow({
|
await createNewWorkflow({
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
org_id: orgId,
|
org_id: orgId,
|
||||||
workflow_name: `${deployment.workflow.name} (Cloned)`,
|
workflow_name: `${deployment.workflow.name} (Cloned)`,
|
||||||
workflowData: {
|
workflowData: {
|
||||||
workflow: deployment.version.workflow,
|
workflow: deployment.version.workflow,
|
||||||
workflow_api: deployment?.version.workflow_api,
|
workflow_api: deployment?.version.workflow_api,
|
||||||
snapshot: deployment?.version.snapshot,
|
snapshot: deployment?.version.snapshot,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
redirect(`/workflows/${deployment.workflow.id}`);
|
redirect(`/workflows/${deployment.workflow.id}`);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: "Successfully cloned workflow",
|
message: "Successfully cloned workflow",
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
export const cloneMachine = withServerPromise(async (deployment_id: string) => {
|
export const cloneMachine = withServerPromise(async (deployment_id: string) => {
|
||||||
const deployment = await db.query.deploymentsTable.findFirst({
|
const deployment = await db.query.deploymentsTable.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
eq(deploymentsTable.environment, "public-share"),
|
eq(deploymentsTable.environment, "public-share"),
|
||||||
eq(deploymentsTable.id, deployment_id),
|
eq(deploymentsTable.id, deployment_id),
|
||||||
),
|
),
|
||||||
with: {
|
with: {
|
||||||
machine: true,
|
machine: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!deployment) throw new Error("No deployment found");
|
if (!deployment) throw new Error("No deployment found");
|
||||||
if (deployment.machine.type !== "comfy-deploy-serverless")
|
if (deployment.machine.type !== "comfy-deploy-serverless")
|
||||||
throw new Error("Can only clone comfy-deploy-serverlesss");
|
throw new Error("Can only clone comfy-deploy-serverlesss");
|
||||||
|
|
||||||
const { userId, orgId } = auth();
|
const { userId, orgId } = auth();
|
||||||
|
|
||||||
if (!userId) throw new Error("No user id");
|
if (!userId) throw new Error("No user id");
|
||||||
|
|
||||||
await addCustomMachine({
|
await addCustomMachine({
|
||||||
gpu: deployment.machine.gpu,
|
gpu: deployment.machine.gpu,
|
||||||
models: deployment.machine.models,
|
models: deployment.machine.models,
|
||||||
snapshot: deployment.machine.snapshot,
|
snapshot: deployment.machine.snapshot,
|
||||||
name: `${deployment.machine.name} (Cloned)`,
|
name: `${deployment.machine.name} (Cloned)`,
|
||||||
type: "comfy-deploy-serverless",
|
type: "comfy-deploy-serverless",
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: "Successfully cloned workflow",
|
message: "Successfully cloned workflow",
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function findUserShareDeployment(share_id: string) {
|
export async function findUserShareDeployment(share_id: string) {
|
||||||
const { userId, orgId } = auth();
|
const { userId, orgId } = auth();
|
||||||
|
|
||||||
if (!userId) throw new Error("No user id");
|
if (!userId) throw new Error("No user id");
|
||||||
|
|
||||||
const [deployment] = await db
|
const [deployment] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(deploymentsTable)
|
.from(deploymentsTable)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
isValidUUID(share_id)
|
isValidUUID(share_id)
|
||||||
? eq(deploymentsTable.id, share_id)
|
? eq(deploymentsTable.id, share_id)
|
||||||
: eq(deploymentsTable.share_slug, share_id),
|
: eq(deploymentsTable.share_slug, share_id),
|
||||||
eq(deploymentsTable.environment, "public-share"),
|
eq(deploymentsTable.environment, "public-share"),
|
||||||
orgId
|
orgId
|
||||||
? eq(deploymentsTable.org_id, orgId)
|
? eq(deploymentsTable.org_id, orgId)
|
||||||
: and(
|
: and(
|
||||||
eq(deploymentsTable.user_id, userId),
|
eq(deploymentsTable.user_id, userId),
|
||||||
isNull(deploymentsTable.org_id),
|
isNull(deploymentsTable.org_id),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!deployment) throw new Error("No deployment found");
|
if (!deployment) throw new Error("No deployment found");
|
||||||
|
|
||||||
return deployment;
|
return deployment;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const updateSharePageInfo = withServerPromise(
|
export const updateSharePageInfo = withServerPromise(
|
||||||
async ({
|
async ({
|
||||||
id,
|
id,
|
||||||
...data
|
...data
|
||||||
}: z.infer<typeof publicShareDeployment> & {
|
}: z.infer<typeof publicShareDeployment> & {
|
||||||
id: string;
|
id: string;
|
||||||
}) => {
|
}) => {
|
||||||
const { userId } = auth();
|
const { userId } = auth();
|
||||||
if (!userId) return { error: "No user id" };
|
if (!userId) return { error: "No user id" };
|
||||||
|
|
||||||
console.log(data);
|
console.log(data);
|
||||||
|
|
||||||
const [deployment] = await db
|
const [deployment] = await db
|
||||||
.update(deploymentsTable)
|
.update(deploymentsTable)
|
||||||
.set(data)
|
.set(data)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(deploymentsTable.environment, "public-share"),
|
eq(deploymentsTable.environment, "public-share"),
|
||||||
eq(deploymentsTable.id, id),
|
eq(deploymentsTable.id, id),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
return { message: "Info Updated" };
|
return { message: "Info Updated" };
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { getMachineById } from "@/server/curdMachine";
|
||||||
|
import { auth } from "@clerk/nextjs";
|
||||||
|
import jwt from "jsonwebtoken";
|
||||||
|
import { getOrgOrUserDisplayName } from "@/server/getOrgOrUserDisplayName";
|
||||||
|
import { withServerPromise } from "@/server/withServerPromise";
|
||||||
|
import "server-only";
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
|
||||||
|
export const editWorkflowOnMachine = withServerPromise(
|
||||||
|
async (workflow_version_id: string, machine_id: string) => {
|
||||||
|
const { userId, orgId } = auth();
|
||||||
|
|
||||||
|
const headersList = headers();
|
||||||
|
const host = headersList.get("host") || "";
|
||||||
|
const protocol = headersList.get("x-forwarded-proto") || "";
|
||||||
|
const domain = `${protocol}://${host}`;
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
throw new Error("No user id");
|
||||||
|
}
|
||||||
|
|
||||||
|
const machine = await getMachineById(machine_id);
|
||||||
|
|
||||||
|
const expireTime = "1w";
|
||||||
|
const token = jwt.sign(
|
||||||
|
{ user_id: userId, org_id: orgId },
|
||||||
|
process.env.JWT_SECRET!,
|
||||||
|
{
|
||||||
|
expiresIn: expireTime,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const userName = await getOrgOrUserDisplayName(orgId, userId);
|
||||||
|
|
||||||
|
let endpoint = machine.endpoint;
|
||||||
|
|
||||||
|
if (machine.type === "comfy-deploy-serverless") {
|
||||||
|
endpoint = machine.endpoint.replace("comfyui-api", "comfyui-app");
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${endpoint}?workflow_version_id=${encodeURIComponent(
|
||||||
|
workflow_version_id,
|
||||||
|
)}&auth_token=${encodeURIComponent(token)}&org_display=${encodeURIComponent(
|
||||||
|
userName,
|
||||||
|
)}&origin=${encodeURIComponent(domain)}`;
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { db } from "@/db/db";
|
||||||
|
import { usersTable } from "@/db/schema";
|
||||||
|
import { clerkClient } from "@clerk/nextjs";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
|
||||||
|
export async function getOrgOrUserDisplayName(
|
||||||
|
orgId: string | undefined | null,
|
||||||
|
userId: string,
|
||||||
|
) {
|
||||||
|
return orgId
|
||||||
|
? await clerkClient.organizations
|
||||||
|
.getOrganization({
|
||||||
|
organizationId: orgId,
|
||||||
|
})
|
||||||
|
.then((x) => x.name)
|
||||||
|
: (await db.select().from(usersTable).where(eq(usersTable.id, userId)))[0]
|
||||||
|
.name;
|
||||||
|
}
|
||||||
@@ -49,24 +49,26 @@ export async function getRunsData(run_id: string, user?: APIKeyUserType) {
|
|||||||
for (let i = 0; i < data.outputs.length; i++) {
|
for (let i = 0; i < data.outputs.length; i++) {
|
||||||
const output = data.outputs[i];
|
const output = data.outputs[i];
|
||||||
|
|
||||||
if (output.data?.images !== undefined) {
|
if (output.data?.images !== undefined)
|
||||||
for (let j = 0; j < output.data?.images.length; j++) {
|
replaceUrls(output.data?.images, data.id);
|
||||||
const element = output.data?.images[j];
|
|
||||||
element.url = replaceCDNUrl(
|
if (output.data?.files !== undefined)
|
||||||
`${process.env.SPACES_ENDPOINT}/${process.env.SPACES_BUCKET}/outputs/runs/${data.id}/${element.filename}`
|
replaceUrls(output.data?.files, data.id);
|
||||||
);
|
|
||||||
}
|
if (output.data?.gifs !== undefined)
|
||||||
} else if (output.data?.files !== undefined) {
|
replaceUrls(output.data?.gifs, data.id);
|
||||||
for (let j = 0; j < output.data?.files.length; j++) {
|
|
||||||
const element = output.data?.files[j];
|
|
||||||
element.url = replaceCDNUrl(
|
|
||||||
`${process.env.SPACES_ENDPOINT}/${process.env.SPACES_BUCKET}/outputs/runs/${data.id}/${element.filename}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function replaceUrls(dataType: any[], dataId: string) {
|
||||||
|
for (let j = 0; j < dataType.length; j++) {
|
||||||
|
const element = dataType[j];
|
||||||
|
element.url = replaceCDNUrl(
|
||||||
|
`${process.env.SPACES_ENDPOINT}/${process.env.SPACES_BUCKET}/outputs/runs/${dataId}/${element.filename}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
"use server";
|
|
||||||
|
|
||||||
import { LemonSqueezy } from "@lemonsqueezy/lemonsqueezy.js";
|
|
||||||
import "server-only";
|
|
||||||
|
|
||||||
const ls = new LemonSqueezy(process.env.LEMONSQUEEZY_API_KEY || "");
|
|
||||||
|
|
||||||
export async function getPricing() {
|
|
||||||
const products = await ls.getProducts();
|
|
||||||
|
|
||||||
return products;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getUsage() {
|
|
||||||
const usageRecord = await ls.getUsageRecords();
|
|
||||||
|
|
||||||
return usageRecord;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setUsage(id: number, quantity: number) {
|
|
||||||
const setUsage = await ls.createUsageRecord({
|
|
||||||
subscriptionItemId: id,
|
|
||||||
quantity: quantity,
|
|
||||||
});
|
|
||||||
|
|
||||||
return setUsage;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getSubscription() {
|
|
||||||
const subscription = await ls.getSubscriptions();
|
|
||||||
|
|
||||||
return subscription;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getSubscriptionItem() {
|
|
||||||
const subscriptionItem = await ls.getSubscriptionItems();
|
|
||||||
|
|
||||||
return subscriptionItem;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getUserData() {
|
|
||||||
const user = await ls.getUser();
|
|
||||||
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||