diff --git a/README.md b/README.md index f5417bf..e9ca3da 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ go -C backend build -o ../.local/mirrorouc . ./mirrorouc -static ./dist -data ./data -manager http://127.0.0.1:12345 -worker YOUR_WORKER_ID ``` -默认监听 `127.0.0.1:8081`,可通过 `-listen` 修改。首页为 `/`,管理后台为 `/admin`,同步状态页为 `/status`。数据库与上传文件保存在 `data/`,更新时保留该目录。 +默认监听 `127.0.0.1:8081`,可通过 `-listen` 修改。首页为 `/`,公告页为 `/announcements`,管理后台为 `/admin`,同步状态页为 `/status`。数据库与上传文件保存在 `data/`,更新时保留该目录。 镜像目录与下载由已有的 Web 服务器提供,路径为 `/mirrors/<源名>/`。自定义目录页的 Fancyindex 模板随前端构建生成在 `dist/fancy-index/` 中。 diff --git a/backend/announcements_test.go b/backend/announcements_test.go new file mode 100644 index 0000000..61a089e --- /dev/null +++ b/backend/announcements_test.go @@ -0,0 +1,128 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" +) + +func publicArticles(t *testing.T, c *testClient, home bool) []Record { + t.Helper() + path := "/api/v1/announcements" + if home { + path = "/api/v1/public" + } + w := c.call("GET", path, nil, false) + status(t, w, 200) + var records []Record + if home { + var payload struct { + Announcements []Record `json:"announcements"` + } + if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + records = payload.Announcements + } else if err := json.Unmarshal(w.Body.Bytes(), &records); err != nil { + t.Fatal(err) + } + return records +} + +func TestAnnouncementsArchiveAndHome(t *testing.T) { + c := fixture(t) + // An archive must include older articles beyond the former 100-record cap. + for i := 0; i < 105; i++ { + _, err := c.app.saveRecord("announcements", fmt.Sprintf("history-%03d", i), Announcement{Title: "历史公告", Body: "## Markdown 正文\n\n保留全文。", Published: true, Date: "2020-01-01T00:00:00Z"}, 0) + if err != nil { + t.Fatal(err) + } + } + for id, article := range map[string]Announcement{ + "pinned": {Title: "置顶公告", Body: "置顶正文", Published: true, Pinned: true, Date: "2019-01-01T00:00:00Z"}, + "newer": {Title: "较晚公告", Body: "较晚正文", Published: true, Date: "2026-10-31T18:00:00Z"}, + "older": {Title: "较早公告", Body: "较早正文", Published: true, Date: "2026-11-01T01:00:00+08:00"}, + "draft": {Title: "未公开标题", Body: "未公开正文", Pinned: true, Date: "2027-01-01T00:00:00Z"}, + } { + if _, err := c.app.saveRecord("announcements", id, article, 0); err != nil { + t.Fatal(err) + } + } + archive := publicArticles(t, c, false) + if len(archive) != 108 { + t.Fatalf("archive omitted published articles: %d", len(archive)) + } + for i, id := range []string{"pinned", "newer", "older"} { + if archive[i].ID != id { + t.Fatalf("incorrect pinned / chronological order: %+v", archive[:3]) + } + } + for _, record := range archive { + if record.ID == "draft" { + t.Fatal("draft exposed in archive") + } + } + var last Announcement + if err := decodeData(archive[len(archive)-1].Data, &last); err != nil || last.Body != "## Markdown 正文\n\n保留全文。" { + t.Fatal("archive did not retain complete Markdown") + } + home := publicArticles(t, c, true) + if len(home) != 5 || home[0].ID != "pinned" || home[1].ID != "newer" { + t.Fatalf("home should show five recent, pinned-first links: %+v", home) + } +} + +func TestAnnouncementPublishingLifecycle(t *testing.T) { + c := fixture(t) + c.login("editor") + article := Announcement{Title: "维护通知", Date: "2026-11-01T00:00:00+08:00"} + save := func(revision, want int) { + t.Helper() + status(t, c.call("PUT", "/api/v1/admin/records/announcements/maintenance", map[string]any{"data": article, "revision": revision}, true), want) + } + assertVisible := func(want int) { + t.Helper() + for _, home := range []bool{false, true} { + if got := len(publicArticles(t, c, home)); got != want { + t.Fatalf("public visibility: want %d, got %d (home=%v)", want, got, home) + } + } + } + save(0, 200) // Empty bodies may be saved as drafts. + assertVisible(0) + article.Published = true + save(1, 400) // Publishing an empty body must not alter the draft. + assertVisible(0) + article.Body = "## 维护安排\n\n- 时间:今晚\n- 影响:短暂中断\n\n`apt update`" + save(1, 200) + assertVisible(1) + save(1, 409) // Another editor cannot overwrite a newer revision. + article.Published = false + save(2, 200) + assertVisible(0) + article.Published = true + save(3, 200) + assertVisible(1) + status(t, c.call("DELETE", "/api/v1/admin/records/announcements/maintenance", map[string]int{"revision": 4}, true), 200) + assertVisible(0) +} + +func TestAnnouncementsDirectNavigation(t *testing.T) { + c := fixture(t) + if err := os.WriteFile(filepath.Join(c.app.cfg.Static, "index.html"), []byte("MirrorOUC"), 0600); err != nil { + t.Fatal(err) + } + for _, path := range []string{"/announcements", "/announcements/"} { + for _, method := range []string{"GET", "HEAD"} { + w := c.call(method, path, nil, false) + status(t, w, 200) + if method == "HEAD" && w.Body.Len() != 0 { + t.Fatal("HEAD returned a response body") + } + } + } + status(t, c.call("POST", "/announcements", nil, false), 405) + status(t, c.call("GET", "/announcements/missing", nil, false), 404) +} diff --git a/backend/content.go b/backend/content.go index 2630918..d919eaf 100644 --- a/backend/content.go +++ b/backend/content.go @@ -291,11 +291,23 @@ func (a *App) public(w http.ResponseWriter, r *http.Request) { mirrors = append(mirrors, publicMirror(job, meta)) } sort.Slice(mirrors, func(i, j int) bool { return mirrors[i].Name < mirrors[j].Name }) - announcements, err := a.records("announcements") + published, err := a.publishedAnnouncements() if err != nil { a.internal(w, err) return } + // The home page only needs recent links. The archive endpoint returns all bodies. + if len(published) > 5 { + published = published[:5] + } + respond(w, 200, map[string]any{"site": site.Data, "mirrors": mirrors, "announcements": published, "source": map[string]any{"updatedAt": updated, "stale": upstreamError != "" || updated == 0 || time.Now().UnixMilli()-updated > 60000, "code": upstreamError}}) +} + +func (a *App) publishedAnnouncements() ([]Record, error) { + announcements, err := a.records("announcements") + if err != nil { + return nil, err + } published := []Record{} for _, record := range announcements { var d Announcement @@ -309,12 +321,23 @@ func (a *App) public(w http.ResponseWriter, r *http.Request) { if a.Pinned != b.Pinned { return a.Pinned } - return a.Date > b.Date + at, _ := time.Parse(time.RFC3339, a.Date) + bt, _ := time.Parse(time.RFC3339, b.Date) + if !at.Equal(bt) { + return at.After(bt) + } + return published[i].ID < published[j].ID }) - if len(published) > 100 { - published = published[:100] + return published, nil +} + +func (a *App) announcements(w http.ResponseWriter, r *http.Request) { + published, err := a.publishedAnnouncements() + if err != nil { + a.internal(w, err) + return } - respond(w, 200, map[string]any{"site": site.Data, "mirrors": mirrors, "announcements": published, "source": map[string]any{"updatedAt": updated, "stale": upstreamError != "" || updated == 0 || time.Now().UnixMilli()-updated > 60000, "code": upstreamError}}) + respond(w, 200, published) } func (a *App) overview(w http.ResponseWriter, r *http.Request) { if _, ok := a.require(w, r, false); !ok { diff --git a/backend/main.go b/backend/main.go index d419ac9..aad3e71 100644 --- a/backend/main.go +++ b/backend/main.go @@ -103,6 +103,7 @@ func (a *App) handler() http.Handler { respond(w, 200, map[string]string{"status": "ok"}) }) mux.HandleFunc("GET /api/v1/public", a.public) + mux.HandleFunc("GET /api/v1/announcements", a.announcements) mux.HandleFunc("GET /api/v1/monitoring", a.monitoring) mux.HandleFunc("GET /api/v1/job-speeds", a.jobSpeeds) mux.HandleFunc("POST /api/v1/auth/login", a.login) @@ -140,7 +141,7 @@ func (a *App) handler() http.Handler { return } path := r.URL.Path - if path == "/" || path == "/status" || path == "/status/" || path == "/admin" || strings.HasPrefix(path, "/admin/") { + if path == "/" || path == "/status" || path == "/status/" || path == "/announcements" || path == "/announcements/" || path == "/admin" || strings.HasPrefix(path, "/admin/") { http.ServeFile(w, r, filepath.Join(a.cfg.Static, "index.html")) return } diff --git a/scripts/build-directory.ts b/scripts/build-directory.ts index de2022e..d401e4c 100644 --- a/scripts/build-directory.ts +++ b/scripts/build-directory.ts @@ -7,7 +7,7 @@ const t = (key: string) => i18n.global.t(key) const escape = (value: string) => value.replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]!) const text = (key: string) => `${escape(t(key))}` const navigation = [ - ['mirrors', '/'], ['news', 'https://www.itouc.cn/announcements/'], ['status', '/status'], + ['mirrors', '/'], ['news', '/announcements'], ['status', '/status'], ['feedback', 'https://git.itouc.cn/ITStudio_OUC/OUCMirror-WebUI/issues'], ].map(([key, href]) => `${text(`common.nav.${key}`)}`).join('') const languages = Object.entries(directoryMessages).map(([locale, messages]) => ``).join('') diff --git a/src/App.vue b/src/App.vue index e7b8db8..ce5918e 100644 --- a/src/App.vue +++ b/src/App.vue @@ -10,14 +10,16 @@ import RollingText from './components/RollingText.vue' import LanguagePicker from './components/LanguagePicker.vue' import StatusPage from './components/StatusPage.vue' import AdminPage from './components/AdminPage.vue' +import AnnouncementsPage from './components/AnnouncementsPage.vue' import MarkdownContent from './components/MarkdownContent.vue' import { content } from './api' +import { announcementUrl } from './announcements' import { usePublicData } from './usePublicData' import { useMirrorFormats } from './useMirrorFormats' import { type Mirror } from './data' import { datetimeFormats, readPreference, savePreference, type Locale } from './locales' -const { t, d, locale } = useI18n() +const { t, locale } = useI18n() const isAdminPage = window.location.pathname.startsWith('/admin') const { site, mirrors, announcements: articleRecords, source, loading } = usePublicData() const announcements = computed(() => articleRecords.value.map(row => ({ id: row.id, ...row.data }))) @@ -38,9 +40,10 @@ const themeRoot = ref() const themes: Theme[] = ['light', 'dark', 'system'] const themeIcons = { light: Sun, dark: Moon, system: Monitor } const isStatusPage = window.location.pathname.replace(/\/$/, '') === '/status' +const isAnnouncementsPage = window.location.pathname.replace(/\/$/, '') === '/announcements' const navigation = [ - { key: 'mirrors', href: '/', active: !isStatusPage && !isAdminPage }, - { key: 'news', href: 'https://www.itouc.cn/announcements/', active: false }, + { key: 'mirrors', href: '/', active: !isStatusPage && !isAdminPage && !isAnnouncementsPage }, + { key: 'news', href: '/announcements', active: isAnnouncementsPage }, { key: 'status', href: '/status', active: isStatusPage }, { key: 'feedback', href: 'https://git.itouc.cn/ITStudio_OUC/OUCMirror-WebUI/issues', active: false }, ] @@ -55,7 +58,10 @@ watch(locale, (value) => { document.title = t('common.pageTitle') savePreference('mirrorouc.locale', value) }, { immediate: true }) -watch([locale, site], () => { document.title = site.value ? `MirrorOUC · ${content(site.value.name, locale.value)}` : t('common.pageTitle') }) +watch([locale, site], () => { + const siteTitle = site.value ? `MirrorOUC · ${content(site.value.name, locale.value)}` : t('common.pageTitle') + document.title = isAnnouncementsPage ? `${t('announcements.title')} · ${siteTitle}` : siteTitle +}, { immediate: true }) function selectTheme(value: Theme) { theme.value = value; themeOpen.value = false } const search = ref('') @@ -86,22 +92,18 @@ function nextLabel(mirror: Mirror) { } function resetSearch() { search.value = ''; searchInput.value?.focus() } -type Modal = 'help' | 'news' | 'about' | 'downloads' | 'mirror' +type Modal = 'help' | 'about' | 'downloads' | 'mirror' const dialog = ref() const modal = ref(null) const selectedMirror = ref(null) -const selectedNews = ref(null) -const activeNews = computed(() => announcements.value.find(item => item.id === selectedNews.value)) const modalTitle = computed(() => { if (modal.value === 'mirror') return selectedMirror.value?.name || '' - if (modal.value === 'news' && activeNews.value) return activeNews.value.title - const keys = { help: 'mirrors.helpTitle', news: 'announcements.title', about: 'common.aboutTitle', downloads: 'announcements.downloadsTitle' } + const keys = { help: 'mirrors.helpTitle', about: 'common.aboutTitle', downloads: 'announcements.downloadsTitle' } return modal.value && modal.value in keys ? t(keys[modal.value as keyof typeof keys]) : '' }) -async function openModal(value: Modal, mirror?: Mirror, news?: string) { +async function openModal(value: Modal, mirror?: Mirror) { modal.value = value selectedMirror.value = mirror || null - selectedNews.value = news || null mobileOpen.value = false themeOpen.value = false await nextTick() @@ -114,7 +116,7 @@ watch(modal, value => { document.body.classList.toggle('dialog-open', value !== function onKeydown(event: KeyboardEvent) { if (event.key === 'Escape') { themeOpen.value = false; mobileOpen.value = false } const target = event.target as HTMLElement - if (!dialog.value?.open && ((event.key === 'k' && (event.ctrlKey || event.metaKey)) + if (!isAdminPage && !isAnnouncementsPage && !dialog.value?.open && ((event.key === 'k' && (event.ctrlKey || event.metaKey)) || (event.key === '/' && !['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) && !target.isContentEditable))) { event.preventDefault() if (isStatusPage) statusPage.value?.focusSearch() @@ -152,7 +154,7 @@ onBeforeUnmount(() => {