diff --git a/.env.example b/.env.example index b64cef0..e2c860e 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,6 @@ -NezhaBaseUrl=http://1.1.1.1:8008 -NezhaAuth=nezha-token -ServerDisablePrefetch=false -NEXT_PUBLIC_NezhaFetchInterval=2000 +NezhaBaseUrl=http://124.XX.XX.XX:8008 +NezhaAuth=your-nezha-api-token +DefaultLocale=zh +NEXT_PUBLIC_NezhaFetchInterval=5000 NEXT_PUBLIC_ShowFlag=true -NEXT_PUBLIC_DisableCartoon=false \ No newline at end of file +NEXT_PUBLIC_DisableCartoon=true \ No newline at end of file diff --git a/.github/workflows/Deploy.yml b/.github/workflows/Deploy.yml index 2bed758..5e2c76f 100644 --- a/.github/workflows/Deploy.yml +++ b/.github/workflows/Deploy.yml @@ -5,8 +5,40 @@ on: tags: - "v*" +env: + REGISTRY_IMAGE: hamster1963/nezha-dash + ALIYUN_REGISTRY_IMAGE: registry.cn-guangzhou.aliyuncs.com/hamster-home/nezha-dash + jobs: + changelog: + name: Generate Changelog + runs-on: ubuntu-latest + outputs: + release_body: ${{ steps.git-cliff.outputs.content }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Generate a changelog + uses: orhun/git-cliff-action@v4 + id: git-cliff + with: + config: git-cliff-config/cliff.toml + args: -vv --latest --strip 'footer' + env: + OUTPUT: CHANGES.md + - name: Release + uses: softprops/action-gh-release@v2 + if: startsWith(github.ref, 'refs/tags/') + with: + body: ${{ steps.git-cliff.outputs.content }} + token: ${{ secrets.GITHUB_TOKEN }} + env: + GITHUB_REPOSITORY: ${{ github.repository }} + build-and-push: + name: Build and push Docker image runs-on: ubuntu-latest environment: Production steps: @@ -37,8 +69,8 @@ jobs: uses: docker/metadata-action@v5 with: images: | - hamster1963/nezha-dash - registry.cn-guangzhou.aliyuncs.com/hamster-home/nezha-dash + ${{ env.REGISTRY_IMAGE }} + ${{ env.ALIYUN_REGISTRY_IMAGE }} tags: | type=raw,value=latest type=ref,event=tag diff --git a/README.md b/README.md index bf886ce..2291b6d 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,14 @@ #### 环境变量 -| 变量名 | 含义 | 示例 | -| ------------------------------ | -------------------- | -------------------------------- | -| NezhaBaseUrl | nezha 面板地址 | http://120.x.x.x:8008 | -| NezhaAuth | nezha 面板 API Token | 5hAY3QX6Nl9B3Uxxxx26KMvOMyXS1Udi | -| ServerDisablePrefetch | 是否禁用预加载 | **默认**:false | -| NEXT_PUBLIC_NezhaFetchInterval | 获取数据间隔(毫秒) | **默认**:2000 | -| NEXT_PUBLIC_ShowFlag | 是否显示旗帜 | **默认**:false | -| NEXT_PUBLIC_DisableCartoon | 是否禁用卡通人物 | **默认**:false | +| 变量名 | 含义 | 示例 | +| ------------------------------ | -------------------------------- | -------------------------------- | +| NezhaBaseUrl | nezha 面板地址 | http://120.x.x.x:8008 | +| NezhaAuth | nezha 面板 API Token | 5hAY3QX6Nl9B3Uxxxx26KMvOMyXS1Udi | +| DefaultLocale | 面板默认显示语言(代码参考下表) | **默认**:en | +| NEXT_PUBLIC_NezhaFetchInterval | 获取数据间隔(毫秒) | **默认**:2000 | +| NEXT_PUBLIC_ShowFlag | 是否显示旗帜 | **默认**:false | +| NEXT_PUBLIC_DisableCartoon | 是否禁用卡通人物 | **默认**:false | #### 多语言支持 diff --git a/app/[locale]/(main)/ClientComponents/ServerListClient.tsx b/app/[locale]/(main)/ClientComponents/ServerListClient.tsx index 756c5ca..6d4b586 100644 --- a/app/[locale]/(main)/ClientComponents/ServerListClient.tsx +++ b/app/[locale]/(main)/ClientComponents/ServerListClient.tsx @@ -6,18 +6,29 @@ import { nezhaFetcher } from "../../../../lib/utils"; import useSWR from "swr"; import getEnv from "../../../../lib/env-entry"; export default function ServerListClient() { - const { data } = useSWR("/api/server", nezhaFetcher, { + const { data, error } = useSWR("/api/server", nezhaFetcher, { refreshInterval: Number(getEnv("NEXT_PUBLIC_NezhaFetchInterval")) || 2000, }); + if (error) + return ( +
+

