feat(feeds): cache FreshRSS subscriptions and category navigation
Build and publish container images / images (push) Failing after 6m7s

This commit is contained in:
Anya Tokugawa committed 2026-11-08 04:48:55 +09:00
1 parent 7fe64113c7
commit bfed3d20f5
12 files changed
+503 -34

No files matched your search

+51 -2
View File
@@ -1,7 +1,7 @@
# 15. RSSビューア・FreshRSS・newsboat
状態:内蔵簡易reader、FreshRSS読取connector、共通viewer、Wiki保存・タスク化、ダッシュボードを実装。
OPMLの確認付き追加取り込み・書出しも実装済み。FreshRSSへの書戻しは残件。本番反映と実FreshRSSへの接続は未実施。
OPMLの確認付き追加取り込み・書出し、FreshRSS購読・カテゴリのnavigationも実装済み。FreshRSSへの書戻しは残件。本番反映と実FreshRSSへの接続は未実施。
既存のブログRSS「配信」と、本章の外部RSS「購読」は別機能。
2026-11-08:利用者指定のサブプロジェクト順で最初に実施する。内蔵readerは簡易利用の
@@ -72,6 +72,7 @@ API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用
| `POST sources/{uuid}/refresh` | 次回背景取得を予約。画面から外部通信しない |
| `POST sources/{uuid}/delete` | versionを照合してsource・cache・内蔵read/starを削除 |
| `GET items` | source/unread/starred/件名・配信元で絞り込み、100件単位のkeysetページング |
| `GET catalog?source=…` | 本人のFreshRSS購読・カテゴリの取得済み一覧。外部通信なし |
| `GET item?source=…&id=…` | 本人の記事本文 |
| `POST state` | 内蔵read/starの条件付き変更。FreshRSSは拒否 |
| `POST note` | 公開範囲確認付きのWiki単独保存。request_idと入力hashで再送を識別 |
@@ -83,6 +84,8 @@ managed schema `feeds` v1に `feed_sources`、`feed_items`、`feed_states`、`fe
v2で`feed_items.body_html`を追加します。既存のテキスト本文・既読・starは保持し、条件付きGETのvalidatorを
一度クリアして次回背景取得でHTMLを取り直します。migration前のworkerは設定versionで無効化します。
v3で`feed_import_receipts`を追加し、購読の一括追加と再送記録を同時保存します。
v4でsourceに購読一覧、記事にremote feed ID・カテゴリIDを追加します。FreshRSSの旧workerを
versionで無効化し、次の背景取得を予約します。内蔵sourceのversion・取得予約は変更しません。
既存テーブルを破壊・再構成しません。SQLiteのforeign_keys設定に依存せず削除を完遂するtriggerを
持ちます。内蔵read/starを本文cacheから分離し、記事を保持窓から落としても状態は黙って消しません。
DBは内蔵購読・状態・保存receiptの正本であり、全体を捨てられるcacheとは扱いません。
@@ -103,6 +106,7 @@ sourceのprovider・URL・資格情報の変更は別sourceを作る契約です
| 内蔵記事cache | 1 source最大500件、text本文32 KiB・HTML本文128 KiB。HTML上限超過はtextへフォールバックし、text切詰めを明示 |
| 内蔵read/star | 1 source最大10,000件。上限では新規状態保存を拒否し、既存状態を捨てない |
| FreshRSS | reading-list最新200件の窓を取得。更新成功時はその窓で置換し、全履歴同期とはしない |
| FreshRSS購読一覧 | 最大1,000購読、1購読64カテゴリ、保存JSON 1 MiB。記事と同じ取得予算で収集 |
| 再試行 | 次の設定間隔まで待機。手動予約にも最終成功から60秒の制限、取得中の重複claim拒否 |
内蔵は条件付きGET、304ではcacheを保持します。どちらのproviderも通信・認証・構文失敗で
@@ -110,12 +114,57 @@ sourceのprovider・URL・資格情報の変更は別sourceを作る契約です
成功/失敗件数だけを記録します。資格情報・生本文・秘密を含み得るURLをログへ出しません。
extension無効化は画面・API・取得・完了保存に適用します。購読を登録するまで外部通信は発生しません。
### FreshRSSの購読とカテゴリ
背景取得ではlogin後にreading-listと`subscription/list`を読み、両方に成功した場合だけ
記事・購読一覧を同じtransactionで置換します。一方の取得失敗、上限超過、不正なsnapshotでは
前回の両cacheを保持します。記事が取得窓内にない購読も一覧には残します。
左ペインでFreshRSS sourceを選ぶとカテゴリ選択・購読名の検索・購読一覧を表示します。
カテゴリは表示名でなくremote category ID、購読は`origin.streamId`とsubscription IDを対応させます。
同名でも混同せず、複数カテゴリに属する購読も扱います。`GET items`の`feed`/`category`は
source指定と組み合わせ、既存の未読・star・検索・keysetページングと併用できます。
絞り込み対象は最新200記事のcache内に限られ、購読を選んでも履歴全件を外部取得しません。
購読の追加・削除やカテゴリの編集はFreshRSS側で行います。
## 既読・star同期を追加する条件
server-authoritative stateと未送信の操作を分けます。操作ごとのrequest_idで重複を防ぎ、成功応答前に確定済みと表示しません。newsboat等で同時変更された場合、古いローカルcacheをまとめて送り返しません。接続解除・認可失効時は未送信変更を勝手に再送しません。
FreshRSS APIに条件付き更新がない操作もあり得るため、対応版の実機fixtureで競合動作を確認するまで完全な双方向同期を約束しません。
### 書戻しの次段階設計
以下は未実装のRSS-3です。購読navigationの追加だけでは書戻しを有効にしません。
sourceごとに既定OFFの書戻し設定を設け、操作は`read`または`starred`の一項目と希望値に限定します。
cache内の他項目を同時に送らず、全件既読・購読編集も初期対象に含めません。
操作記録は記事cacheから分離し、Domain・本人・request_id、source・記事ID、対象項目、希望値、
source version、状態、claim期限を保持します。同一request_idの同じ入力は同じ記録を返し、
違う入力は拒否します。同じ記事に未解決の操作がある間は次の操作を受け付けません。
受付APIは外部通信せず、低優先度workerが送信します。記録数とworkerの時間予算は必ず有限にします。
| 状態 | 次の処理 |
| --- | --- |
| queued | sourceの有効状態・書戻し設定・version・本人の権限を再検査してclaim。古すぎる未送信操作は中止 |
| preparing | FreshRSSの現在値を取得。すでに希望値なら書き込まず確認済み。異なる場合だけ変更tokenを取得 |
| sending | この状態をDBに確定してから変更を送る。再起動やtimeoutでも自動再送しない |
| confirmed | 送信後の読取で希望値を確認。確認できた値だけcacheへ反映 |
| unknown | 送信済みか適用済みか判断できない。成功扱いにせず、利用者の再確認操作を待つ |
| checking | unknownの再確認。読取のみで、希望値ならconfirmed、異なれば競合として提示 |
| failed / cancelled / conflict | 原因を示して終了。新たに送る場合は利用者の明示操作を必要とする |
通常取得と書戻しはsourceのleaseを共有し、古い取得結果が書戻し後の値を上書きしないようにします。
設定変更・無効化・削除は未送信操作を止めますが、すでに外へ送った要求は取り消せません。
その場合はunknownを保持し、設定変更後のcacheへ旧workerが反映することを拒否します。
外部clientとの同時変更を原子的に防げないAPIでは、確認直後に状態が再変更される可能性もあります。
readbackは観測結果であり、exactly-onceやリモートCASの保証とは区別します。
受入テストは、opt-inなしの拒否、同じ操作の再送、別項目の保持、送信前の権限失効、
送信直後の応答喪失、worker停止・再起動、unknownの読取専用再確認、source削除・設定変更、
通常取得との排他、他clientによる同時変更を含めます。実サービスを使わない合成fixtureで
これらを通した後、指定版FreshRSSでの受入を別途行います。
## 内蔵簡易reader
購読追加/削除、フォルダ、記事一覧、既読/未読、star、更新間隔と保持上限を初期範囲に
@@ -178,7 +227,7 @@ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。
- [x] RSS-4b:OPML export/importのpreview、選択追加、重複確認、原子的な保存と再送防止。置換・状態移行は範囲外。
- [ ] RSS-5:FreshRSS実環境の接続先・版・API資格情報を指定してread-only受入。
- [ ] RSS-6:大規模利用時の公平性、host別並列上限、Retry-After/backoff、資格情報rotation UI。
- [ ] RSS-7:FreshRSSの購読一覧・カテゴリを使うnavigation。現在の左ペインはPagesWikiに登録したsourceとそのフォルダで、FreshRSSの全購読一覧ではない。
- [x] RSS-7:FreshRSSの購読一覧・カテゴリを使うnavigation。同名ID分離、複数カテゴリ、cache内絞り込み、背景での原子的更新、失敗時保持。
隔離試験はRSS/Atom・FreshRSS login/read、欠落ID・巨大/不正feed、条件付きGET、失敗時cache保持、
本人分離・失効・readonly、二重送信・版競合・旧worker拒否、migration再実行/失敗rollback、
+9 -1
View File
@@ -47,6 +47,14 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
return
}
switch {
case key == "catalog" && r.Method == "GET":
catalog, e := s.store.FeedCatalog(r.Context(), domain, actor, r.URL.Query().Get("source"))
if e != nil {
taskError(w, e)
return
}
writeEventJSON(w, 200, map[string]any{"subscriptions": catalog})
return
case key == "note" && r.Method == "POST":
var input struct {
RequestID string `json:"request_id"`
@@ -159,7 +167,7 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
return
}
}
items, e := s.store.FeedItems(r.Context(), domain, actor, q.Get("source"), q.Get("filter"), q.Get("q"), before, q.Get("key"))
items, e := s.store.FeedItems(r.Context(), domain, actor, q.Get("source"), q.Get("filter"), q.Get("q"), before, q.Get("key"), q.Get("feed"), q.Get("category"))
if e != nil {
taskError(w, e)
return
+149
View File
@@ -0,0 +1,149 @@
package server
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strings"
"testing"
"github.com/google/uuid"
"pageswiki/internal/store"
)
const testFeedCatalog = `{"subscriptions":[{"id":"feed/1","title":"Same title","categories":[{"id":"user/alice/label/Tech","label":"技術"}]},{"id":"feed/2","title":"Same title","categories":[{"id":"user/alice/label/Other","label":"技術"}]},{"id":"feed/3","title":"Empty feed","categories":[]}]}`
func TestFreshRSSCatalogValidation(t *testing.T) {
catalog, e := parseFreshRSSCatalog([]byte(testFeedCatalog))
if e != nil || len(catalog) != 3 || catalog[0].Categories[0].ID == catalog[1].Categories[0].ID {
t.Fatal(catalog, e)
}
for _, raw := range []string{`{}`, `{"subscriptions":null}`, `{"subscriptions":[{"id":""}]}`, `{"subscriptions":[{"id":"feed/1"},{"id":"feed/1"}]}`, `{"subscriptions":[{"id":"feed/1","categories":[{"id":"cat","label":"A"},{"id":"cat","label":"A"}]}]}`, `{"subscriptions":[{"id":"feed/1","categories":[{"id":"cat","label":"A"}]},{"id":"feed/2","categories":[{"id":"cat","label":"B"}]}]}`} {
if _, e := parseFreshRSSCatalog([]byte(raw)); e == nil {
t.Fatal("accepted", raw)
}
}
if c, e := parseFreshRSSCatalog([]byte(`{"subscriptions":[]}`)); e != nil || len(c) != 0 {
t.Fatal(c, e)
}
big := make([]store.FeedRemoteSubscription, 1001)
raw, _ := json.Marshal(map[string]any{"subscriptions": big})
if _, e := parseFreshRSSCatalog(raw); e == nil {
t.Fatal("unbounded catalog")
}
}
func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
s, token, domain, actor, local := feedFixture(t)
ctx := context.Background()
if e := s.store.FeedSourceAction(ctx, domain, actor, local.UUID, "delete", local.Version); e != nil {
t.Fatal(e)
}
v := store.FeedSource{UUID: uuid.NewString(), Provider: "freshrss", Title: "FreshRSS", URL: "https://example.org/api/greader.php", Enabled: true, Interval: 300}
v.Credential, _ = s.store.SealFeedCredential(domain, actor, v.UUID, "reader", "secret")
if _, e := s.store.SaveFeedSource(ctx, domain, actor, v); e != nil {
t.Fatal(e)
}
calls := 0
failCatalog := false
client := &http.Client{Transport: feedTransportFunc(func(r *http.Request) (*http.Response, error) {
calls++
body := ""
switch {
case strings.HasSuffix(r.URL.Path, "/accounts/ClientLogin"):
if r.Method != "POST" {
t.Error("login method")
}
body = "Auth=synthetic"
case strings.HasSuffix(r.URL.Path, "/stream/contents/reading-list"):
if r.Method != "GET" || r.URL.Query().Get("n") != "200" {
t.Error("article request")
}
body = `{"items":[{"id":"a","title":"First","origin":{"title":"Same title","streamId":"feed/1"},"categories":["user/alice/label/Tech"]},{"id":"b","title":"Second","origin":{"title":"Same title","streamId":"feed/2"},"categories":["user/alice/label/Other"]}]}`
if failCatalog {
body = `{"items":[]}`
}
case strings.HasSuffix(r.URL.Path, "/subscription/list"):
if r.Method != "GET" || r.Header.Get("Authorization") != "GoogleLogin auth=synthetic" {
t.Error("catalog request")
}
if failCatalog {
return nil, errors.New("synthetic timeout")
}
body = testFeedCatalog
default:
t.Fatalf("unexpected external request %s %s", r.Method, r.URL.Path)
}
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))}, nil
})}
run := func() {
t.Helper()
if _, e := s.store.DB.Exec(`UPDATE feed_sources SET next_ms=0 WHERE uuid=?`, v.UUID); e != nil {
t.Fatal(e)
}
if e := s.syncFeedSourcesWithClient(ctx, &store.EventJob{}, client); e != nil {
t.Fatal(e)
}
}
run()
if calls != 3 {
t.Fatal("fetch count", calls)
}
w := feedRequestTest(s, token, "GET", "catalog?source="+v.UUID, nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Empty feed") || strings.Contains(w.Body.String(), "secret") {
t.Fatal(w.Code, w.Body)
}
for _, scope := range []string{"feed=feed%2F1", "category=" + url.QueryEscape("user/alice/label/Tech")} {
w = feedRequestTest(s, token, "GET", "items?source="+v.UUID+"&"+scope, nil)
var data struct {
Items []store.FeedItem `json:"items"`
}
json.Unmarshal(w.Body.Bytes(), &data)
if w.Code != 200 || len(data.Items) != 1 || data.Items[0].ID != "a" {
t.Fatal(scope, w.Code, w.Body)
}
}
w = feedRequestTest(s, token, "GET", "items?feed=feed%2F1", nil)
if w.Code != 422 {
t.Fatal("unscoped remote ID", w.Code, w.Body)
}
other, e := s.store.CreatePasswordAccount(domain, "catalogother", "long test password", "Other", "")
if e != nil {
t.Fatal(e)
}
otherToken, e := s.store.CreateAuthSession(domain, other.UUID)
if e != nil {
t.Fatal(e)
}
if w = feedRequestTest(s, otherToken, "GET", "catalog?source="+v.UUID, nil); w.Code == 200 {
t.Fatal("cross-owner catalog leak")
}
if w = feedRequestTest(s, "", "GET", "catalog?source="+v.UUID, nil); w.Code == 200 {
t.Fatal("anonymous catalog leak")
}
if _, e := s.store.FeedCatalog(ctx, uuid.NewString(), actor, v.UUID); e == nil {
t.Fatal("cross-domain catalog leak")
}
if calls != 3 {
t.Fatal("foreground external request")
}
failCatalog = true
run()
catalog, e := s.store.FeedCatalog(ctx, domain, actor, v.UUID)
if e != nil || len(catalog) != 3 {
t.Fatal("lost catalog", catalog, e)
}
items, e := s.store.FeedItems(ctx, domain, actor, v.UUID, "", "", -1, "")
if e != nil || len(items) != 2 {
t.Fatal("lost articles", items, e)
}
if e := s.setSystemExtensionEnabled(domain, "organizer.feeds", false); e != nil {
t.Fatal(e)
}
if _, e := s.store.FeedCatalog(ctx, domain, actor, v.UUID); !errors.Is(e, store.ErrAccessDenied) {
t.Fatal("disabled read", e)
}
}
+54 -5
View File
@@ -328,7 +328,7 @@ func feedRequest(ctx context.Context, client *http.Client, method, target, auth
}
return raw, res.Header, res.StatusCode, nil
}
func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, user, password string) ([]store.FeedItem, error) {
func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, user, password string, catalogs ...*[]store.FeedRemoteSubscription) ([]store.FeedItem, error) {
base := strings.TrimRight(v.URL, "/")
raw, _, _, e := feedRequest(ctx, client, "POST", base+"/accounts/ClientLogin", "", url.Values{"Email": {user}, "Passwd": {password}}, nil)
if e != nil {
@@ -354,7 +354,8 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
Published int64 `json:"published"`
Categories []string `json:"categories"`
Origin struct {
Title string `json:"title"`
Title string `json:"title"`
StreamID string `json:"streamId"`
} `json:"origin"`
Alternate []struct {
Href string `json:"href"`
@@ -377,7 +378,10 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
return nil, errFeedInvalid
}
seen[i.ID] = true
item := store.FeedItem{ID: i.ID, Title: feedText(i.Title, 2048), Feed: feedText(i.Origin.Title, 512)}
if (i.Origin.StreamID != "" && !store.ValidFeedRemoteID(i.Origin.StreamID)) || len(i.Categories) > 64 {
return nil, errFeedInvalid
}
item := store.FeedItem{ID: i.ID, Title: feedText(i.Title, 2048), Feed: feedText(i.Origin.Title, 512), RemoteFeed: i.Origin.StreamID, RemoteCategories: []string{}}
if i.Published > 0 && i.Published < time.Now().AddDate(1, 0, 0).Unix() {
item.PublishedMS = i.Published * 1000
}
@@ -391,6 +395,9 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
item.URL = feedLink(base, i.Alternate[0].Href)
}
for _, c := range i.Categories {
if !store.ValidFeedRemoteID(c) {
return nil, errFeedInvalid
}
if strings.HasSuffix(c, "/state/com.google/read") {
item.Read = true
}
@@ -399,12 +406,53 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
}
if pos := strings.Index(c, "/label/"); pos >= 0 {
item.Folder = feedText(c[pos+7:], 512)
item.RemoteCategories = append(item.RemoteCategories, c)
}
}
out = append(out, item)
}
if len(catalogs) > 0 {
raw, _, _, e = feedRequest(ctx, client, "GET", base+"/reader/api/0/subscription/list?output=json", auth, nil, nil)
if e != nil {
return nil, e
}
catalog, e := parseFreshRSSCatalog(raw)
if e != nil {
return nil, e
}
*catalogs[0] = catalog
}
return out, nil
}
func parseFreshRSSCatalog(raw []byte) ([]store.FeedRemoteSubscription, error) {
if len(raw) > 4<<20 || !utf8.Valid(raw) {
return nil, errFeedInvalid
}
var response struct {
Subscriptions []store.FeedRemoteSubscription `json:"subscriptions"`
}
if json.Unmarshal(raw, &response) != nil || response.Subscriptions == nil {
return nil, errFeedInvalid
}
if len(response.Subscriptions) > 1000 {
return nil, errors.New("limit")
}
for i := range response.Subscriptions {
sub := &response.Subscriptions[i]
sub.Title = feedText(sub.Title, 512)
if sub.Categories == nil {
sub.Categories = []store.FeedCategory{}
}
for j := range sub.Categories {
sub.Categories[j].Label = feedText(sub.Categories[j].Label, 512)
}
}
if _, e := store.FeedCatalogJSON(response.Subscriptions); e != nil {
return nil, errFeedInvalid
}
return response.Subscriptions, nil
}
func (s *Server) syncFeedSources(ctx context.Context, job *store.EventJob) error {
client := calendarSourceClient()
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
@@ -435,6 +483,7 @@ func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.Event
}
child, stop := context.WithTimeout(ctx, 8*time.Second)
var items []store.FeedItem
var catalog []store.FeedRemoteSubscription
etag, modified := v.ETag, v.Modified
unchanged := false
if !validCalendarSourceURL(v.URL) {
@@ -443,7 +492,7 @@ func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.Event
var user, password string
user, password, e = s.store.OpenFeedCredential(v)
if e == nil {
items, e = fetchFreshRSS(child, client, v, user, password)
items, e = fetchFreshRSS(child, client, v, user, password, &catalog)
} else {
e = errors.New("credentials")
}
@@ -478,7 +527,7 @@ func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.Event
} else {
done++
}
if e = s.store.CompleteFeed(ctx, v, items, etag, modified, code, unchanged); e != nil && !errors.Is(e, store.ErrAccessDenied) && !errors.Is(e, store.ErrTaskConflict) {
if e = s.store.CompleteFeed(ctx, v, items, etag, modified, code, unchanged, catalog); e != nil && !errors.Is(e, store.ErrAccessDenied) && !errors.Is(e, store.ErrTaskConflict) {
return e
}
}
+24 -2
View File
@@ -543,8 +543,30 @@ func TestFeedsChromium(t *testing.T) {
if e = s.store.CompleteFeed(context.Background(), claim, items, "", "", "", false); e != nil {
t.Fatal(e)
}
_ = domain
_ = actor
fresh, e := s.store.SaveFeedSource(context.Background(), domain, actor, store.FeedSource{UUID: uuid.NewString(), Provider: "freshrss", Title: "FreshRSS fixture", URL: "https://example.org/api/greader.php", Enabled: true, Interval: 300})
if e != nil {
t.Fatal(e)
}
all, e := s.store.FeedSources(context.Background(), domain, actor)
if e != nil {
t.Fatal(e)
}
for _, v := range all {
if v.UUID == fresh.UUID {
fresh = v
}
}
claim, e = s.store.ClaimFeed(context.Background(), fresh)
if e != nil {
t.Fatal(e)
}
catalog, e := parseFreshRSSCatalog([]byte(testFeedCatalog))
if e != nil {
t.Fatal(e)
}
if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "catalog-a", Title: "Catalog first", RemoteFeed: "feed/1", RemoteCategories: []string{"user/alice/label/Tech"}}, {ID: "catalog-b", Title: "Catalog second", RemoteFeed: "feed/2", RemoteCategories: []string{"user/alice/label/Other"}}}, "", "", "", false, catalog); e != nil {
t.Fatal(e)
}
s.store.BackgroundJobsDisabled = true
s = New(s.store)
script, e := os.ReadFile("internal/server/testdata/feeds.js")
+10 -2
View File
@@ -13,7 +13,7 @@
d.querySelectorAll('.feed-row')[1].click();await wait(()=>d.querySelector('#feed-reader .feed-body')&&!d.querySelector('#feed-reader .feed-body').shadowRoot);assert(d.querySelector('#feed-reader .feed-body').textContent.includes('<script>'),'Literal text not preserved');d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')?.shadowRoot);
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'*',bubbles:true}));await wait(()=>d.querySelector('.feed-row[aria-selected=true]').textContent.includes('★'));
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));await wait(()=>!d.querySelector('.feed-layout').classList.contains('reading'));
d.getElementById('feed-more').click();await wait(()=>d.querySelectorAll('.feed-row').length===120);
d.getElementById('feed-more').click();await wait(()=>d.querySelectorAll('.feed-row').length===122);
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'/',bubbles:true}));await wait(()=>d.activeElement.type==='search');d.activeElement.value='119';d.activeElement.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===1);
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));
d.querySelector('#feed-reader .feed-actions button:last-child').click();await wait(()=>d.querySelector('#feed-reader form'));
@@ -26,6 +26,14 @@
await wait(()=>d.querySelectorAll('#feed-opml-preview tbody tr').length===3);const checks=d.querySelectorAll('#feed-opml-preview tbody input');assert(checks[0].checked&&!checks[0].disabled&&checks[1].disabled&&checks[2].disabled,'Import eligibility');
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML overflow');d.querySelector('.feed-import-options input[type=checkbox]').checked=false;d.getElementById('feed-opml-preview').requestSubmit();await wait(()=>!d.getElementById('feed-opml-preview'));
assert(d.getElementById('feed-sources').textContent.includes('Import '+w.innerWidth),'Imported source missing');d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));choose();await wait(()=>d.querySelectorAll('#feed-opml-preview tbody tr').length===3);assert(d.querySelector('#feed-opml-preview tbody input').disabled,'Duplicate after import');
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML preview overflow');document.body.dataset.vimReady='1';
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML preview overflow');
[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='FreshRSS fixture').click();await wait(()=>d.querySelectorAll('.feed-subscriptions button').length===4&&d.querySelectorAll('.feed-row').length===2);
const category=d.getElementById('feed-category');category.value='user/alice/label/Tech';category.dispatchEvent(new w.Event('change'));await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog first'));
assert(d.querySelectorAll('.feed-subscriptions button').length===2,'Category navigation');
d.getElementById('feed-category').value='';d.getElementById('feed-category').dispatchEvent(new w.Event('change'));await wait(()=>d.querySelectorAll('.feed-row').length===2);
d.querySelector('.feed-subscriptions button[data-feed="feed/2"]').click();await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog second'));
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));assert(d.querySelectorAll('#feed-reader .feed-actions button:disabled').length===2,'FreshRSS not read-only');
if(w.innerWidth<=600)d.querySelector('#feed-toolbar button').click();
assert(d.documentElement.scrollWidth<=w.innerWidth,'Catalog overflow');document.body.dataset.vimReady='1';
}catch(e){const out=document.createElement('pre');out.id='error';out.textContent=e.stack;document.body.append(out);}
})();
+68 -17
View File
@@ -37,6 +37,13 @@ var feedMigrations = []db.SQLMigration{{Version: 1, Name: "private_feed_reader",
Version: 3, Name: "feed_import_receipts", Statements: []string{
`CREATE TABLE feed_import_receipts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,request_id TEXT NOT NULL,input_hash TEXT NOT NULL,result TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,request_id))`,
}, Assertions: []string{schemaUnique("feed_import_receipts", "domain_uuid,owner_uuid,request_id")},
}, {
Version: 4, Name: "freshrss_catalog", Statements: []string{
`ALTER TABLE feed_sources ADD COLUMN remote_catalog TEXT NOT NULL DEFAULT '[]'`,
`ALTER TABLE feed_items ADD COLUMN remote_feed TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE feed_items ADD COLUMN remote_categories TEXT NOT NULL DEFAULT '[]'`,
`UPDATE feed_sources SET next_ms=0,lease='',lease_until=0,version=version+1 WHERE provider='freshrss'`,
}, Assertions: []string{schemaColumns("feed_sources", "remote_catalog"), schemaColumns("feed_items", "remote_feed,remote_categories")},
}}
// CaptureFeedNote creates an inert Wiki note and receipt atomically. It does not
@@ -124,19 +131,21 @@ type FeedSource struct {
Modified string `json:"-"`
}
type FeedItem struct {
Source string `json:"source"`
ID string `json:"id"`
Title string `json:"title"`
URL string `json:"url"`
Body string `json:"body,omitempty"`
BodyHTML string `json:"body_html,omitempty"`
PublishedMS int64 `json:"published_ms"`
Feed string `json:"feed"`
Folder string `json:"folder"`
Read bool `json:"read"`
Starred bool `json:"starred"`
Version int64 `json:"version"`
Provider string `json:"provider"`
Source string `json:"source"`
ID string `json:"id"`
Title string `json:"title"`
URL string `json:"url"`
Body string `json:"body,omitempty"`
BodyHTML string `json:"body_html,omitempty"`
PublishedMS int64 `json:"published_ms"`
Feed string `json:"feed"`
Folder string `json:"folder"`
Read bool `json:"read"`
Starred bool `json:"starred"`
Version int64 `json:"version"`
Provider string `json:"provider"`
RemoteFeed string `json:"remote_feed,omitempty"`
RemoteCategories []string `json:"remote_categories,omitempty"`
}
const feedSourceColumns = `uuid,domain_uuid,owner_uuid,provider,title,folder,url,credential,version,enabled,interval_seconds,next_ms,lease,lease_until,last_ms,error,etag,modified`
@@ -294,14 +303,27 @@ func (s *Store) FeedSourceAction(ctx context.Context, domain, owner, id, action
return nil
})
}
func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, query string, before int64, beforeID string) ([]FeedItem, error) {
func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, query string, before int64, beforeID string, scope ...string) ([]FeedItem, error) {
remoteFeed, category := "", ""
if len(scope) > 2 {
return nil, ErrTaskInvalid
}
if len(scope) > 0 {
remoteFeed = scope[0]
}
if len(scope) > 1 {
category = scope[1]
}
if (remoteFeed != "" && !ValidFeedRemoteID(remoteFeed)) || (category != "" && !ValidFeedRemoteID(category)) || ((remoteFeed != "" || category != "") && source == "") {
return nil, ErrTaskInvalid
}
if len(query) > 200 || len(beforeID) > 1200 {
return nil, ErrTaskInvalid
}
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
return nil, e
}
rows, e := s.DB.QueryContext(ctx, `SELECT i.source_uuid,i.id,i.title,i.url,i.published_ms,i.feed,CASE WHEN s.folder<>'' THEN s.folder ELSE i.folder END,CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END,CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END,COALESCE(t.version,0),s.provider FROM feed_items i JOIN feed_sources s ON s.uuid=i.source_uuid LEFT JOIN feed_states t ON t.source_uuid=i.source_uuid AND t.id=i.id WHERE s.domain_uuid=? AND s.owner_uuid=? AND (?='' OR s.uuid=?) AND (?='' OR instr(lower(i.title),lower(?))>0 OR instr(lower(i.feed),lower(?))>0) AND (?<0 OR i.published_ms<? OR (i.published_ms=? AND (i.source_uuid||':'||i.id)<?)) AND (?<>'unread' OR (CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END)=0) AND (?<>'starred' OR (CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END)=1) ORDER BY i.published_ms DESC,i.source_uuid||':'||i.id DESC LIMIT 101`, domain, owner, source, source, query, query, query, before, before, before, beforeID, filter, filter)
rows, e := s.DB.QueryContext(ctx, `SELECT i.source_uuid,i.id,i.title,i.url,i.published_ms,i.feed,CASE WHEN s.folder<>'' THEN s.folder ELSE i.folder END,CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END,CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END,COALESCE(t.version,0),s.provider FROM feed_items i JOIN feed_sources s ON s.uuid=i.source_uuid LEFT JOIN feed_states t ON t.source_uuid=i.source_uuid AND t.id=i.id WHERE s.domain_uuid=? AND s.owner_uuid=? AND (?='' OR s.uuid=?) AND (?='' OR instr(lower(i.title),lower(?))>0 OR instr(lower(i.feed),lower(?))>0) AND (?<0 OR i.published_ms<? OR (i.published_ms=? AND (i.source_uuid||':'||i.id)<?)) AND (?<>'unread' OR (CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END)=0) AND (?<>'starred' OR (CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END)=1) AND (?='' OR i.remote_feed=?) AND (?='' OR EXISTS(SELECT 1 FROM json_each(i.remote_categories) WHERE value=?)) ORDER BY i.published_ms DESC,i.source_uuid||':'||i.id DESC LIMIT 101`, domain, owner, source, source, query, query, query, before, before, before, beforeID, filter, filter, remoteFeed, remoteFeed, category, category)
if e != nil {
return nil, e
}
@@ -418,7 +440,18 @@ func (s *Store) ClaimFeed(ctx context.Context, v FeedSource) (FeedSource, error)
}
// Failed fetches preserve the previous cache. Version and claim token fence stale workers.
func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem, etag, modified, code string, unchanged bool) error {
func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem, etag, modified, code string, unchanged bool, catalogs ...[]FeedRemoteSubscription) error {
if len(catalogs) > 1 {
return ErrTaskInvalid
}
var catalog string
if len(catalogs) == 1 {
var e error
catalog, e = FeedCatalogJSON(catalogs[0])
if e != nil {
return e
}
}
if len(items) > 500 || len(etag) > 1024 || len(modified) > 1024 {
return ErrTaskInvalid
}
@@ -428,6 +461,14 @@ func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem
return ErrTaskInvalid
}
for _, i := range items {
if (i.RemoteFeed != "" && !ValidFeedRemoteID(i.RemoteFeed)) || len(i.RemoteCategories) > 64 {
return ErrTaskInvalid
}
for _, c := range i.RemoteCategories {
if !ValidFeedRemoteID(c) {
return ErrTaskInvalid
}
}
if i.ID == "" || len(i.ID) > 1024 || len(i.Title) > 2048 || len(i.URL) > 4096 || len(i.Body) > 32768 || len(i.BodyHTML) > 128<<10 || len(i.Feed) > 512 || len(i.Folder) > 512 || i.PublishedMS < 0 {
return ErrTaskInvalid
}
@@ -444,6 +485,11 @@ func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem
if code != "" || unchanged {
return nil
}
if catalog != "" {
if _, e = tx.ExecContext(ctx, `UPDATE feed_sources SET remote_catalog=? WHERE uuid=?`, catalog, v.UUID); e != nil {
return e
}
}
// FreshRSS is authoritative: retain exactly this bounded recent window,
// not stale rows from unsubscribed feeds or old external read/star state.
if v.Provider == "freshrss" {
@@ -452,7 +498,12 @@ func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem
}
}
for _, i := range items {
_, e = tx.ExecContext(ctx, `INSERT INTO feed_items(source_uuid,id,title,url,body,body_html,published_ms,feed,folder,is_read,starred) VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(source_uuid,id) DO UPDATE SET title=excluded.title,url=excluded.url,body=excluded.body,body_html=excluded.body_html,published_ms=excluded.published_ms,feed=excluded.feed,folder=excluded.folder,is_read=excluded.is_read,starred=excluded.starred`, v.UUID, i.ID, i.Title, i.URL, i.Body, i.BodyHTML, i.PublishedMS, i.Feed, i.Folder, i.Read, i.Starred)
categories := i.RemoteCategories
if categories == nil {
categories = []string{}
}
raw, _ := json.Marshal(categories)
_, e = tx.ExecContext(ctx, `INSERT INTO feed_items(source_uuid,id,title,url,body,body_html,published_ms,feed,folder,is_read,starred,remote_feed,remote_categories) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(source_uuid,id) DO UPDATE SET title=excluded.title,url=excluded.url,body=excluded.body,body_html=excluded.body_html,published_ms=excluded.published_ms,feed=excluded.feed,folder=excluded.folder,is_read=excluded.is_read,starred=excluded.starred,remote_feed=excluded.remote_feed,remote_categories=excluded.remote_categories`, v.UUID, i.ID, i.Title, i.URL, i.Body, i.BodyHTML, i.PublishedMS, i.Feed, i.Folder, i.Read, i.Starred, i.RemoteFeed, string(raw))
if e != nil {
return e
}
+75
View File
@@ -0,0 +1,75 @@
package store
import (
"context"
"encoding/json"
"strings"
"unicode/utf8"
)
// Remote IDs are opaque identities, not URLs to fetch or display labels.
type FeedCategory struct {
ID string `json:"id"`
Label string `json:"label"`
}
type FeedRemoteSubscription struct {
ID string `json:"id"`
Title string `json:"title"`
Categories []FeedCategory `json:"categories"`
}
func ValidFeedRemoteID(id string) bool {
return id != "" && len(id) <= 2048 && utf8.ValidString(id) && !strings.ContainsAny(id, "\x00\r\n")
}
// Bound both the number of entries and the encoded snapshot independently of
// the HTTP response limit. Invalid snapshots must not erase a good cache.
func FeedCatalogJSON(catalog []FeedRemoteSubscription) (string, error) {
if len(catalog) > 1000 {
return "", ErrTaskDAVLimit
}
seen := map[string]bool{}
labels := map[string]string{}
for _, sub := range catalog {
if !ValidFeedRemoteID(sub.ID) || seen[sub.ID] || len(sub.Title) > 512 || !utf8.ValidString(sub.Title) || len(sub.Categories) > 64 {
return "", ErrTaskInvalid
}
seen[sub.ID] = true
cats := map[string]bool{}
for _, c := range sub.Categories {
if !ValidFeedRemoteID(c.ID) || cats[c.ID] || len(c.Label) > 512 || !utf8.ValidString(c.Label) {
return "", ErrTaskInvalid
}
if label, ok := labels[c.ID]; ok && label != c.Label {
return "", ErrTaskInvalid
}
cats[c.ID], labels[c.ID] = true, c.Label
}
}
if catalog == nil {
catalog = []FeedRemoteSubscription{}
}
raw, e := json.Marshal(catalog)
if e != nil {
return "", e
}
if len(raw) > 1<<20 {
return "", ErrTaskDAVLimit
}
return string(raw), nil
}
func (s *Store) FeedCatalog(ctx context.Context, domain, owner, source string) ([]FeedRemoteSubscription, error) {
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
return nil, e
}
var raw string
if e := s.DB.QueryRowContext(ctx, `SELECT remote_catalog FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, source, domain, owner).Scan(&raw); e != nil {
return nil, e
}
var catalog []FeedRemoteSubscription
if e := json.Unmarshal([]byte(raw), &catalog); e != nil {
return nil, e
}
return catalog, nil
}
+41
View File
@@ -109,3 +109,44 @@ func TestFeedImportReceiptMigrationRollbackAndRepeat(t *testing.T) {
t.Fatal("receipt must survive deletion", count, err)
}
}
func TestFeedCatalogMigrationRollbackAndRepeat(t *testing.T) {
st := newSchemaTestStore(t)
ctx := context.Background()
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", feedMigrations[:3]); e != nil {
t.Fatal(e)
}
if _, e := st.DB.Exec(`INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,version,enabled,interval_seconds,lease,next_ms) VALUES('s','d','u','freshrss','Title','','https://example.org',7,1,300,'old',999); INSERT INTO feed_items(source_uuid,id,title,url,body,published_ms,feed,folder,is_read,starred,body_html) VALUES('s','i','Title','','Body',1,'','',1,1,'<p>Body</p>')`); e != nil {
t.Fatal(e)
}
broken := append([]db.SQLMigration(nil), feedMigrations...)
broken[3].Statements = append(append([]string(nil), feedMigrations[3].Statements...), `INSERT INTO no_such_feed_table VALUES(1)`)
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", broken); e == nil {
t.Fatal("expected failure")
}
var count int
if e := st.DB.QueryRow(`SELECT count(*) FROM pragma_table_info('feed_items') WHERE name='remote_feed'`).Scan(&count); e != nil || count != 0 {
t.Fatal("partial migration", count, e)
}
if e := st.DB.QueryRow(`SELECT version FROM feed_sources WHERE uuid='s'`).Scan(&count); e != nil || count != 7 {
t.Fatal("partial fence", count, e)
}
for range 2 {
if e := st.ensureSchemaComponent("feeds"); e != nil {
t.Fatal(e)
}
}
var version, next int
var catalog, lease, body string
var read, star bool
if e := st.DB.QueryRow(`SELECT version,next_ms,lease,remote_catalog FROM feed_sources WHERE uuid='s'`).Scan(&version, &next, &lease, &catalog); e != nil || version != 8 || next != 0 || lease != "" || catalog != "[]" {
t.Fatal(version, next, lease, catalog, e)
}
if e := st.DB.QueryRow(`SELECT body_html,is_read,starred FROM feed_items WHERE source_uuid='s'`).Scan(&body, &read, &star); e != nil || body != "<p>Body</p>" || !read || !star {
t.Fatal("lost old cache", body, read, star, e)
}
var integrity string
if e := st.DB.QueryRow(`PRAGMA integrity_check`).Scan(&integrity); e != nil || integrity != "ok" {
t.Fatal(integrity, e)
}
}
+1
View File
@@ -1,4 +1,5 @@
.feeds-page{height:100dvh;overflow:hidden;display:flex;flex-direction:column;background:var(--bg);color:var(--fg)}
.feed-catalog{padding:.3rem 0 .4rem .5rem;display:grid;gap:.3rem;border-left:2px solid var(--border,#8885)}#feeds-app .feed-catalog select,#feeds-app .feed-catalog input{width:100%;min-width:0;box-sizing:border-box;font-size:.75rem}.feed-subscriptions{display:grid;gap:0}.feed-subscriptions button{text-align:left;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:.75rem!important;border:0!important;content-visibility:auto;contain-intrinsic-size:auto 29px}.feed-subscriptions button[aria-current=true]{background:color-mix(in srgb,var(--accent,#659de4) 22%,transparent)!important}
.feed-opml{display:grid;gap:.6rem;min-width:0}.feed-opml>label{display:grid;gap:.25rem}.feed-opml input[type=file]{width:100%;box-sizing:border-box}.feed-opml table{width:100%;table-layout:fixed;border-collapse:collapse;font-size:.8rem}.feed-opml th,.feed-opml td{text-align:left;vertical-align:top;padding:.3rem;border-bottom:1px solid var(--border,#8885);overflow-wrap:anywhere}.feed-opml th:first-child{width:1.6rem}.feed-opml th:nth-child(3){width:20%}.feed-opml th:last-child{width:20%}.feed-opml small{display:block;font-size:.7rem;opacity:.7;overflow-wrap:anywhere}#feeds-app .feed-opml input[type=checkbox]{width:auto;min-height:1.2rem}.feed-import-options{display:flex;gap:.75rem;align-items:center;flex-wrap:wrap}#feeds-app .feed-import-options label:has(input[type=checkbox]){display:flex;align-items:center}.feed-opml input:disabled{opacity:.4}
#feed-status:empty{display:none}#feed-reader .feed-body-html{white-space:normal}.feed-original{display:inline-flex;align-items:center;justify-content:center;min-width:2rem;min-height:2rem;border-radius:.2rem}.feed-original:hover{background:var(--border,#8883)}.feed-original svg{width:1.1rem;height:1.1rem;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
.feeds-page .topbar,.feeds-page .organizer-nav{flex-shrink:0}.feeds-page #feeds-app{flex:1;min-height:0;display:flex;flex-direction:column;width:100%;max-width:none;margin:0;padding:0 .5rem .25rem;box-sizing:border-box}
+19 -3
View File
@@ -10,6 +10,7 @@
async function request(path,options={}){const response=await fetch(api+path,{credentials:'same-origin',cache:'no-store',...options,headers:{'Content-Type':'application/json',...options.headers}});if(response.redirected||response.status===401)throw Error(t('Please sign in again.','再度ログインしてください。'));const data=await response.json().catch(()=>({}));if(!response.ok)throw Error(response.status===412?t('Changed elsewhere or refresh is cooling down. Reload before retrying.','別の操作と競合したか、更新の待機時間中です。再読込して確認してください。'):t('Request failed: ','操作に失敗しました: ')+(data.error||response.status));return data;}
const post=(path,body)=>request(path,{method:'POST',body:JSON.stringify(body)});
let sources=[],items=[],selected=-1,currentSource='',filter='',search='',next=null,loading=false,seq=0,detailSeq=0,editing=false,controller,detailController;
let remoteFeed='',remoteCategory='',catalog=[],catalogSeq=0,catalogController;
const sourceLabel=el('strong','RSS'),searchbox=el('input');searchbox.type='search';searchbox.placeholder=t('Search titles / feeds… /','件名・配信元を検索… /');searchbox.ariaLabel=searchbox.placeholder;
const filters=el('select');for(const [v,en,jp]of [['','All','すべて'],['unread','Unread','未読'],['starred','Starred','star付き']]){const o=el('option',t(en,jp));o.value=v;filters.append(o);}filters.ariaLabel=t('Filter','絞り込み');filters.onchange=()=>{filter=filters.value;load(false).catch(report);};
const refresh=button('↻',t('Queue source refresh (r)','背景更新を予約 (r)'),queueRefresh);refresh.disabled=!writable;
@@ -25,18 +26,33 @@
function drawSources(){sourcesView.replaceChildren();const all=button(t('All sources','すべての購読元'),'',()=>chooseSource(''));sourcesView.append(all);let folder=null;
for(const source of sources){if(folder!==source.folder){folder=source.folder;sourcesView.append(el('h3',folder||t('Sources','購読元')));}const row=el('div',undefined,'feed-source');row.setAttribute('aria-current',String(currentSource===source.uuid));
const b=button((source.enabled?'':'⏸ ')+source.title,source.title,()=>chooseSource(source.uuid));if(source.error){b.classList.add('feed-source-error');b.title+=' · '+source.error;}row.append(b);if(writable)row.append(button('⚙',t('Source settings','購読元設定'),()=>sourceForm(source)));sourcesView.append(row);
if(source.uuid===currentSource&&source.provider==='freshrss')drawCatalog(sourcesView);
}
}
async function chooseSource(id){currentSource=id;drawSources();layout.classList.remove('sources-open','reading');editing=false;await load(false);}
function drawCatalog(parent){
const nav=el('div',undefined,'feed-catalog'),categories=el('select'),names=new Map();categories.ariaLabel=t('FreshRSS category','FreshRSSカテゴリ');categories.id='feed-category';
for(const sub of catalog)for(const cat of sub.categories)names.set(cat.id,cat.label);
for(const [id,name]of [['',t('All categories','すべてのカテゴリ')],...Array.from(names).sort((a,b)=>a[1].localeCompare(b[1]))]){const option=el('option',name);option.value=id;categories.append(option);}categories.value=remoteCategory;
categories.onchange=()=>{remoteCategory=categories.value;remoteFeed='';drawSources();load(false).catch(report);};nav.append(categories);
const find=el('input');find.type='search';find.placeholder=find.ariaLabel=t('Find subscription','購読を絞り込む');nav.append(find);
const list=el('div',undefined,'feed-subscriptions');nav.append(list);parent.append(nav);
const draw=()=>{list.replaceChildren();const subs=catalog.filter(sub=>(!remoteCategory||sub.categories.some(c=>c.id===remoteCategory))&&sub.title.toLocaleLowerCase().includes(find.value.toLocaleLowerCase())).sort((a,b)=>a.title.localeCompare(b.title));
const add=(id,title)=>{const b=button(title,title,async()=>{remoteFeed=id;for(const node of list.children)node.setAttribute('aria-current',String(node===b));layout.classList.remove('sources-open');await load(false);});b.dataset.feed=id;b.setAttribute('aria-current',String(id===remoteFeed));list.append(b);};add('',t('All subscriptions','すべての購読'));for(const sub of subs)add(sub.id,sub.title||sub.id);
};find.oninput=draw;draw();
}
async function loadCatalog(){catalogController?.abort();catalogController=new AbortController();const version=++catalogSeq;catalog=[];if(sources.find(s=>s.uuid===currentSource)?.provider!=='freshrss')return;
const data=await request('catalog?'+new URLSearchParams({source:currentSource}),{signal:catalogController.signal});if(version!==catalogSeq)return;catalog=data.subscriptions;drawSources();
}
async function chooseSource(id){currentSource=id;remoteFeed=remoteCategory='';catalog=[];drawSources();layout.classList.remove('reading');editing=false;await Promise.all([loadCatalog(),load(false)]);if(sources.find(s=>s.uuid===id)?.provider!=='freshrss')layout.classList.remove('sources-open');}
function rowNode(item,index){const row=el('div',undefined,'feed-row'+(item.read?'':' unread'));row.id='feed-row-'+index;row.setAttribute('role','option');row.setAttribute('aria-selected',String(index===selected));for(const text of [(item.starred?'★':item.read?' ':'●'),date(item.published_ms),item.feed||sources.find(s=>s.uuid===item.source)?.title||'',item.title||t('(Untitled)','(無題)')])row.append(el('span',text));row.title=item.title;row.onclick=()=>open(index).catch(report);return row;}
function drawRows(){rows.replaceChildren(...items.map(rowNode));more.hidden=!next;more.textContent='↓';more.title=more.ariaLabel=t('More articles','続きを表示');if(!items.length)rows.append(el('p',t('No articles','記事なし'),'feed-warning'));}
async function load(append){if(append&&(!next||loading))return;controller?.abort();controller=new AbortController();const version=++seq;loading=true;more.disabled=true;
try{const q=new URLSearchParams({source:currentSource,filter,q:search});if(append){q.set('before',next.ms);q.set('key',next.key);}const data=await request('items?'+q,{signal:controller.signal});if(version!==seq)return;
try{const q=new URLSearchParams({source:currentSource,filter,q:search,feed:remoteFeed,category:remoteCategory});if(append){q.set('before',next.ms);q.set('key',next.key);}const data=await request('items?'+q,{signal:controller.signal});if(version!==seq)return;
if(!append){detailSeq++;items=[];selected=-1;reader.replaceChildren();layout.classList.remove('reading');editing=false;}items.push(...data.items);const last=data.items.at(-1);next=data.more&&last?{ms:last.published_ms,key:last.source+':'+last.id}:null;drawRows();status.textContent='';
}finally{if(version===seq){loading=false;more.disabled=false;}}
}
more.onclick=()=>load(true).catch(report);
async function reload(){sources=(await request('sources')).sources;drawSources();await load(false);}
async function reload(){sources=(await request('sources')).sources;if(!sources.some(s=>s.uuid===currentSource)){currentSource=remoteFeed=remoteCategory='';}drawSources();await loadCatalog();if(remoteCategory&&!catalog.some(s=>s.categories.some(c=>c.id===remoteCategory)))remoteCategory='';if(remoteFeed&&!catalog.some(s=>s.id===remoteFeed))remoteFeed='';drawSources();await load(false);}
async function queueRefresh(){const targets=sources.filter(s=>s.enabled&&(!currentSource||currentSource===s.uuid));for(const s of targets)await post('sources/'+s.uuid+'/refresh',{version:s.version});status.textContent=t('Refresh queued','更新を予約しました');}
toolbar.append(button('⟳',t('Reload cached list','取得済み一覧を再読込'),reload));
async function open(index){if(index<0||index>=items.length)return;editing=false;selected=index;detailController?.abort();detailController=new AbortController();const version=++detailSeq;for(const [i,row]of [...rows.querySelectorAll('.feed-row')].entries())row.setAttribute('aria-selected',String(i===index));rows.setAttribute('aria-activedescendant','feed-row-'+index);document.getElementById('feed-row-'+index)?.scrollIntoView({block:'nearest'});
+2 -2
View File
@@ -1,9 +1,9 @@
{{ define "feeds.gohtml" }}<!doctype html>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{ T "feeds.title" }} · {{ .WikiName }}</title>
<link rel="stylesheet" href="/static/css/main.css"><link rel="stylesheet" href="/static/css/theme/base.css"><link rel="stylesheet" href="{{ .ThemeCSS }}"><link rel="stylesheet" href="/static/css/feeds.css?v=3"></head>
<link rel="stylesheet" href="/static/css/main.css"><link rel="stylesheet" href="/static/css/theme/base.css"><link rel="stylesheet" href="{{ .ThemeCSS }}"><link rel="stylesheet" href="/static/css/feeds.css?v=4"></head>
<body class="mode-view organizer-page feeds-page"><header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div>{{ template "auth-menu" . }}</header>{{ template "organizer-nav" . }}
<main id="feeds-app" data-writable="{{ .FeedWritable }}" data-tasks="{{ .TasksEnabled }}">
<div id="feed-toolbar"></div><p id="feed-status" role="status" aria-live="polite"></p>
<div class="feed-layout"><aside id="feed-sources" aria-label="{{ T "feeds.title" }}"></aside><section class="feed-index"><div id="feed-columns" aria-hidden="true"></div><div id="feed-rows" tabindex="0" role="listbox" aria-label="{{ T "feeds.title" }}"></div><button type="button" id="feed-more" hidden>↓</button></section><article id="feed-reader" tabindex="0"></article></div>
</main><script src="/static/js/feeds.js?v=3" defer></script></body></html>{{ end }}
</main><script src="/static/js/feeds.js?v=4" defer></script></body></html>{{ end }}