From 809b7c55018d4f3e0febebd139a19f5fd8745d70 Mon Sep 17 00:00:00 2001 From: Justin Date: Tue, 24 Nov 2026 19:36:56 +0800 Subject: [PATCH] feat(sub): allow switching the inline QR code format on the subscription page (#7157) The large QR card on the subscription page always encoded the raw link, so a Clash/Mihomo or JSON user who scanned it got a profile their client could not parse. Add a SUB / JSON / CLASH switch under the card for the enabled formats. The card starts on the format of the route the page was opened through: the server puts subFormat into the page data, so the /mihomo/ and /clash-legacy/ aliases start on CLASH as well. --- frontend/src/env.d.ts | 1 + frontend/src/pages/sub/SubLinksTab.tsx | 64 ++++++++++++++++--- frontend/src/pages/sub/SubPage.css | 8 +++ frontend/src/pages/sub/SubPage.tsx | 2 + frontend/src/test/sub-links-tab.test.tsx | 81 ++++++++++++++++++++++++ internal/sub/controller.go | 16 +++-- internal/sub/info_endpoint_test.go | 47 ++++++++++++++ internal/sub/service.go | 1 + 8 files changed, 207 insertions(+), 13 deletions(-) create mode 100644 frontend/src/test/sub-links-tab.test.tsx diff --git a/frontend/src/env.d.ts b/frontend/src/env.d.ts index 6aff7f8be..e71d9d2d4 100644 --- a/frontend/src/env.d.ts +++ b/frontend/src/env.d.ts @@ -14,6 +14,7 @@ interface SubPageData { subUrl?: string; subJsonUrl?: string; subClashUrl?: string; + subFormat?: 'raw' | 'json' | 'clash'; subTitle?: string; subSupportUrl?: string; subUpdates?: number; diff --git a/frontend/src/pages/sub/SubLinksTab.tsx b/frontend/src/pages/sub/SubLinksTab.tsx index 3b3324af3..69233e4df 100644 --- a/frontend/src/pages/sub/SubLinksTab.tsx +++ b/frontend/src/pages/sub/SubLinksTab.tsx @@ -1,33 +1,70 @@ +import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Button, QRCode, Tag } from 'antd'; +import { Button, QRCode, Segmented, Tag } from 'antd'; import { CopyOutlined, DownloadOutlined } from '@ant-design/icons'; import SubQrButton from './SubQrButton'; +type SubLinkKind = 'SUB' | 'JSON' | 'CLASH'; + +interface SubLinkRow { + kind: SubLinkKind; + color: string; + url: string; + title: string; + downloadable: boolean; +} + +type SubPageFormat = NonNullable; + interface SubLinksTabProps { subUrl: string; subJsonUrl: string; subClashUrl: string; + format: SubPageFormat; onCopy: (value: string) => void; } const appendRawView = (url: string) => `${url}${url.includes('?') ? '&' : '?'}view=raw`; -export default function SubLinksTab({ subUrl, subJsonUrl, subClashUrl, onCopy }: SubLinksTabProps) { +// The server names the format of the route that rendered the page; aliases +// such as /mihomo/ and /clash-legacy/ never match a row URL, so paths cannot. +const QR_KIND_BY_FORMAT: Record = { + raw: 'SUB', + json: 'JSON', + clash: 'CLASH', +}; + +export default function SubLinksTab({ + subUrl, + subJsonUrl, + subClashUrl, + format, + onCopy, +}: SubLinksTabProps) { const { t } = useTranslation(); const subLabel = t('pages.settings.subSettings'); - const rows = [ - { kind: 'SUB', color: 'green', url: subUrl, title: subLabel, downloadable: false }, + const rows: SubLinkRow[] = [ + { kind: 'SUB' as const, color: 'green', url: subUrl, title: subLabel, downloadable: false }, { - kind: 'JSON', + kind: 'JSON' as const, color: 'purple', url: subJsonUrl, title: `${subLabel} JSON`, downloadable: true, }, - { kind: 'CLASH', color: 'gold', url: subClashUrl, title: 'Clash / Mihomo', downloadable: true }, + { + kind: 'CLASH' as const, + color: 'gold', + url: subClashUrl, + title: 'Clash / Mihomo', + downloadable: true, + }, ].filter((row) => row.url); + const [selectedKind, setSelectedKind] = useState(QR_KIND_BY_FORMAT[format]); + const activeRow = rows.find((row) => row.kind === selectedKind) ?? rows[0]; + return (
{rows.map((row) => ( @@ -64,11 +101,11 @@ export default function SubLinksTab({ subUrl, subJsonUrl, subClashUrl, onCopy }:
))} - {subUrl && ( + {activeRow && (
-
+
{t('subscription.scanTitle')}
{t('subscription.scanHint')}
+ {rows.length > 1 && ( + + size="small" + className="sub-qr-segmented" + value={activeRow.kind} + onChange={setSelectedKind} + options={rows.map((row) => ({ value: row.kind, label: row.kind }))} + /> + )}
)} diff --git a/frontend/src/pages/sub/SubPage.css b/frontend/src/pages/sub/SubPage.css index 7c897e514..adef43d9f 100644 --- a/frontend/src/pages/sub/SubPage.css +++ b/frontend/src/pages/sub/SubPage.css @@ -397,6 +397,10 @@ a.sub-row-title:hover { line-height: 0; } +.sub-qr-body { + min-width: 0; +} + .sub-qr-title { margin-bottom: 4px; font-size: 15px; @@ -404,6 +408,10 @@ a.sub-row-title:hover { color: var(--ant-color-text); } +.sub-qr-segmented { + margin-top: 10px; +} + /* apps */ .sub-apps { display: flex; diff --git a/frontend/src/pages/sub/SubPage.tsx b/frontend/src/pages/sub/SubPage.tsx index 5a548358f..d001c37cb 100644 --- a/frontend/src/pages/sub/SubPage.tsx +++ b/frontend/src/pages/sub/SubPage.tsx @@ -27,6 +27,7 @@ const sId = subData.sId || ''; const subUrl = subData.subUrl || ''; const subJsonUrl = subData.subJsonUrl || ''; const subClashUrl = subData.subClashUrl || ''; +const subFormat = subData.subFormat || 'raw'; const subTitle = subData.subTitle || ''; const subSupportUrl = subData.subSupportUrl || ''; const updateHours = Number(subData.subUpdates || 0); @@ -99,6 +100,7 @@ export default function SubPage() { subUrl={subUrl} subJsonUrl={subJsonUrl} subClashUrl={subClashUrl} + format={subFormat} onCopy={copy} /> ), diff --git a/frontend/src/test/sub-links-tab.test.tsx b/frontend/src/test/sub-links-tab.test.tsx new file mode 100644 index 000000000..dcf7a80b2 --- /dev/null +++ b/frontend/src/test/sub-links-tab.test.tsx @@ -0,0 +1,81 @@ +import { fireEvent, render, within } from '@testing-library/react'; +import { QRCode } from 'antd'; +import { describe, expect, it, vi } from 'vitest'; + +import SubLinksTab from '@/pages/sub/SubLinksTab'; +import { renderWithProviders } from './test-utils'; + +const SUB_URL = 'https://vpn.example.com/sub/abc'; +const JSON_URL = 'https://vpn.example.com/json/abc'; +const CLASH_URL = 'https://vpn.example.com/clash/abc'; + +function expectedQrMarkup(value: string): string { + const { container, unmount } = render( + , + ); + const html = container.querySelector('svg')?.innerHTML ?? ''; + unmount(); + return html; +} + +describe('SubLinksTab inline QR card', () => { + it('switches the inline QR code between enabled subscription formats', () => { + const view = renderWithProviders( + , + ); + + const card = view.container.querySelector('.sub-qr-card') as HTMLElement; + expect(card).not.toBeNull(); + const qrSvg = () => card.querySelector('.sub-qr-code svg')?.innerHTML; + + expect(qrSvg()).toBe(expectedQrMarkup(SUB_URL)); + expect(qrSvg()).not.toBe(expectedQrMarkup(CLASH_URL)); + + fireEvent.click(within(card).getByText('CLASH')); + expect(qrSvg()).toBe(expectedQrMarkup(CLASH_URL)); + + fireEvent.click(within(card).getByText('JSON')); + expect(qrSvg()).toBe(expectedQrMarkup(JSON_URL)); + }); + + it.each([ + ['clash', CLASH_URL], + ['json', JSON_URL], + ] as const)('starts on the %s QR code when that route rendered the page', (format, url) => { + const view = renderWithProviders( + , + ); + + const card = view.container.querySelector('.sub-qr-card') as HTMLElement; + expect(card.querySelector('.sub-qr-code svg')?.innerHTML).toBe(expectedQrMarkup(url)); + }); + + it('offers no switcher when only the raw subscription is enabled', () => { + const view = renderWithProviders( + , + ); + + const card = view.container.querySelector('.sub-qr-card') as HTMLElement; + expect(card.querySelector('.sub-qr-code svg')?.innerHTML).toBe(expectedQrMarkup(SUB_URL)); + expect(card.querySelector('.ant-segmented')).toBeNull(); + }); +}); diff --git a/internal/sub/controller.go b/internal/sub/controller.go index 05da499ad..f726bd93c 100644 --- a/internal/sub/controller.go +++ b/internal/sub/controller.go @@ -28,6 +28,11 @@ import ( const ( subMihomoPath = "/mihomo/" subClashLegacyPath = "/clash-legacy/" + + // Which subscription format the route that rendered the page serves. + subPageFormatRaw = "raw" + subPageFormatJSON = "json" + subPageFormatClash = "clash" ) // writeSubError translates a service-layer result into an HTTP response. @@ -400,7 +405,7 @@ func (a *SUBController) configuredSubscriptionPathOwner(candidate string) string // info is for the content a client app imports — the raw subscription body. A // browser viewing the HTML info page gets clean, name-only remarks (usage is // shown in the page summary). -func (a *SUBController) maybeServeSubPage(c *gin.Context) bool { +func (a *SUBController) maybeServeSubPage(c *gin.Context, format string) bool { accept := c.GetHeader("Accept") wantsHTML := strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html") if !wantsHTML { @@ -410,6 +415,7 @@ func (a *SUBController) maybeServeSubPage(c *gin.Context) bool { if !ok { return true } + page.Format = format a.serveSubPage(c, page.BasePath, page) return true } @@ -424,6 +430,7 @@ func (a *SUBController) maybeServeSubInfo(c *gin.Context) bool { } info := a.subPageContext(page) delete(info, "links") + delete(info, "subFormat") info["emails"] = dedupeEmails(page.Emails) c.JSON(http.StatusOK, info) return true @@ -480,7 +487,7 @@ func (a *SUBController) subs(c *gin.Context) { logSubscriptionRoute(userAgent, "info") return } - if a.maybeServeSubPage(c) { + if a.maybeServeSubPage(c, subPageFormatRaw) { logSubscriptionRoute(userAgent, "html") return } @@ -705,6 +712,7 @@ func (a *SUBController) subPageContext(page PageData) map[string]any { "subUrl": page.SubUrl, "subJsonUrl": page.SubJsonUrl, "subClashUrl": page.SubClashUrl, + "subFormat": page.Format, "subTitle": page.SubTitle, "subSupportUrl": page.SubSupportUrl, "subUpdates": updateHours, @@ -825,7 +833,7 @@ func (a *SUBController) subJsons(c *gin.Context) { a.recordSubscriptionFetch(c) return } - if a.maybeServeSubPage(c) { + if a.maybeServeSubPage(c, subPageFormatJSON) { return } if !a.enforceHwid(c) { @@ -887,7 +895,7 @@ func (a *SUBController) subClash(c *gin.Context, legacy bool) { a.recordSubscriptionFetch(c) return } - if a.maybeServeSubPage(c) { + if a.maybeServeSubPage(c, subPageFormatClash) { return } if !a.enforceHwid(c) { diff --git a/internal/sub/info_endpoint_test.go b/internal/sub/info_endpoint_test.go index be41202ca..ddb2f583e 100644 --- a/internal/sub/info_endpoint_test.go +++ b/internal/sub/info_endpoint_test.go @@ -128,3 +128,50 @@ func TestSubInfoEndpoint_HTMLPageStillWinsWithoutFormatParam(t *testing.T) { t.Fatalf("injected page data must carry isOnline; body=%s", w.Body.String()) } } + +func TestSubPageDataNamesTheFormatOfTheVisitedRoute(t *testing.T) { + gin.SetMode(gin.TestMode) + initSubDB(t) + seedInfoEndpointSub(t, "fmt-sub", "fmt@x") + for key, value := range map[string]string{ + "subPath": "/sub/", "subJsonPath": "/json/", "subClashPath": "/clash/", + "subJsonEnable": "true", "subClashEnable": "true", + } { + if err := database.GetDB().Where("key = ?", key).Delete(&model.Setting{}).Error; err != nil { + t.Fatalf("clear %s: %v", key, err) + } + if err := database.GetDB().Create(&model.Setting{Key: key, Value: value}).Error; err != nil { + t.Fatalf("set %s: %v", key, err) + } + } + oldDistFS := distFS + distFS = testDistFS + t.Cleanup(func() { distFS = oldDistFS }) + + router, err := (&Server{}).initRouter() + if err != nil { + t.Fatal(err) + } + + for path, want := range map[string]string{ + "/sub/fmt-sub": "raw", + "/json/fmt-sub": "json", + "/clash/fmt-sub": "clash", + "/mihomo/fmt-sub": "clash", + "/clash-legacy/fmt-sub": "clash", + } { + t.Run(path, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Host = "sub.example.com" + req.Header.Set("Accept", "text/html") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String()) + } + if marker := `"subFormat":"` + want + `"`; !strings.Contains(w.Body.String(), marker) { + t.Fatalf("page data lacks %s; body=%s", marker, w.Body.String()) + } + }) + } +} diff --git a/internal/sub/service.go b/internal/sub/service.go index 2680563e4..a0d79a6f8 100644 --- a/internal/sub/service.go +++ b/internal/sub/service.go @@ -3384,6 +3384,7 @@ type PageData struct { SubUrl string SubJsonUrl string SubClashUrl string + Format string SubTitle string SubSupportUrl string SubAnnounce string