{error.message}

+

+ Please check your environment variables and review the server console + logs for more details. +

+
+ ); if (!data) return null; - const sortedServers = data.result.sort((a, b) => { - if (a.display_index && b.display_index) { - return b.display_index - a.display_index; - } - if (a.display_index) return -1; - if (b.display_index) return 1; + + const { result } = data; + + const sortedServers = result.sort((a, b) => { + const displayIndexDiff = (b.display_index || 0) - (a.display_index || 0); + if (displayIndexDiff !== 0) return displayIndexDiff; return a.id - b.id; }); + return (
{sortedServers.map((serverInfo) => ( diff --git a/app/[locale]/(main)/page.tsx b/app/[locale]/(main)/page.tsx index 1c3f65e..4bbb174 100644 --- a/app/[locale]/(main)/page.tsx +++ b/app/[locale]/(main)/page.tsx @@ -1,9 +1,15 @@ +import { unstable_setRequestLocale } from "next-intl/server"; import ServerList from "../../../components/ServerList"; import ServerOverview from "../../../components/ServerOverview"; export const runtime = 'edge'; -export default function Home() { +export default function Home({ + params: { locale }, +}: { + params: { locale: string }; +}) { + unstable_setRequestLocale(locale); return (
diff --git a/app/[locale]/layout.tsx b/app/[locale]/layout.tsx index 46993ac..2410b08 100644 --- a/app/[locale]/layout.tsx +++ b/app/[locale]/layout.tsx @@ -1,6 +1,8 @@ // @auto-i18n-check. Please do not delete the line. import "@/styles/globals.css"; +import "/node_modules/flag-icons/css/flag-icons.min.css"; + import React from "react"; import { NextIntlClientProvider, useMessages } from "next-intl"; import { PublicEnvScript } from "next-runtime-env"; @@ -10,6 +12,7 @@ import { ThemeProvider } from "next-themes"; import { Viewport } from "next"; import { cn } from "@/lib/utils"; import { locales } from "@/i18n-metadata"; +import { unstable_setRequestLocale } from "next-intl/server"; const fontSans = FontSans({ subsets: ["latin"], @@ -34,11 +37,12 @@ export const viewport: Viewport = { userScalable: false, }; -export function generateStaticParams() { +export const dynamic = "force-static"; + +export async function generateStaticParams() { return locales.map((locale) => ({ locale })); } - export default function LocaleLayout({ children, params: { locale }, @@ -46,6 +50,8 @@ export default function LocaleLayout({ children: React.ReactNode; params: { locale: string }; }) { + unstable_setRequestLocale(locale); + const messages = useMessages(); return ( diff --git a/app/api/server/route.ts b/app/api/server/route.ts index b7c5583..84cc817 100644 --- a/app/api/server/route.ts +++ b/app/api/server/route.ts @@ -8,17 +8,18 @@ export const dynamic = "force-dynamic"; export const runtime = 'edge'; +interface NezhaDataResponse { + error?: string; + data?: ServerApi; +} + export async function GET(_: Request) { - try { - const response = await GetNezhaData(); - return NextResponse.json(response, { status: 200 }); - } catch (error) { - console.error(error); - return NextResponse.json( - { error: "fetch nezha data failed" }, - { status: 400 }, - ); + const response = (await GetNezhaData()) as NezhaDataResponse; + if (response.error) { + console.log(response.error); + return NextResponse.json({ error: response.error }, { status: 400 }); } + return NextResponse.json(response, { status: 200 }); } async function GetNezhaData() { diff --git a/bun.lockb b/bun.lockb index 0667cb3..6139404 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/components/ServerCard.tsx b/components/ServerCard.tsx index 666e158..8111f24 100644 --- a/components/ServerCard.tsx +++ b/components/ServerCard.tsx @@ -9,8 +9,9 @@ import { } from "@/components/ui/popover"; import { cn, formatNezhaInfo } from "@/lib/utils"; import ServerCardPopover from "./ServerCardPopover"; -import getUnicodeFlagIcon from "country-flag-icons/unicode"; + import { env } from "next-runtime-env"; +import ServerFlag from "./ServerFlag"; export default function ServerCard({ serverInfo, @@ -32,15 +33,7 @@ export default function ServerCard({
- {showFlag ? ( - country_code ? ( - - {getUnicodeFlagIcon(country_code)} - - ) : ( - 🏁 - ) - ) : null} + {showFlag ? : null}

- {" "} - {/* 设置固定宽度 */}

{t("CPU")}

{cpu.toFixed(2)}% @@ -67,8 +58,6 @@ export default function ServerCard({
- {" "} - {/* 设置固定宽度 */}

{t("Mem")}

{mem.toFixed(2)}% @@ -76,8 +65,6 @@ export default function ServerCard({
- {" "} - {/* 设置固定宽度 */}

{t("STG")}

{stg.toFixed(2)}% @@ -85,8 +72,6 @@ export default function ServerCard({
- {" "} - {/* 设置固定宽度 */}

{t("Upload")}

{up.toFixed(2)} @@ -94,8 +79,6 @@ export default function ServerCard({
- {" "} - {/* 设置固定宽度 */}

{t("Download")}

{down.toFixed(2)} @@ -113,15 +96,7 @@ export default function ServerCard({
- {showFlag ? ( - country_code ? ( - - {getUnicodeFlagIcon(country_code)} - - ) : ( - 🏁 - ) - ) : null} + {showFlag ? : null}

{ + const checkEmojiSupport = () => { + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + const emojiFlag = "🇺🇸"; // 使用美国国旗作为测试 + if (!ctx) return; + ctx.fillStyle = "#000"; + ctx.textBaseline = "top"; + ctx.font = "32px Arial"; + ctx.fillText(emojiFlag, 0, 0); + + const support = ctx.getImageData(16, 16, 1, 1).data[3] !== 0; + setSupportsEmojiFlags(support); + }; + + checkEmojiSupport(); + }, []); + + if (!country_code) return null; + + return ( + + {!supportsEmojiFlags ? ( + + ) : ( + getUnicodeFlagIcon(country_code) + )} + + ); +} diff --git a/docker/.env.example b/docker/.env.example index b811421..e2c860e 100644 --- a/docker/.env.example +++ b/docker/.env.example @@ -1,6 +1,6 @@ -NezhaBaseUrl=http://0.0.0.0:8008 -NezhaAuth=5hAY3QX6Nl9B3UOQgB26KdsdS1dsdUdM -ServerDisablePrefetch=false +NezhaBaseUrl=http://124.XX.XX.XX:8008 +NezhaAuth=your-nezha-api-token +DefaultLocale=zh NEXT_PUBLIC_NezhaFetchInterval=5000 NEXT_PUBLIC_ShowFlag=true NEXT_PUBLIC_DisableCartoon=true \ No newline at end of file diff --git a/git-cliff-config/cliff.toml b/git-cliff-config/cliff.toml new file mode 100644 index 0000000..940461c --- /dev/null +++ b/git-cliff-config/cliff.toml @@ -0,0 +1,83 @@ +# git-cliff ~ configuration file +# https://git-cliff.org/docs/configuration +# +# Lines starting with "#" are comments. +# Configuration options are organized into tables and keys. +# See documentation for more information on available options. + +[changelog] +# changelog header +header = """ +# Changelog\n +""" +# template for the changelog body +# https://tera.netlify.app/docs/ +body = """ +{% if version %}\ + ## Release {{ version | trim_start_matches(pat="v") }} - {{ timestamp | date(format="%Y-%m-%d") }} +{% else %}\ + ## [unreleased] +{% endif %}\ + +{% for group, commits in commits | group_by(attribute="group") %} + ### {{ group | upper_first }} + {% for commit in commits %} + * {{ commit.message | upper_first }} ([{{ commit.id | truncate(length=7, end="") }}]($REPO/commit/{{ commit.id }})) by [@{{ commit.author.name }}](https://github.com/{{ commit.author.name }})\ + {% for footer in commit.footers -%} + , {{ footer.token }}{{ footer.separator }}{{ footer.value }}\ + {% endfor %}\ + {% endfor %} +{% endfor %}\n +""" +# remove the leading and trailing whitespace from the template +trim = true +postprocessors = [ + { pattern = '\$REPO', replace = "https://github.com/hamster1963/nezha-dash" }, # replace repository URL +] +# changelog footer +footer = """ +""" + + +[git] +# parse the commits based on https://www.conventionalcommits.org +conventional_commits = true +# filter out the commits that are not conventional +filter_unconventional = true +# process each line of a commit as an individual commit +split_commits = true +# regex for preprocessing the commit messages +commit_preprocessors = [ + { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/orhun/git-cliff/issues/${2}))" }, +] +# regex for parsing and grouping commits +commit_parsers = [ + { message = "^feat", group = "⛰️ Features" }, + { message = "^fix", group = "🐛 Bug Fixes" }, + { message = "^doc", group = "📚 Documentation" }, + { message = "^perf", group = "⚡ Performance" }, + { message = "^refactor", group = "🚜 Refactor" }, + { message = "^style", group = "🎨 Styling" }, + { message = "^test", group = "🧪 Testing" }, + { message = "^chore\\(release\\): prepare for", skip = true }, + { message = "^chore\\(pr\\)", skip = true }, + { message = "^chore\\(pull\\)", skip = true }, + { message = "^chore", group = "⚙️ Miscellaneous Tasks" }, + { body = ".*security", group = "🛡️ Security" }, + { message = "^update", group = "🔼 Updates" }, + { message = "^delete", group = "🔞 Delete" }, +] +# protect breaking changes from being skipped due to matching a skipping commit_parser +protect_breaking_commits = false +# filter out the commits that are not matched by commit parsers +filter_commits = false +# glob pattern for matching git tags +tag_pattern = "v[0-20]*" +# regex for skipping tags +skip_tags = "" +# regex for ignoring tags +ignore_tags = "v.*-beta.*" +# sort the tags topologically +topo_order = false +# sort the commits inside sections by oldest/newest order +sort_commits = "oldest" diff --git a/i18n-metadata.ts b/i18n-metadata.ts index acf3a7c..3151be8 100644 --- a/i18n-metadata.ts +++ b/i18n-metadata.ts @@ -1,5 +1,7 @@ // @auto-i18n-check. Please do not delete the line. +import getEnv from "./lib/env-entry"; + export const localeItems = [ { code: "en", name: "English" }, { code: "ja", name: "日本語" }, @@ -21,4 +23,4 @@ export const localeItems = [ ]; export const locales = localeItems.map((item) => item.code); -export const defaultLocale = "en"; +export const defaultLocale = getEnv("DefaultLocale") || "en"; diff --git a/lib/serverFetch.tsx b/lib/serverFetch.tsx index 15d16f1..d8fa983 100644 --- a/lib/serverFetch.tsx +++ b/lib/serverFetch.tsx @@ -10,8 +10,8 @@ export async function GetNezhaData() { var nezhaBaseUrl = getEnv("NezhaBaseUrl"); if (!nezhaBaseUrl) { - console.error("NezhaBaseUrl is not set"); - throw new Error("NezhaBaseUrl is not set"); + console.log("NezhaBaseUrl is not set"); + return { error: "NezhaBaseUrl is not set" }; } // Remove trailing slash @@ -27,7 +27,12 @@ export async function GetNezhaData() { revalidate: 0, }, }); - const nezhaData = (await response.json()).result as NezhaAPI[]; + const resData = await response.json(); + const nezhaData = resData.result as NezhaAPI[]; + if (!nezhaData) { + console.log(resData); + return { error: "NezhaData fetch failed" }; + } const data: ServerApi = { live_servers: 0, offline_servers: 0, diff --git a/middleware.ts b/middleware.ts index a4b787c..ebcec7e 100644 --- a/middleware.ts +++ b/middleware.ts @@ -1,14 +1,14 @@ // @auto-i18n-check. Please do not delete the line. import createMiddleware from "next-intl/middleware"; -import { locales } from "./i18n-metadata"; +import { defaultLocale, locales } from "./i18n-metadata"; export default createMiddleware({ // A list of all locales that are supported locales: locales, // Used when no locale matches - defaultLocale: "en", + defaultLocale: defaultLocale, // 'always': This is the default, The home page will also be redirected to the default language, such as www.abc.com to www.abc.com/en // 'as-needed': The default page is not redirected. For example, if you open www.abc.com, it is still www.abc.com diff --git a/next.config.mjs b/next.config.mjs index 5234c22..397de22 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -1,3 +1,9 @@ +import withBundleAnalyzer from "@next/bundle-analyzer"; + +const bundleAnalyzer = withBundleAnalyzer({ + enabled: process.env.ANALYZE === "true", +}); + import createNextIntlPlugin from "next-intl/plugin"; const withNextIntl = createNextIntlPlugin(); import withPWAInit from "@ducanh2912/next-pwa"; @@ -16,5 +22,10 @@ const withPWA = withPWAInit({ const nextConfig = { output: "standalone", reactStrictMode: true, + logging: { + fetches: { + fullUrl: true, + }, + }, }; -export default withPWA(withNextIntl(nextConfig)); +export default bundleAnalyzer(withPWA(withNextIntl(nextConfig))); diff --git a/package.json b/package.json index 0f6a9e7..40ad458 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "clsx": "^2.1.1", "country-flag-icons": "^1.5.13", "eslint-plugin-simple-import-sort": "^12.1.1", + "flag-icons": "^7.2.3", "lucide-react": "^0.414.0", "luxon": "^3.5.0", "next": "^14.2.13", @@ -47,8 +48,8 @@ "eslint-plugin-turbo": "^2.1.2", "eslint-plugin-unused-imports": "^4.1.4", "@next/bundle-analyzer": "^14.2.13", - "@types/node": "^22.7.2", - "@types/react": "^18.3.9", + "@types/node": "^22.7.4", + "@types/react": "^18.3.10", "@types/react-dom": "^18.3.0", "autoprefixer": "^10.4.20", "eslint": "^9.11.1",