From 8df8ee8936505f19bfbb59e550df5dca47253f49 Mon Sep 17 00:00:00 2001 From: Yidadaa Date: Mon, 10 Apr 2023 22:46:58 +0800 Subject: [PATCH 1/5] fix: #676 docker override old proxy files --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 018396ef..6aa1bfb4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -46,7 +46,7 @@ CMD if [ -n "$PROXY_URL" ]; then \ host=$(echo $PROXY_URL | cut -d/ -f3 | cut -d: -f1); \ port=$(echo $PROXY_URL | cut -d: -f3); \ conf=/etc/proxychains.conf; \ - echo "strict_chain" >> $conf; \ + echo "strict_chain" > $conf; \ echo "proxy_dns" >> $conf; \ echo "remote_dns_subnet 224" >> $conf; \ echo "tcp_read_time_out 15000" >> $conf; \ From 7aee53ea05494ef55412a1e2745a8a9ee8d497d8 Mon Sep 17 00:00:00 2001 From: Yidadaa Date: Mon, 10 Apr 2023 23:13:20 +0800 Subject: [PATCH 2/5] fix: #507 break cjk chars in stream mode --- app/api/chat-stream/route.ts | 2 +- app/requests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/api/chat-stream/route.ts b/app/api/chat-stream/route.ts index 526623ce..41f13549 100644 --- a/app/api/chat-stream/route.ts +++ b/app/api/chat-stream/route.ts @@ -40,7 +40,7 @@ async function createStream(req: NextRequest) { const parser = createParser(onParse); for await (const chunk of res.body as any) { - parser.feed(decoder.decode(chunk)); + parser.feed(decoder.decode(chunk, { stream: true })); } }, }); diff --git a/app/requests.ts b/app/requests.ts index ee3498c1..6254c7c7 100644 --- a/app/requests.ts +++ b/app/requests.ts @@ -171,7 +171,7 @@ export async function requestChatStream( const resTimeoutId = setTimeout(() => finish(), TIME_OUT_MS); const content = await reader?.read(); clearTimeout(resTimeoutId); - const text = decoder.decode(content?.value); + const text = decoder.decode(content?.value, { stream: true }); responseText += text; const done = !content || content.done; From 9b61cb1335b33fc889cb1db2c8a3624144772d86 Mon Sep 17 00:00:00 2001 From: Yidadaa Date: Tue, 11 Apr 2023 01:21:34 +0800 Subject: [PATCH 3/5] refactor: build/runtime/client configs --- Dockerfile | 1 - app/api/access.ts | 17 --------------- app/components/settings.tsx | 9 ++++---- app/config/build.ts | 27 ++++++++++++++++++++++++ app/config/client.ts | 42 +++++++++++++++++++++++++++++++++++++ app/config/server.ts | 42 +++++++++++++++++++++++++++++++++++++ app/constant.ts | 1 + app/layout.tsx | 31 +++------------------------ app/page.tsx | 19 ++++++++++++++++- app/store/access.ts | 8 ++++--- app/store/update.ts | 6 +++--- app/utils.ts | 25 ---------------------- middleware.ts | 8 ++++--- next.config.js | 9 +++----- 14 files changed, 154 insertions(+), 91 deletions(-) delete mode 100644 app/api/access.ts create mode 100644 app/config/build.ts create mode 100644 app/config/client.ts create mode 100644 app/config/server.ts diff --git a/Dockerfile b/Dockerfile index 6aa1bfb4..7ed7bc15 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,6 @@ RUN apk update && apk add --no-cache git ENV OPENAI_API_KEY="" ENV CODE="" -ARG DOCKER=true WORKDIR /app COPY --from=deps /app/node_modules ./node_modules diff --git a/app/api/access.ts b/app/api/access.ts deleted file mode 100644 index d3e4c9cf..00000000 --- a/app/api/access.ts +++ /dev/null @@ -1,17 +0,0 @@ -import md5 from "spark-md5"; - -export function getAccessCodes(): Set { - const code = process.env.CODE; - - try { - const codes = (code?.split(",") ?? []) - .filter((v) => !!v) - .map((v) => md5.hash(v.trim())); - return new Set(codes); - } catch (e) { - return new Set(); - } -} - -export const ACCESS_CODES = getAccessCodes(); -export const IS_IN_DOCKER = process.env.DOCKER; diff --git a/app/components/settings.tsx b/app/components/settings.tsx index bbb28b46..d3998596 100644 --- a/app/components/settings.tsx +++ b/app/components/settings.tsx @@ -26,13 +26,14 @@ import { import { Avatar } from "./chat"; import Locale, { AllLangs, changeLang, getLang } from "../locales"; -import { getCurrentVersion, getEmojiUrl } from "../utils"; +import { getEmojiUrl } from "../utils"; import Link from "next/link"; import { UPDATE_URL } from "../constant"; import { SearchService, usePromptStore } from "../store/prompt"; import { requestUsage } from "../requests"; import { ErrorBoundary } from "./error"; import { InputRange } from "./input-range"; +import { getClientSideConfig } from "../config/client"; function SettingItem(props: { title: string; @@ -88,9 +89,9 @@ export function Settings(props: { closeSettings: () => void }) { const updateStore = useUpdateStore(); const [checkingUpdate, setCheckingUpdate] = useState(false); - const currentId = getCurrentVersion(); + const currentVersion = getClientSideConfig()?.version; const remoteId = updateStore.remoteId; - const hasNewVersion = currentId !== remoteId; + const hasNewVersion = currentVersion !== remoteId; function checkUpdate(force = false) { setCheckingUpdate(true); @@ -224,7 +225,7 @@ export function Settings(props: { closeSettings: () => void }) { { + try { + const childProcess = require("child_process"); + return ( + childProcess + // .execSync("git describe --tags --abbrev=0") + .execSync("git rev-parse --short HEAD") + .toString() + .trim() + ); + } catch (e) { + console.error("[Build Config] No git or not from git repo."); + return "unknown"; + } +})(); + +export const getBuildConfig = () => { + if (typeof process === "undefined") { + throw Error( + "[Server Config] you are importing a nodejs-only module outside of nodejs", + ); + } + + return { + commitId: COMMIT_ID, + }; +}; diff --git a/app/config/client.ts b/app/config/client.ts new file mode 100644 index 00000000..0e9c50d0 --- /dev/null +++ b/app/config/client.ts @@ -0,0 +1,42 @@ +import { RUNTIME_CONFIG_DOM } from "../constant"; + +function queryMeta(key: string, defaultValue?: string): string { + let ret: string; + if (document) { + const meta = document.head.querySelector( + `meta[name='${key}']`, + ) as HTMLMetaElement; + ret = meta?.content ?? ""; + } else { + ret = defaultValue ?? ""; + } + + return ret; +} + +export function getClientSideConfig() { + if (typeof window === "undefined") { + throw Error( + "[Client Config] you are importing a browser-only module outside of browser", + ); + } + + const dom = document.getElementById(RUNTIME_CONFIG_DOM); + + if (!dom) { + throw Error("[Config] Dont get config before page loading!"); + } + + try { + const fromServerConfig = JSON.parse(dom.innerText) as DangerConfig; + const fromBuildConfig = { + version: queryMeta("version"), + }; + return { + ...fromServerConfig, + ...fromBuildConfig, + }; + } catch (e) { + console.error("[Config] failed to parse client config"); + } +} diff --git a/app/config/server.ts b/app/config/server.ts new file mode 100644 index 00000000..798177e5 --- /dev/null +++ b/app/config/server.ts @@ -0,0 +1,42 @@ +import md5 from "spark-md5"; + +declare global { + namespace NodeJS { + interface ProcessEnv { + OPENAI_API_KEY?: string; + CODE?: string; + PROXY_URL?: string; + VERCEL?: string; + } + } +} + +const ACCESS_CODES = (function getAccessCodes(): Set { + const code = process.env.CODE; + + try { + const codes = (code?.split(",") ?? []) + .filter((v) => !!v) + .map((v) => md5.hash(v.trim())); + return new Set(codes); + } catch (e) { + return new Set(); + } +})(); + +export const getServerSideConfig = () => { + if (typeof process === "undefined") { + throw Error( + "[Server Config] you are importing a nodejs-only module outside of nodejs", + ); + } + + return { + apiKey: process.env.OPENAI_API_KEY, + code: process.env.CODE, + codes: ACCESS_CODES, + needCode: ACCESS_CODES.size > 0, + proxyUrl: process.env.PROXY_URL, + isVercel: !!process.env.VERCEL, + }; +}; diff --git a/app/constant.ts b/app/constant.ts index 8a519d44..6f08ad75 100644 --- a/app/constant.ts +++ b/app/constant.ts @@ -5,3 +5,4 @@ export const ISSUE_URL = `https://github.com/${OWNER}/${REPO}/issues`; export const UPDATE_URL = `${REPO_URL}#keep-updated`; export const FETCH_COMMIT_URL = `https://api.github.com/repos/${OWNER}/${REPO}/commits?per_page=1`; export const FETCH_TAG_URL = `https://api.github.com/repos/${OWNER}/${REPO}/tags?per_page=1`; +export const RUNTIME_CONFIG_DOM = "danger-runtime-config"; diff --git a/app/layout.tsx b/app/layout.tsx index 49a6d644..38748ef3 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -2,19 +2,9 @@ import "./styles/globals.scss"; import "./styles/markdown.scss"; import "./styles/highlight.scss"; -import process from "child_process"; -import { ACCESS_CODES, IS_IN_DOCKER } from "./api/access"; +import { getBuildConfig } from "./config/build"; -let COMMIT_ID: string | undefined; -try { - COMMIT_ID = process - // .execSync("git describe --tags --abbrev=0") - .execSync("git rev-parse --short HEAD") - .toString() - .trim(); -} catch (e) { - console.error("No git or not from git repo."); -} +const buildConfig = getBuildConfig(); export const metadata = { title: "ChatGPT Next Web", @@ -26,21 +16,6 @@ export const metadata = { themeColor: "#fafafa", }; -function Meta() { - const metas = { - version: COMMIT_ID ?? "unknown", - access: ACCESS_CODES.size > 0 || IS_IN_DOCKER ? "enabled" : "disabled", - }; - - return ( - <> - {Object.entries(metas).map(([k, v]) => ( - - ))} - - ); -} - export default function RootLayout({ children, }: { @@ -58,7 +33,7 @@ export default function RootLayout({ content="#151515" media="(prefers-color-scheme: dark)" /> - + diff --git a/app/page.tsx b/app/page.tsx index 1d1da222..484e2c20 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,12 +1,29 @@ import { Analytics } from "@vercel/analytics/react"; import { Home } from "./components/home"; +import { getServerSideConfig } from "./config/server"; +import { RUNTIME_CONFIG_DOM } from "./constant"; + +const serverConfig = getServerSideConfig(); + +// Danger! Don not write any secret value here! +// 警告!不要在这里写入任何敏感信息! +const DANGER_CONFIG = { + needCode: serverConfig?.needCode, +}; + +declare global { + type DangerConfig = typeof DANGER_CONFIG; +} export default function App() { return ( <> +
+ {JSON.stringify(DANGER_CONFIG)} +
- + {serverConfig?.isVercel && } ); } diff --git a/app/store/access.ts b/app/store/access.ts index 5d43e632..9eafc3a4 100644 --- a/app/store/access.ts +++ b/app/store/access.ts @@ -1,6 +1,6 @@ import { create } from "zustand"; import { persist } from "zustand/middleware"; -import { queryMeta } from "../utils"; +import { getClientSideConfig } from "../config/client"; export interface AccessControlStore { accessCode: string; @@ -20,7 +20,7 @@ export const useAccessStore = create()( token: "", accessCode: "", enabledAccessControl() { - return queryMeta("access") === "enabled"; + return !!getClientSideConfig()?.needCode; }, updateCode(code: string) { set((state) => ({ accessCode: code })); @@ -30,7 +30,9 @@ export const useAccessStore = create()( }, isAuthorized() { // has token or has code or disabled access control - return !!get().token || !!get().accessCode || !get().enabledAccessControl(); + return ( + !!get().token || !!get().accessCode || !get().enabledAccessControl() + ); }, }), { diff --git a/app/store/update.ts b/app/store/update.ts index 97fb343c..78001f91 100644 --- a/app/store/update.ts +++ b/app/store/update.ts @@ -1,7 +1,7 @@ import { create } from "zustand"; import { persist } from "zustand/middleware"; +import { getClientSideConfig } from "../config/client"; import { FETCH_COMMIT_URL, FETCH_TAG_URL } from "../constant"; -import { getCurrentVersion } from "../utils"; export interface UpdateStore { lastUpdate: number; @@ -22,7 +22,7 @@ export const useUpdateStore = create()( const overTenMins = Date.now() - get().lastUpdate > 10 * 60 * 1000; const shouldFetch = force || overTenMins; if (!shouldFetch) { - return getCurrentVersion(); + return getClientSideConfig()?.version ?? ""; } try { @@ -38,7 +38,7 @@ export const useUpdateStore = create()( return remoteId; } catch (error) { console.error("[Fetch Upstream Commit Id]", error); - return getCurrentVersion(); + return getClientSideConfig()?.version ?? ""; } }, }), diff --git a/app/utils.ts b/app/utils.ts index 9a792fd5..5c2b0697 100644 --- a/app/utils.ts +++ b/app/utils.ts @@ -69,31 +69,6 @@ export function selectOrCopy(el: HTMLElement, content: string) { return true; } -export function queryMeta(key: string, defaultValue?: string): string { - let ret: string; - if (document) { - const meta = document.head.querySelector( - `meta[name='${key}']`, - ) as HTMLMetaElement; - ret = meta?.content ?? ""; - } else { - ret = defaultValue ?? ""; - } - - return ret; -} - -let currentId: string; -export function getCurrentVersion() { - if (currentId) { - return currentId; - } - - currentId = queryMeta("version"); - - return currentId; -} - export function getEmojiUrl(unified: string, style: EmojiStyle) { return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`; } diff --git a/middleware.ts b/middleware.ts index 9338a2c6..31a417a2 100644 --- a/middleware.ts +++ b/middleware.ts @@ -1,21 +1,23 @@ import { NextRequest, NextResponse } from "next/server"; -import { ACCESS_CODES } from "./app/api/access"; +import { getServerSideConfig } from "./app/config/server"; import md5 from "spark-md5"; export const config = { matcher: ["/api/openai", "/api/chat-stream"], }; +const serverConfig = getServerSideConfig(); + export function middleware(req: NextRequest) { const accessCode = req.headers.get("access-code"); const token = req.headers.get("token"); const hashedCode = md5.hash(accessCode ?? "").trim(); - console.log("[Auth] allowed hashed codes: ", [...ACCESS_CODES]); + console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]); console.log("[Auth] got access code:", accessCode); console.log("[Auth] hashed access code:", hashedCode); - if (ACCESS_CODES.size > 0 && !ACCESS_CODES.has(hashedCode) && !token) { + if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !token) { return NextResponse.json( { error: true, diff --git a/next.config.js b/next.config.js index fc164db9..f7d5ff08 100644 --- a/next.config.js +++ b/next.config.js @@ -8,14 +8,11 @@ const nextConfig = { config.module.rules.push({ test: /\.svg$/, use: ["@svgr/webpack"], - }); // 针对 SVG 的处理规则 + }); return config; - } + }, + output: "standalone", }; -if (process.env.DOCKER) { - nextConfig.output = 'standalone' -} - module.exports = nextConfig; From d6e6dd09f06ed2797bfe5b9ea4803213179bed97 Mon Sep 17 00:00:00 2001 From: Yidadaa Date: Tue, 11 Apr 2023 02:54:31 +0800 Subject: [PATCH 4/5] feat: dynamic config --- app/api/config/route.ts | 21 +++++ app/components/home.tsx | 161 ++++++++++++++++++------------------ app/components/settings.tsx | 7 +- app/config/client.ts | 42 ---------- app/page.tsx | 17 +--- app/store/access.ts | 30 ++++++- app/store/update.ts | 34 ++++++-- middleware.ts | 2 +- 8 files changed, 160 insertions(+), 154 deletions(-) create mode 100644 app/api/config/route.ts delete mode 100644 app/config/client.ts diff --git a/app/api/config/route.ts b/app/api/config/route.ts new file mode 100644 index 00000000..e04e22a0 --- /dev/null +++ b/app/api/config/route.ts @@ -0,0 +1,21 @@ +import { NextRequest, NextResponse } from "next/server"; + +import { getServerSideConfig } from "../../config/server"; + +const serverConfig = getServerSideConfig(); + +// Danger! Don not write any secret value here! +// 警告!不要在这里写入任何敏感信息! +const DANGER_CONFIG = { + needCode: serverConfig.needCode, +}; + +declare global { + type DangerConfig = typeof DANGER_CONFIG; +} + +export async function POST(req: NextRequest) { + return NextResponse.json({ + needCode: serverConfig.needCode, + }); +} diff --git a/app/components/home.tsx b/app/components/home.tsx index e73b8041..3055b688 100644 --- a/app/components/home.tsx +++ b/app/components/home.tsx @@ -2,13 +2,7 @@ require("../polyfill"); -import { - useState, - useEffect, - useRef, - useCallback, - MouseEventHandler, -} from "react"; +import { useState, useEffect, useRef } from "react"; import { IconButton } from "./button"; import styles from "./home.module.scss"; @@ -30,7 +24,6 @@ import { Chat } from "./chat"; import dynamic from "next/dynamic"; import { REPO_URL } from "../constant"; import { ErrorBoundary } from "./error"; -import { useDebounce } from "use-debounce"; export function Loading(props: { noLogo?: boolean }) { return ( @@ -165,96 +158,100 @@ function _Home() { } return ( -
+ <>
-
-
ChatGPT Next
-
- Build your own AI assistant. -
-
- -
-
-
{ - setOpenSettings(false); - setShowSideBar(false); - }} + className={ + styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}` + } > - -
- -
-
-
- } - onClick={chatStore.deleteSession} - /> +
+
ChatGPT Next
+
+ Build your own AI assistant.
-
+
+ +
+
+ +
{ + setOpenSettings(false); + setShowSideBar(false); + }} + > + +
+ +
+
+
+ } + onClick={chatStore.deleteSession} + /> +
+
+ } + onClick={() => { + setOpenSettings(true); + setShowSideBar(false); + }} + shadow + /> +
+ +
+
} + icon={} + text={Locale.Home.NewChat} onClick={() => { - setOpenSettings(true); + createNewSession(); setShowSideBar(false); }} shadow />
- -
-
- } - text={Locale.Home.NewChat} - onClick={() => { - createNewSession(); - setShowSideBar(false); - }} - shadow - />
+ +
onDragMouseDown(e as any)} + >
-
onDragMouseDown(e as any)} - >
+
+ {openSettings ? ( + { + setOpenSettings(false); + setShowSideBar(true); + }} + /> + ) : ( + setShowSideBar(true)} + sideBarShowing={showSideBar} + /> + )} +
- -
- {openSettings ? ( - { - setOpenSettings(false); - setShowSideBar(true); - }} - /> - ) : ( - setShowSideBar(true)} - sideBarShowing={showSideBar} - /> - )} -
-
+ ); } diff --git a/app/components/settings.tsx b/app/components/settings.tsx index d3998596..e418d484 100644 --- a/app/components/settings.tsx +++ b/app/components/settings.tsx @@ -33,7 +33,6 @@ import { SearchService, usePromptStore } from "../store/prompt"; import { requestUsage } from "../requests"; import { ErrorBoundary } from "./error"; import { InputRange } from "./input-range"; -import { getClientSideConfig } from "../config/client"; function SettingItem(props: { title: string; @@ -89,13 +88,13 @@ export function Settings(props: { closeSettings: () => void }) { const updateStore = useUpdateStore(); const [checkingUpdate, setCheckingUpdate] = useState(false); - const currentVersion = getClientSideConfig()?.version; - const remoteId = updateStore.remoteId; + const currentVersion = updateStore.version; + const remoteId = updateStore.remoteVersion; const hasNewVersion = currentVersion !== remoteId; function checkUpdate(force = false) { setCheckingUpdate(true); - updateStore.getLatestCommitId(force).then(() => { + updateStore.getLatestVersion(force).then(() => { setCheckingUpdate(false); }); } diff --git a/app/config/client.ts b/app/config/client.ts deleted file mode 100644 index 0e9c50d0..00000000 --- a/app/config/client.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { RUNTIME_CONFIG_DOM } from "../constant"; - -function queryMeta(key: string, defaultValue?: string): string { - let ret: string; - if (document) { - const meta = document.head.querySelector( - `meta[name='${key}']`, - ) as HTMLMetaElement; - ret = meta?.content ?? ""; - } else { - ret = defaultValue ?? ""; - } - - return ret; -} - -export function getClientSideConfig() { - if (typeof window === "undefined") { - throw Error( - "[Client Config] you are importing a browser-only module outside of browser", - ); - } - - const dom = document.getElementById(RUNTIME_CONFIG_DOM); - - if (!dom) { - throw Error("[Config] Dont get config before page loading!"); - } - - try { - const fromServerConfig = JSON.parse(dom.innerText) as DangerConfig; - const fromBuildConfig = { - version: queryMeta("version"), - }; - return { - ...fromServerConfig, - ...fromBuildConfig, - }; - } catch (e) { - console.error("[Config] failed to parse client config"); - } -} diff --git a/app/page.tsx b/app/page.tsx index 484e2c20..20b50317 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,27 +1,14 @@ import { Analytics } from "@vercel/analytics/react"; import { Home } from "./components/home"; + import { getServerSideConfig } from "./config/server"; -import { RUNTIME_CONFIG_DOM } from "./constant"; const serverConfig = getServerSideConfig(); -// Danger! Don not write any secret value here! -// 警告!不要在这里写入任何敏感信息! -const DANGER_CONFIG = { - needCode: serverConfig?.needCode, -}; - -declare global { - type DangerConfig = typeof DANGER_CONFIG; -} - -export default function App() { +export default async function App() { return ( <> -
- {JSON.stringify(DANGER_CONFIG)} -
{serverConfig?.isVercel && } diff --git a/app/store/access.ts b/app/store/access.ts index 9eafc3a4..aed13168 100644 --- a/app/store/access.ts +++ b/app/store/access.ts @@ -1,26 +1,33 @@ import { create } from "zustand"; import { persist } from "zustand/middleware"; -import { getClientSideConfig } from "../config/client"; export interface AccessControlStore { accessCode: string; token: string; + needCode: boolean; + updateToken: (_: string) => void; updateCode: (_: string) => void; enabledAccessControl: () => boolean; isAuthorized: () => boolean; + fetch: () => void; } export const ACCESS_KEY = "access-control"; +let fetchState = 0; // 0 not fetch, 1 fetching, 2 done + export const useAccessStore = create()( persist( (set, get) => ({ token: "", accessCode: "", + needCode: true, enabledAccessControl() { - return !!getClientSideConfig()?.needCode; + get().fetch(); + + return get().needCode; }, updateCode(code: string) { set((state) => ({ accessCode: code })); @@ -34,6 +41,25 @@ export const useAccessStore = create()( !!get().token || !!get().accessCode || !get().enabledAccessControl() ); }, + fetch() { + if (fetchState > 0) return; + fetchState = 1; + fetch("/api/config", { + method: "post", + body: null, + }) + .then((res) => res.json()) + .then((res: DangerConfig) => { + console.log("[Config] got config from server", res); + set(() => ({ ...res })); + }) + .catch(() => { + console.error("[Config] failed to fetch config"); + }) + .finally(() => { + fetchState = 2; + }); + }, }), { name: ACCESS_KEY, diff --git a/app/store/update.ts b/app/store/update.ts index 78001f91..efcdc8a7 100644 --- a/app/store/update.ts +++ b/app/store/update.ts @@ -1,28 +1,46 @@ import { create } from "zustand"; import { persist } from "zustand/middleware"; -import { getClientSideConfig } from "../config/client"; import { FETCH_COMMIT_URL, FETCH_TAG_URL } from "../constant"; export interface UpdateStore { lastUpdate: number; - remoteId: string; + remoteVersion: string; - getLatestCommitId: (force: boolean) => Promise; + version: string; + getLatestVersion: (force: boolean) => Promise; } export const UPDATE_KEY = "chat-update"; +function queryMeta(key: string, defaultValue?: string): string { + let ret: string; + if (document) { + const meta = document.head.querySelector( + `meta[name='${key}']`, + ) as HTMLMetaElement; + ret = meta?.content ?? ""; + } else { + ret = defaultValue ?? ""; + } + + return ret; +} + export const useUpdateStore = create()( persist( (set, get) => ({ lastUpdate: 0, - remoteId: "", + remoteVersion: "", + + version: "unknown", + + async getLatestVersion(force = false) { + set(() => ({ version: queryMeta("version") })); - async getLatestCommitId(force = false) { const overTenMins = Date.now() - get().lastUpdate > 10 * 60 * 1000; const shouldFetch = force || overTenMins; if (!shouldFetch) { - return getClientSideConfig()?.version ?? ""; + return get().version ?? "unknown"; } try { @@ -32,13 +50,13 @@ export const useUpdateStore = create()( const remoteId = (data[0].sha as string).substring(0, 7); set(() => ({ lastUpdate: Date.now(), - remoteId, + remoteVersion: remoteId, })); console.log("[Got Upstream] ", remoteId); return remoteId; } catch (error) { console.error("[Fetch Upstream Commit Id]", error); - return getClientSideConfig()?.version ?? ""; + return get().version ?? ""; } }, }), diff --git a/middleware.ts b/middleware.ts index 31a417a2..c2e07770 100644 --- a/middleware.ts +++ b/middleware.ts @@ -32,7 +32,7 @@ export function middleware(req: NextRequest) { // inject api key if (!token) { - const apiKey = process.env.OPENAI_API_KEY; + const apiKey = serverConfig.apiKey; if (apiKey) { console.log("[Auth] set system token"); req.headers.set("token", apiKey); From 6841846613ecdea74cdf37291c5ffd907085191f Mon Sep 17 00:00:00 2001 From: Yidadaa Date: Tue, 11 Apr 2023 02:56:48 +0800 Subject: [PATCH 5/5] fixup --- app/components/home.tsx | 150 +++++++++++++++++++--------------------- 1 file changed, 73 insertions(+), 77 deletions(-) diff --git a/app/components/home.tsx b/app/components/home.tsx index 3055b688..b9c6a8a3 100644 --- a/app/components/home.tsx +++ b/app/components/home.tsx @@ -158,100 +158,96 @@ function _Home() { } return ( - <> +
+
+
ChatGPT Next
+
+ Build your own AI assistant. +
+
+ +
+
+
{ + setOpenSettings(false); + setShowSideBar(false); + }} > -
-
ChatGPT Next
-
- Build your own AI assistant. -
-
- -
-
+ +
-
{ - setOpenSettings(false); - setShowSideBar(false); - }} - > - -
- -
-
-
- } - onClick={chatStore.deleteSession} - /> -
-
- } - onClick={() => { - setOpenSettings(true); - setShowSideBar(false); - }} - shadow - /> -
- -
-
+
+
+
} - text={Locale.Home.NewChat} + icon={} + onClick={chatStore.deleteSession} + /> +
+
+ } onClick={() => { - createNewSession(); + setOpenSettings(true); setShowSideBar(false); }} shadow />
+
- -
onDragMouseDown(e as any)} - >
-
- -
- {openSettings ? ( - { - setOpenSettings(false); - setShowSideBar(true); +
+ } + text={Locale.Home.NewChat} + onClick={() => { + createNewSession(); + setShowSideBar(false); }} + shadow /> - ) : ( - setShowSideBar(true)} - sideBarShowing={showSideBar} - /> - )} +
+ +
onDragMouseDown(e as any)} + >
- + +
+ {openSettings ? ( + { + setOpenSettings(false); + setShowSideBar(true); + }} + /> + ) : ( + setShowSideBar(true)} + sideBarShowing={showSideBar} + /> + )} +
+
); }