diff --git a/app/api/common.ts b/app/api/common.ts index 946125c6f..7b19b9783 100644 --- a/app/api/common.ts +++ b/app/api/common.ts @@ -3,6 +3,7 @@ import { getServerSideConfig } from "../config/server"; import { DEFAULT_MODELS, OPENAI_BASE_URL, GEMINI_BASE_URL } from "../constant"; import { collectModelTable } from "../utils/model"; import { makeAzurePath } from "../azure"; +import { getIP } from "@/app/api/auth"; const serverConfig = getServerSideConfig(); @@ -130,3 +131,45 @@ export async function requestOpenai( clearTimeout(timeoutId); } } + +export async function requestLog( + req: NextRequest, + jsonBody: any, + url_path: string, +) { + // LOG + try { + if (url_path.startsWith("mj/") && !url_path.startsWith("mj/submit/")) { + return; + } + // const protocol = req.headers.get("x-forwarded-proto") || "http"; + //const baseUrl = process.env.NEXTAUTH_URL ?? "http://localhost:3000"; + const baseUrl = "http://localhost:3000"; + const ip = getIP(req); + // 对其进行 Base64 解码 + let h_userName = req.headers.get("x-request-name"); + if (h_userName) { + const buffer = Buffer.from(h_userName, "base64"); + h_userName = decodeURIComponent(buffer.toString("utf-8")); + } + console.log("[中文]", h_userName, baseUrl); + const logData = { + ip: ip, + path: url_path, + // logEntry: JSON.stringify(jsonBody), + model: url_path.startsWith("mj/") ? "midjourney" : jsonBody?.model, // 后面尝试请求是添加到参数 + userName: h_userName, + }; + + await fetch(`${baseUrl}/api/logs/openai`, { + method: "POST", + headers: { + "Content-Type": "application/json", + // ...req.headers, + }, + body: JSON.stringify(logData), + }); + } catch (e) { + console.log("[LOG]", e, "=========="); + } +} diff --git a/app/api/logs/[...path]/route.ts b/app/api/logs/[...path]/route.ts index 099dee047..44070b1d1 100644 --- a/app/api/logs/[...path]/route.ts +++ b/app/api/logs/[...path]/route.ts @@ -31,13 +31,18 @@ async function handle( const regex_message = /(?<="content":")(.*?)(?="}[,\]])/g; const matchAllMessage = request_data.logEntry.match(regex_message); // console.log(matchAllMessage, "====="); - if (matchAllMessage.length > 0) { + if (matchAllMessage && matchAllMessage.length > 0) { request_data.logToken = getTokenLength(matchAllMessage.join(" ")) + matchAllMessage.length * 3; + } else { + request_data.logToken = 0; } delete request_data["logEntry"]; } + if (request_data?.model == "midjourney") { + request_data.logToken = 1000; + } } catch (e) { console.log("[LOG]", "logToken", e); request_data.logToken = 0; diff --git a/app/api/midjourney/[...path]/route.ts b/app/api/midjourney/[...path]/route.ts index 2adc39ae0..bc5cbfdf0 100644 --- a/app/api/midjourney/[...path]/route.ts +++ b/app/api/midjourney/[...path]/route.ts @@ -1,6 +1,7 @@ import { NextRequest, NextResponse } from "next/server"; -import { auth } from "@/app/api/auth"; +import { auth, getIP } from "@/app/api/auth"; import { ModelProvider } from "@/app/constant"; +import { requestLog } from "@/app/api/common"; const BASE_URL = process.env.MIDJOURNEY_PROXY_URL ?? null; const MIDJOURNEY_PROXY_KEY = process.env.MIDJOURNEY_PROXY_KEY ?? null; @@ -53,6 +54,10 @@ async function handle( "", ); + if (reqPath.startsWith("mj/submit/")) { + await requestLog(req, jsonBody, reqPath); + } + let fetchUrl = `${mjProxyUrl}/${reqPath}`; console.log("[MJ Proxy] ", fetchUrl); diff --git a/app/api/openai/[...path]/route.ts b/app/api/openai/[...path]/route.ts index 8885baf97..9e4352413 100644 --- a/app/api/openai/[...path]/route.ts +++ b/app/api/openai/[...path]/route.ts @@ -10,7 +10,7 @@ import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; import { auth, getIP } from "../../auth"; import { getToken } from "next-auth/jwt"; -import { requestOpenai } from "../../common"; +import { requestLog, requestOpenai } from "../../common"; import { headers } from "next/headers"; const ALLOWD_PATH = new Set(Object.values({ ...OpenaiPath, ...AZURE_PATH })); @@ -75,37 +75,7 @@ async function handle( jsonBody = {}; } - try { - const protocol = req.headers.get("x-forwarded-proto") || "http"; - //const baseUrl = process.env.NEXTAUTH_URL ?? "http://localhost:3000"; - const baseUrl = "http://localhost:3000"; - const ip = getIP(req); - // 对其进行 Base64 解码 - let h_userName = req.headers.get("x-request-name"); - if (h_userName) { - const buffer = Buffer.from(h_userName, "base64"); - h_userName = decodeURIComponent(buffer.toString("utf-8")); - } - console.log("[中文]", h_userName, baseUrl); - const logData = { - ip: ip, - path: subpath, - logEntry: JSON.stringify(jsonBody), - model: jsonBody?.model, - userName: h_userName, - }; - - await fetch(`${baseUrl}/api/logs/openai`, { - method: "POST", - headers: { - "Content-Type": "application/json", - // ...req.headers, - }, - body: JSON.stringify(logData), - }); - } catch (e) { - console.log("[LOG]", e, "=========="); - } + await requestLog(req, jsonBody, subpath); const isAzure = AZURE_MODELS.includes(jsonBody?.model as string); // console.log("[Models]", jsonBody?.model); diff --git a/app/components/chat.tsx b/app/components/chat.tsx index 7830e5064..acee90610 100644 --- a/app/components/chat.tsx +++ b/app/components/chat.tsx @@ -36,7 +36,7 @@ import AutoIcon from "../icons/auto.svg"; import BottomIcon from "../icons/bottom.svg"; import StopIcon from "../icons/pause.svg"; import RobotIcon from "../icons/robot.svg"; -import UploadIcon from "../icons/upload.svg"; +// import UploadIcon from "../icons/upload.svg"; import { ChatMessage, @@ -433,7 +433,6 @@ export function ChatActions(props: { showPromptModal: () => void; scrollToBottom: () => void; showPromptHints: () => void; - imageSelected: (img: any) => void; hitBottom: boolean; uploading: boolean; }) { @@ -455,25 +454,6 @@ export function ChatActions(props: { const couldStop = ChatControllerPool.hasPending(); const stopAll = () => ChatControllerPool.stopAll(); - function selectImage() { - document.getElementById("chat-image-file-select-upload")?.click(); - } - - const onImageSelected = (e: any) => { - const file = e.target.files[0]; - const filename = file.name; - const reader = new FileReader(); - reader.readAsDataURL(file); - reader.onload = () => { - const base64 = reader.result; - props.imageSelected({ - filename, - base64, - }); - }; - e.target.value = null; - }; - // switch model const currentModel = chatStore.currentSession().mask.modelConfig.model; const allModels = useAllModels(); @@ -529,13 +509,13 @@ export function ChatActions(props: { {/* />*/} {/*)}*/} - {showUploadImage && ( - : } - /> - )} + {/*{showUploadImage && (*/} + : } + /> + {/*)}*/} } /> - } - /> - + {/*}*/} + {/*/>*/} + {/**/} {showModelSelector && ( (null); const [userInput, setUserInput] = useState(""); - const [useImages, setUseImages] = useState([]); const [mjImageMode, setMjImageMode] = useState("IMAGINE"); const [isLoading, setIsLoading] = useState(false); const { submitKey, shouldSubmit } = useSubmitHandler(); @@ -784,36 +763,23 @@ function _Chat() { const doSubmit = (userInput: string) => { if (userInput.trim() === "") return; - if (useImages.length > 0) { - if (mjImageMode === "IMAGINE" && userInput == "") { - alert(Locale.Midjourney.NeedInputUseImgPrompt); - return; - } - } else { - const matchCommand = chatCommands.match(userInput); - if (matchCommand.matched) { - setUserInput(""); - setPromptHints([]); - matchCommand.invoke(); - return; - } + const matchCommand = chatCommands.match(userInput); + if (matchCommand.matched) { + setUserInput(""); + setPromptHints([]); + matchCommand.invoke(); + return; } setIsLoading(true); chatStore - .onUserInput( - userInput, - { - useImages, - mjImageMode, - setAutoScroll, - }, - attachImages, - ) + .onUserInput(userInput, attachImages, { + mjImageMode, + setAutoScroll, + }) .then(() => setIsLoading(false)); setAttachImages([]); localStorage.setItem(LAST_INPUT_KEY, userInput); setUserInput(""); - setUseImages([]); setMjImageMode("IMAGINE"); setPromptHints([]); if (!isMobileScreen) inputRef.current?.focus(); @@ -1393,6 +1359,8 @@ function _Chat() { className={styles["chat-message-item-image"]} src={getMessageImages(message)[0]} alt="" + width={100} + height={100} /> )} {getMessageImages(message).length > 1 && ( @@ -1413,6 +1381,8 @@ function _Chat() { key={index} src={image} alt="" + width={20} + height={20} /> ); })} @@ -1588,54 +1558,7 @@ function _Chat() { setUserInput("/"); onSearch(""); }} - imageSelected={(img: any) => { - if (useImages.length >= 5) { - alert(Locale.Midjourney.SelectImgMax(5)); - return; - } - setUseImages([...useImages, img]); - }} /> - {useImages.length > 0 && ( -
- {useImages.map((img: any, i) => ( - { - setUseImages(useImages.filter((_, ii) => ii != i)); - }} - title={img.filename} - alt={img.filename} - width={20} - height={20} - /> - ))} -
- {[ - { name: Locale.Midjourney.ModeImagineUseImg, value: "IMAGINE" }, - // { name: Locale.Midjourney.ModeBlend, value: "BLEND" }, - // { name: Locale.Midjourney.ModeDescribe, value: "DESCRIBE" }, - ].map((item, i) => ( - - ))} -
-
- {Locale.Midjourney.HasImgTip} -
-
- )}