Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1057be6d2b | ||
|
|
e4c184d71c | ||
|
|
4711a0efbf | ||
|
|
61ecd1ffbd | ||
|
|
131a7ca01f |
No files matched your search
+4
-1
@@ -14,7 +14,10 @@ FROM source AS test
|
||||
# Test packages create independent SQLite stores. Serialize packages to avoid
|
||||
# concurrent server/store initialization exhausting the shared runner's I/O.
|
||||
# Keep production database deadlines and the complete test suite unchanged.
|
||||
RUN go test -p 1 ./...
|
||||
# Temporary test databases use bounded RAM-backed storage rather than the
|
||||
# runner's overlay filesystem. Compiler temporary files remain on disk.
|
||||
RUN --mount=type=tmpfs,target=/test-tmp,size=2147483648 \
|
||||
TMPDIR=/test-tmp GOTMPDIR=/tmp go test -p 1 ./...
|
||||
|
||||
FROM source AS runtime
|
||||
RUN go build -o /pageswiki ./cmd/pageswiki
|
||||
|
||||
+65
-10
@@ -1,7 +1,7 @@
|
||||
# 15. RSSビューア・FreshRSS・newsboat
|
||||
|
||||
状態:内蔵簡易reader、FreshRSS読取connector、共通viewer、Wiki保存・タスク化、ダッシュボードを実装。
|
||||
OPMLの確認付き追加取り込み・書出し、FreshRSS購読・カテゴリのnavigationも実装済み。FreshRSSへの書戻しは残件。本番反映と実FreshRSSへの接続は未実施。
|
||||
OPMLの確認付き追加取り込み・書出し、FreshRSS購読・カテゴリのnavigation、opt-inの既読・star書戻しを実装済み。本番反映と実FreshRSSへの接続は未実施。
|
||||
既存のブログRSS「配信」と、本章の外部RSS「購読」は別機能。
|
||||
|
||||
2026-11-08:利用者指定のサブプロジェクト順で最初に実施する。内蔵readerは簡易利用の
|
||||
@@ -33,7 +33,7 @@ FreshRSS停止時は取得済みcacheと鮮度・接続状態を示し、内蔵
|
||||
## 実装済みの読取機能
|
||||
|
||||
`/v/feeds` に購読一覧、フォルダ、記事一覧、外部原文へのリンク、Wiki保存を提供します。
|
||||
FreshRSSの記事・既読・starは取得しますが、状態の変更は送信しません。UIにも読取専用と明示し、
|
||||
FreshRSSの記事・既読・starを取得します。既定は読取専用で、source設定で明示的に許可した場合だけ状態の変更を送信します。
|
||||
FreshRSS passwordを設定時以外にブラウザへ返さず、login tokenはbackend内でのみ利用します。
|
||||
資格情報は既存の暗号化機構を使い、Domain・所有者・source UUID・用途に束縛します。
|
||||
|
||||
@@ -52,7 +52,7 @@ tooltipに残します。タブ名は「RSS」、原文リンクはアイコン
|
||||
|
||||
`j/k`・上下矢印で移動、`Enter/l`で本文、`Esc/h`で一覧、`/`で件名・配信元検索、`n`で次の未読、
|
||||
`m`で既読切替、`*`でstar、`r`で背景更新予約、`?`でキー案内です。フォーム入力・IME変換中は
|
||||
一覧ショートカットを抑止します。FreshRSSでは`m`と`*`も外部変更を行いません。
|
||||
一覧ショートカットを抑止します。FreshRSSでは書戻し許可時だけ`m`と`*`で操作を予約します。
|
||||
|
||||
HTML本文は見出し・表・箇条書き・強調・リンクを保持して描画し、plain textは文字情報として表示します。
|
||||
server側の許可リストでscript・イベント属性・任意CSS・form・iframe・画像等を除去し、表示時にも再検査します。
|
||||
@@ -75,6 +75,11 @@ API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用
|
||||
| `GET catalog?source=…` | 本人のFreshRSS購読・カテゴリの取得済み一覧。外部通信なし |
|
||||
| `GET item?source=…&id=…` | 本人の記事本文 |
|
||||
| `POST state` | 内蔵read/starの条件付き変更。FreshRSSは拒否 |
|
||||
| `POST remote-state` | FreshRSSの一記事・一項目の変更を予約。request_id、source、id、field、desired、source_versionを指定 |
|
||||
| `GET action?source=…&id=…` | 本人の記事の最新操作記録。外部通信なし |
|
||||
| `GET actions` | 本人の操作履歴。status/sourceで絞り込み、50件単位のkeysetページング |
|
||||
| `GET action/export?request_id=…` | 本人の操作記録1件をJSON attachmentで保存。資格情報・本文・worker claimは含めない |
|
||||
| `POST action/check` | request_idで結果不明操作の読取専用再確認を予約 |
|
||||
| `POST note` | 公開範囲確認付きのWiki単独保存。request_idと入力hashで再送を識別 |
|
||||
| `GET opml/export` | 本人の内蔵購読をOPML 2.0としてダウンロード |
|
||||
| `POST opml/preview` | ファイルを解析し、追加可能・登録済み・重複・未対応等を返す。保存・外部通信なし |
|
||||
@@ -86,6 +91,9 @@ v2で`feed_items.body_html`を追加します。既存のテキスト本文・
|
||||
v3で`feed_import_receipts`を追加し、購読の一括追加と再送記録を同時保存します。
|
||||
v4でsourceに購読一覧、記事にremote feed ID・カテゴリIDを追加します。FreshRSSの旧workerを
|
||||
versionで無効化し、次の背景取得を予約します。内蔵sourceのversion・取得予約は変更しません。
|
||||
v5でsourceの`write_enabled`(既定OFF)と`feed_actions`を追加します。操作記録はsourceを削除しても保持し、
|
||||
送信済みの可能性があるものはunknown、未送信はcancelledにします。DB更新前にバックアップを取得し、
|
||||
旧バイナリへの切戻しだけで追加schemaが巻き戻るとは扱いません。
|
||||
既存テーブルを破壊・再構成しません。SQLiteのforeign_keys設定に依存せず削除を完遂するtriggerを
|
||||
持ちます。内蔵read/starを本文cacheから分離し、記事を保持窓から落としても状態は黙って消しません。
|
||||
DBは内蔵購読・状態・保存receiptの正本であり、全体を捨てられるcacheとは扱いません。
|
||||
@@ -100,6 +108,7 @@ sourceのprovider・URL・資格情報の変更は別sourceを作る契約です
|
||||
| --- | --- |
|
||||
| 個人のsource数 | Domain・本人ごとに32 |
|
||||
| 定期event | `feed.source.sync`、既定60秒周期、低優先度、1回最大4 sourceを直列取得 |
|
||||
| 書戻しworker | 同じevent内で最大2操作を先に処理。各8秒、取得と合計35秒の予算を共有し、残り9秒未満なら次の操作・取得を開始しない |
|
||||
| source更新間隔 | 5〜1440分、既定30分。取得候補になる間隔であり、混雑時の完了時刻保証ではない |
|
||||
| 通信予算 | 1 source 8秒、batch 35秒、応答/展開後本文4 MiB |
|
||||
| 外部接続 | 公開HTTPS/443のみ。DNS検査・接続先固定、内部アドレス・redirect・proxyを拒否 |
|
||||
@@ -127,22 +136,24 @@ source指定と組み合わせ、既存の未読・star・検索・keysetペー
|
||||
絞り込み対象は最新200記事のcache内に限られ、購読を選んでも履歴全件を外部取得しません。
|
||||
購読の追加・削除やカテゴリの編集はFreshRSS側で行います。
|
||||
|
||||
## 既読・star同期を追加する条件
|
||||
## 既読とstarの書戻し
|
||||
|
||||
server-authoritative stateと未送信の操作を分けます。操作ごとのrequest_idで重複を防ぎ、成功応答前に確定済みと表示しません。newsboat等で同時変更された場合、古いローカルcacheをまとめて送り返しません。接続解除・認可失効時は未送信変更を勝手に再送しません。
|
||||
|
||||
FreshRSS APIに条件付き更新がない操作もあり得るため、対応版の実機fixtureで競合動作を確認するまで完全な双方向同期を約束しません。
|
||||
FreshRSSへの変更は一項目のtag追加・削除です。更新直前の状態と不可分に照合するCASではないため、
|
||||
他clientとの同時操作を完全に直列化する双方向同期ではありません。
|
||||
|
||||
### 書戻しの次段階設計
|
||||
### 操作記録と送信状態
|
||||
|
||||
以下は未実装のRSS-3です。購読navigationの追加だけでは書戻しを有効にしません。
|
||||
sourceごとに既定OFFの書戻し設定を設け、操作は`read`または`starred`の一項目と希望値に限定します。
|
||||
RSS-3は合成環境で実装・検証済みです。sourceごとに既定OFFの「FreshRSSの既読・star変更を許可」を設け、操作は`read`または`starred`の一項目と希望値に限定します。
|
||||
cache内の他項目を同時に送らず、全件既読・購読編集も初期対象に含めません。
|
||||
|
||||
操作記録は記事cacheから分離し、Domain・本人・request_id、source・記事ID、対象項目、希望値、
|
||||
source version、状態、claim期限を保持します。同一request_idの同じ入力は同じ記録を返し、
|
||||
違う入力は拒否します。同じ記事に未解決の操作がある間は次の操作を受け付けません。
|
||||
受付APIは外部通信せず、低優先度workerが送信します。記録数とworkerの時間予算は必ず有限にします。
|
||||
受付APIは外部通信せず、低優先度workerが送信します。Domain・本人ごとに未解決20件、全記録10,000件を上限とし、
|
||||
上限で新規受付を拒否します。receiptを自動削除して古い要求を再送可能にすることはしません。
|
||||
queuedは受付から5分で失効します。claimは60秒で、期限切れsending/checkingはunknownにし、変更を再送しません。
|
||||
|
||||
| 状態 | 次の処理 |
|
||||
| --- | --- |
|
||||
@@ -160,6 +171,48 @@ source version、状態、claim期限を保持します。同一request_idの同
|
||||
外部clientとの同時変更を原子的に防げないAPIでは、確認直後に状態が再変更される可能性もあります。
|
||||
readbackは観測結果であり、exactly-onceやリモートCASの保証とは区別します。
|
||||
|
||||
結果不明時は操作欄の`↻`からclaim期限後に再確認できます。書戻し設定をOFFにしても、sourceが有効なら
|
||||
この読取専用再確認は可能です。画面は未解決操作の間だけ2秒間隔で自サーバーの記録を確認し、
|
||||
背景タブでは停止します。記事の既読・star表示は遠隔の状態を確認するまで切り替えません。
|
||||
再確認で希望値と異なる場合はconflictを表示し、新しい変更は利用者が明示的に操作します。
|
||||
|
||||
### 操作履歴の一覧と保全
|
||||
|
||||
ツールバーの時計アイコンから、リーダー内に操作履歴を開きます。モーダルは増やしません。
|
||||
日時、記事・購読元、変更対象と希望値、状態をまとめ、記事がcache内なら本文へ戻れます。
|
||||
スマホ幅では日時・件名・状態を縦にまとめ、再確認・保存のアイコンをタッチできる大きさにします。
|
||||
|
||||
既定の「未解決」はconfirmed/cancelled以外を表示し、処理中、結果不明、すべて、確認済み、
|
||||
未送信、不一致、中止で絞り込めます。一覧はローカルDBだけを読み、外部通信や自動再試行を行いません。
|
||||
履歴の更新は再読込アイコンと絞り込み操作で行い、記事画面の2秒pollは履歴画面では停止します。
|
||||
`GET actions`のstatusは`unresolved`(省略時も同じ)、`pending`、`unknown`、`all`、
|
||||
`confirmed`、`failed`、`conflict`、`cancelled`です。sourceは削除済みUUIDも指定できます。
|
||||
続きは末尾のcreated_msとrequest_idを`before`/`key`として渡します。同時刻の操作も重複・欠落なく辿ります。
|
||||
1回50件+続き判定の1件を読み、所有者の10,000件上限でソート量を制限します。
|
||||
|
||||
sourceや記事へのinner joinは使わず、削除済み購読元やcache窓から外れた記事の記録も残します。
|
||||
記事名・購読元名は現在の取得済み情報であり、操作時点の監査snapshotではありません。
|
||||
取得できない場合は元のsource UUID/記事IDと「削除済み」「キャッシュ外」を表示します。
|
||||
結果不明の記録は、同じDomain・本人の有効なFreshRSS sourceが残り、claim期限を過ぎた場合だけ
|
||||
読取専用再確認を予約できます。書戻しOFFでも再確認でき、readonlyアカウントは閲覧・保存のみです。
|
||||
削除済みsourceは自動再接続しません。本人の記録に残るsource UUID、および全体の未解決操作に
|
||||
残るsource UUIDの新規登録を拒否し、別接続先への誤った結び付けを防ぎます。
|
||||
|
||||
各行からJSON形式(`pageswiki.feed-action`、version 1)の記録を書き出せます。
|
||||
Domain/本人/request ID、操作内容、状態、日時、現在の表示用メタデータを含み、
|
||||
外部URL・資格情報・本文・内部claimは出力しません。ただし元の記事ID自体がURLの場合はそのIDを保持します。
|
||||
一覧・保存ともDomain・本人で制限し、private/no-storeで返します。schemaはv5のままです。
|
||||
|
||||
保存操作はDBからの削除を意味しません。receiptを削除すると同じrequest_idの再送を防げなくなるため、
|
||||
自動削除・一括削除は未実装です。後段の整理機能では、保全manifest・hash・対象件数を照合した上で、
|
||||
成功/中止/失敗等の終端記録だけをarchiveへ移し、重複防止に必要なrequest_idと入力識別子を
|
||||
tombstoneとして保持します。unknownや実行中の記録は移動・削除対象にしません。
|
||||
tombstoneの保持期間・容量上限・旧クライアントからの再送時応答を決めるまで、現在の10,000件上限を維持します。
|
||||
|
||||
外部APIはlogin、記事参照、変更token、edit-tag、記事再参照の順です。記事の個別参照は
|
||||
`POST stream/items/contents`(読取操作)、変更は`POST edit-tag`に`i`・`T`・`a`または`r`一項目を送ります。
|
||||
URLや本文、資格情報を操作記録・ログへ保存しません。[FreshRSS API実装](https://github.com/FreshRSS/FreshRSS/blob/edge/p/api/greader.php)。
|
||||
|
||||
受入テストは、opt-inなしの拒否、同じ操作の再送、別項目の保持、送信前の権限失効、
|
||||
送信直後の応答喪失、worker停止・再起動、unknownの読取専用再確認、source削除・設定変更、
|
||||
通常取得との排他、他clientによる同時変更を含めます。実サービスを使わない合成fixtureで
|
||||
@@ -222,7 +275,9 @@ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。
|
||||
|
||||
- [x] RSS-1:read-only FreshRSS connectorと合成fixture。実接続の受入は別。
|
||||
- [x] RSS-2:安全な共通一覧、出典付きWiki保存、任意のタスク化、ダッシュボード。
|
||||
- [ ] RSS-3:FreshRSSへの明示的な既読/star操作と送信状態・競合・再送の契約。
|
||||
- [x] RSS-3:opt-inの既読/star書戻し、操作receipt、背景処理、readback、結果不明の再確認、失効・競合・排他の合成試験。
|
||||
- [x] RSS-3b1:未解決操作の総覧、cache窓外・削除sourceの記録、再送しない再確認、個別JSON保存。50件ページング、本人分離、readonly、1440px/390pxの合成試験。
|
||||
- [ ] RSS-3b2:保全manifestの照合、終端receiptのarchive、重複防止tombstoneと保持期間・容量上限。未知結果の記録を捨てない。
|
||||
- [x] RSS-4a:内蔵簡易reader、購読設定、既読・star、背景取得。
|
||||
- [x] RSS-4b:OPML export/importのpreview、選択追加、重複確認、原子的な保存と再送防止。置換・状態移行は範囲外。
|
||||
- [ ] RSS-5:FreshRSS実環境の接続先・版・API資格情報を指定してread-only受入。
|
||||
|
||||
@@ -121,6 +121,19 @@ Gitea 1.24 の自動ジョブトークンによるパッケージ公開は前提
|
||||
|
||||
アプリイメージにはソースコードが含まれるため、パッケージの公開範囲にも注意する。
|
||||
|
||||
## テスト用一時領域
|
||||
|
||||
Dockerfileのtest段階では、全Goテストを`-p 1`でパッケージ単位に直列化する。
|
||||
テスト用`TMPDIR`は最大2GiBのtmpfsとし、SQLiteの一時DBをrunnerのoverlay filesystemから分離する。
|
||||
コンパイラ用`GOTMPDIR`はディスク側の`/tmp`に残す。tmpfsは当該RUNの間だけ存在し、
|
||||
runtime段階や本番の保存先・WAL・接続タイムアウトには影響しない。
|
||||
|
||||
CI run 54では、直列化後も既存の壁紙・Ordoschnellic・Seheweitのテストが
|
||||
SQLite接続初期化の5秒タイムアウトで失敗した。ストレージ競合を避ける措置であり、
|
||||
テスト除外・再試行による成功扱い・本番の期限緩和は行わない。
|
||||
tmpfsは最大2GiBのメモリを消費し得るため、runnerにはコンパイラ等と合わせた余裕が必要。
|
||||
実ファイル保存の移行確認は、CIとは別に本番DBの隔離コピーで行う。
|
||||
|
||||
## タグ・容量・本番利用
|
||||
|
||||
3 イメージ共通で `sha-<40桁のコミットID>` を使用し、自動 latest は付けない。
|
||||
@@ -161,3 +174,4 @@ prefix の変更は `PAGESWIKI_IMAGE_PREFIX`(既定 git.anya.jp/anya)。
|
||||
- [Gitea 1.24 Actions の互換性・制限](https://docs.gitea.com/1.24/usage/actions/comparison/)
|
||||
- [Gitea Container Registry](https://docs.gitea.com/usage/packages/container/)
|
||||
- [Docker コンテナの DNS と hosts](https://docs.docker.com/engine/network/#dns-services)
|
||||
- [Dockerfileの一時tmpfsマウント](https://docs.docker.com/reference/dockerfile/#run---mounttype-tmpfs)
|
||||
@@ -0,0 +1,100 @@
|
||||
# RSSリリースとFreshRSS書き戻しの本番反映
|
||||
|
||||
## リリース境界
|
||||
|
||||
注釈付きタグ`v0.11.0`は`16e572397b2b1abf096bd6bca26e2af832768b8d`を指す。
|
||||
RSSの内蔵reader、OPML、FreshRSSの読み取り・購読カタログまでの区切りであり、タグは移動しない。
|
||||
その後の既読・star書き戻しを含む本番反映は`61ecd1ffbdf46897d50c2f7eb7a2e1415f1bb456`。
|
||||
`131a7ca`で機能を実装し、`61ecd1f`でCIのテスト一時領域だけを改善した。
|
||||
2026-11-08 JSTに本番反映済み。独立pages-cliや未コミットのメール保存先調査は対象外。
|
||||
|
||||
## 機能と安全条件
|
||||
|
||||
FreshRSSを正本とし、source単位で明示的に許可した場合だけ既読・starの変更を送る。
|
||||
許可は既定OFF。UI操作は永続キューへ入り、外部での確認後に表示へ反映する。
|
||||
送信結果が不明になった場合は自動再送せず、利用者の再確認操作で外部状態を読む。
|
||||
操作IDによる重複防止、source更新との競合、権限失効、source削除、共有leaseを扱う。
|
||||
詳細と残件は[RSS設計](../../design/ja/feeds.md)を参照。
|
||||
|
||||
今回の本番移行には、前段のタスク作業記録訂正監査・日次ダイジェストの送信試行記録も含む。
|
||||
管理対象スキーマの差分は、feedsの未導入状態からv5、task-productivityのv2からv4。
|
||||
ファイル正本の一括書換えは行わない。後続版のスキーマを旧版へ自動downgradeしない。
|
||||
|
||||
## 検証記録
|
||||
|
||||
- 手元で`go test -p 1 ./...`、`go vet ./...`が成功。
|
||||
- feeds関連のrace検査、1440px・390pxのChromium試験、JavaScript構文検査が成功。
|
||||
- 合成FreshRSSでread/starの追加・解除、応答喪失、再確認、競合、設定変更・失効を検査。
|
||||
- v5の移行失敗時rollback、再実行、既定OFF、source削除後の操作記録保持を検査。
|
||||
- [CI run 53](https://git.anya.jp/anya/pages/actions/runs/53)はv0.11.0候補の全テスト・3イメージの公開に成功。
|
||||
[release run 55](https://git.anya.jp/anya/pages/actions/runs/55)で既存イメージを再ビルドせずv0.11.0へ昇格した。
|
||||
- CI run 54は既存3テストのSQLite接続初期化が5秒でtimeout。追加したFreshRSS試験の失敗ではない。
|
||||
該当3テストを手元で各3回成功。テスト専用tmpfsを導入し、
|
||||
[run 56](https://git.anya.jp/anya/pages/actions/runs/56)で全テスト・3イメージ公開が成功。
|
||||
server 97.912秒、store 27.685秒。テスト省略や本番のdeadline変更は行っていない。
|
||||
詳しくは[CI運用](../gitea-images.md#テスト用一時領域)を参照。
|
||||
- 前回停止時バックアップを独立コピーし、ネットワーク遮断・workers無効で主/外部DBを起動。
|
||||
v0.11.0候補でfeeds v4・task-productivity v4への移行、health、schema check、integrity_checkが成功。
|
||||
外部インスタンスのリハーサルでは再登録を実行せず、既存DBを通常起動した。
|
||||
最終イメージではコピーを旧版の状態に戻して起動し、両DBともfeeds v5・task-productivity v4まで
|
||||
移行した後のhealth・schema check・SQLite integrity_checkが成功した。
|
||||
|
||||
外部取り込みカレンダーと実メール本文は取得・表示していない。実FreshRSSへの操作も行っていない。
|
||||
DB・正本の保全はファイルコピーとバイト照合だけを用いる。実サービスへの書き戻し受入確認は残る。
|
||||
|
||||
## 保全・切替手順
|
||||
|
||||
保全先は`.deployment-backups/release-rss-20261108/`。親0700、構成コピー0600。
|
||||
旧構成と停止時点の`cutover/data`・`cutover/data2`を保持する。
|
||||
変更のないファイルは前回の不変バックアップとのみhardlinkを共有し、稼働元とは共有しない。
|
||||
ディスク空きがDBより小さいため、今回新しく独立コピーしたpages.db(link数1を検証)だけは
|
||||
停止後にchecksum付きin-place同期する。他のファイルにin-place更新を使わない。
|
||||
最終checksum差分ゼロとDBのバイト一致を確認してから新しいイメージを起動する。
|
||||
旧バックアップ・旧イメージは削除しない。
|
||||
|
||||
対象はapp・app2・adaptor-gateway・excalidraw-viewerの4サービス。
|
||||
CI成功後の同一SHAの3イメージをpullし、registry overlayで`up --no-build --no-deps`する。
|
||||
code-server・Kroki・独立CLI・ネットワーク構成は変更しない。
|
||||
切戻しが必要な場合は書込みを停止し、切替後データも保全した上で互換性を判断する。
|
||||
稼働中DBへ旧バックアップを自動復元しない。
|
||||
|
||||
## 本番反映結果
|
||||
|
||||
2026-11-08 06:20:55 JSTに停止開始、06:22:12にバックアップ最終照合・sync完了、
|
||||
06:22:37に4サービスの起動確認完了。停止開始から起動確認まで102秒。
|
||||
`.env.release`は`sha-61ecd1ffbdf46897d50c2f7eb7a2e1415f1bb456`を指定する。
|
||||
本番のバージョン指定はv0.11.0タグそのものではなく、追加実装を含むこの固定SHAである。
|
||||
|
||||
| イメージ | manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:e452a7dbadf13c89909c5ee6a685fa39342926675dec2253747534ef6ffabfb0` |
|
||||
| pageswiki-adaptor-gateway | `sha256:77efae4ef3651e12ebac6a15474448dd93bfa89a7072b8db8e296322a68a7956` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:45b6399438fa1b40d54c0b6dfbcc15ca1464abb03b454e8b281d94d58c80b250` |
|
||||
|
||||
4コンテナのsource revision一致・running・再起動0回を確認。主/外部インスタンスのhealth正常、
|
||||
両DBの管理対象13コンポーネントのschema checkはcurrent。
|
||||
このschema checkだけで全データや全legacy schemaの完全性を保証するものではない。
|
||||
公開HTTPSのhealth・ログインは200、匿名RSS・タスク・拡張設定画面は303、RSSのsources・action APIは401。
|
||||
配信feeds.jsとfeeds.cssのSHA256は配備コミットと一致する。
|
||||
起動後ログのpanic・fatal・database is locked・event job failed・schema失敗の検索パターンは0件。
|
||||
|
||||
最終バックアップの両ルートともchecksum付きdry-runの差分はゼロ。
|
||||
旧v0.10.0イメージは`rollback-before-rss-20261108`タグで保持し、ローカルlatestは新イメージに揃えた。
|
||||
今回作成した隔離リハーサル用の一時コピーとコンテナは片付けたが、旧バックアップは削除していない。
|
||||
完了時のディスク空きは約4GiB。その後の容量整理は次節のとおり。
|
||||
|
||||
FreshRSSの書き戻し許可は自動有効化していない。本番ユーザーの設定・記事状態を試験のために変更せず、
|
||||
外部取り込みカレンダー・実メール・実FreshRSSへ検証用アクセスを行っていない。
|
||||
|
||||
## 容量整理
|
||||
|
||||
2026-11-08、ユーザーの削除指示を受け、旧リリースのバックアップ8世代を削除した。
|
||||
対象はrelease-v0.4.0、v0.5.0、v0.6.0、v0.7.0、v0.7.1、v0.8.0、v0.8.1、v0.9.0の各ディレクトリ。
|
||||
現在の切替直前を保全した`release-rss-20261108`と、その前の`release-v0.10.0-20261107`を残した。
|
||||
hardlink共有ファイルも、残したバックアップの参照は維持される。開発時の小さなソース保全やrsyncログは変更していない。
|
||||
9月のrsyncログを11月のバックアップの外部転送証明とは扱わず、今回の保持世代整理として削除した。
|
||||
|
||||
DockerはPagesWikiの指定repositoryだけを対象に、全コンテナの使用中image ID、v0.10.0の切戻し用、
|
||||
v0.11.0の手元イメージを保護した。旧43 image IDに属する102タグと関連参照をforceなしで削除。
|
||||
daemon全体のprune、レジストリの削除、他サービスのイメージ/volume削除は行っていない。
|
||||
本番停止は不要で、空き容量は約4GiBから約61GiBへ増えた。
|
||||
@@ -42,6 +42,9 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
key := strings.TrimPrefix(r.URL.Path, feedsAPI)
|
||||
if s.handleFeedAction(w, r, domain, actor, key) {
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(key, "opml/") {
|
||||
s.handleFeedOPML(w, r, domain, actor, key)
|
||||
return
|
||||
@@ -211,6 +214,6 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
func init() {
|
||||
translations["en"]["feeds.title"] = "RSS"
|
||||
translations["ja"]["feeds.title"] = "RSS"
|
||||
translations["en"]["feeds.help"] = "Private local feeds and read-only FreshRSS integration"
|
||||
translations["ja"]["feeds.help"] = "個人用の簡易RSSとFreshRSS読取連携"
|
||||
translations["en"]["feeds.help"] = "Private local feeds and FreshRSS integration with optional read/star updates"
|
||||
translations["ja"]["feeds.help"] = "個人用の簡易RSSとFreshRSS連携(既読・star変更は任意)"
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func freshRSSItem(ctx context.Context, client *http.Client, base, auth, id string) (*store.FeedItem, error) {
|
||||
// FreshRSS uses POST for this read-only item lookup (not GET ?i=...).
|
||||
raw, _, _, e := feedRequest(ctx, client, "POST", base+"/reader/api/0/stream/items/contents", auth, url.Values{"i": {id}}, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
items, e := parseFreshRSSItems(raw, base)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if len(items) != 1 || items[0].ID != id {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
return &items[0], nil
|
||||
}
|
||||
func feedActionMatches(a store.FeedAction, i *store.FeedItem) bool {
|
||||
if a.Field == "read" {
|
||||
return i.Read == a.Desired
|
||||
}
|
||||
return i.Starred == a.Desired
|
||||
}
|
||||
|
||||
func (s *Server) runFeedAction(ctx context.Context, client *http.Client, a store.FeedAction, source store.FeedSource) (status, code string, observed *store.FeedItem) {
|
||||
status = "failed"
|
||||
if a.Status == "checking" {
|
||||
status = "unknown"
|
||||
}
|
||||
fail := func(e error) (string, string, *store.FeedItem) {
|
||||
c := e.Error()
|
||||
switch c {
|
||||
case "network", "credentials", "remote_error", "limit", "invalid_feed":
|
||||
default:
|
||||
c = "invalid_feed"
|
||||
}
|
||||
return status, c, nil
|
||||
}
|
||||
if !validCalendarSourceURL(source.URL) {
|
||||
return fail(errFeedInvalid)
|
||||
}
|
||||
user, password, e := s.store.OpenFeedCredential(source)
|
||||
if e != nil {
|
||||
return fail(errors.New("credentials"))
|
||||
}
|
||||
auth, e := freshRSSLogin(ctx, client, source, user, password)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
base := strings.TrimRight(source.URL, "/")
|
||||
item, e := freshRSSItem(ctx, client, base, auth, a.ID)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
if feedActionMatches(a, item) {
|
||||
return "confirmed", "", item
|
||||
}
|
||||
if a.Status == "checking" {
|
||||
return "conflict", "conflict", item
|
||||
}
|
||||
raw, _, _, e := feedRequest(ctx, client, "GET", base+"/reader/api/0/token", auth, nil, nil)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
token := strings.TrimSpace(string(raw))
|
||||
if token == "" || len(token) > 4096 || strings.ContainsAny(token, "\r\n") {
|
||||
return fail(errFeedInvalid)
|
||||
}
|
||||
if e = s.store.MarkFeedActionSending(ctx, a, source); e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
// From this point every uncertain result is terminal until an explicit
|
||||
// read-only recheck. Neither the worker nor a repeated HTTP request resends.
|
||||
status = "unknown"
|
||||
field := "r"
|
||||
if a.Desired {
|
||||
field = "a"
|
||||
}
|
||||
form := url.Values{"i": {a.ID}, "T": {token}, field: {"user/-/state/com.google/" + a.Field}}
|
||||
raw, _, _, e = feedRequest(ctx, client, "POST", base+"/reader/api/0/edit-tag", auth, form, nil)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
if strings.TrimSpace(string(raw)) != "OK" {
|
||||
return fail(errFeedInvalid)
|
||||
}
|
||||
item, e = freshRSSItem(ctx, client, base, auth, a.ID)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
if !feedActionMatches(a, item) {
|
||||
return "conflict", "conflict", item
|
||||
}
|
||||
return "confirmed", "", item
|
||||
}
|
||||
func (s *Server) syncFeedActions(ctx context.Context, client *http.Client) error {
|
||||
actions, e := s.store.DueFeedActions(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for _, a := range actions {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < 9*time.Second {
|
||||
break
|
||||
}
|
||||
a, source, e := s.store.ClaimFeedAction(ctx, a)
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
child, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
status, code, item := s.runFeedAction(child, client, a, source)
|
||||
cancel()
|
||||
e = s.store.CompleteFeedAction(ctx, a, source, status, code, item)
|
||||
if e != nil && !errors.Is(e, store.ErrAccessDenied) && !errors.Is(e, store.ErrTaskConflict) {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) handleFeedAction(w http.ResponseWriter, r *http.Request, domain, actor, key string) bool {
|
||||
if s.handleFeedHistory(w, r, domain, actor, key) {
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case key == "action" && r.Method == "GET":
|
||||
a, e := s.store.FeedAction(r.Context(), domain, actor, r.URL.Query().Get("source"), r.URL.Query().Get("id"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"action": a})
|
||||
return true
|
||||
case key == "remote-state" && r.Method == "POST":
|
||||
var input store.FeedAction
|
||||
if !taskJSON(w, r, &input) {
|
||||
return true
|
||||
}
|
||||
a, e := s.store.QueueFeedAction(r.Context(), domain, actor, input)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
writeEventJSON(w, 202, map[string]any{"action": a})
|
||||
return true
|
||||
case key == "action/check" && r.Method == "POST":
|
||||
var input struct {
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
if !taskJSON(w, r, &input) {
|
||||
return true
|
||||
}
|
||||
if e := s.store.RecheckFeedAction(r.Context(), domain, actor, input.RequestID); e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
writeEventJSON(w, 202, map[string]bool{"ok": true})
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func feedActionFixture(t *testing.T) (*Server, string, string, string, store.FeedSource) {
|
||||
t.Helper()
|
||||
s, token, domain, actor, _ := feedFixture(t)
|
||||
ctx := context.Background()
|
||||
v := store.FeedSource{UUID: uuid.NewString(), Provider: "freshrss", Title: "Remote", URL: "https://example.org/api/greader.php", Enabled: true, WriteEnabled: 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)
|
||||
}
|
||||
all, e := s.store.FeedSources(ctx, domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, x := range all {
|
||||
if x.UUID == v.UUID {
|
||||
v = x
|
||||
}
|
||||
}
|
||||
c, e := s.store.ClaimFeed(ctx, v)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.store.CompleteFeed(ctx, c, []store.FeedItem{{ID: "one", Title: "Article", Starred: true}}, "", "", "", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return s, token, domain, actor, v
|
||||
}
|
||||
func newFeedAction(v store.FeedSource) store.FeedAction {
|
||||
return store.FeedAction{RequestID: uuid.NewString(), Source: v.UUID, ID: "one", Field: "read", Desired: true, SourceVersion: v.Version}
|
||||
}
|
||||
|
||||
type feedRemoteFake struct {
|
||||
id string
|
||||
read, star, timeout bool
|
||||
edits, lookups, requests int
|
||||
beforeEdit func()
|
||||
afterEdit func()
|
||||
}
|
||||
|
||||
func (f *feedRemoteFake) client(t *testing.T) *http.Client {
|
||||
return &http.Client{Transport: feedTransportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
id := f.id
|
||||
if id == "" {
|
||||
id = "one"
|
||||
}
|
||||
f.requests++
|
||||
body := ""
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/ClientLogin"):
|
||||
body = "Auth=test-auth"
|
||||
case strings.HasSuffix(r.URL.Path, "/stream/items/contents"):
|
||||
if r.Method != "POST" {
|
||||
t.Fatal("read lookup requires POST")
|
||||
}
|
||||
r.ParseForm()
|
||||
if r.Form.Get("i") != id {
|
||||
t.Fatal("wrong item")
|
||||
}
|
||||
f.lookups++
|
||||
cats := []string{}
|
||||
if f.read {
|
||||
cats = append(cats, "user/reader/state/com.google/read")
|
||||
}
|
||||
if f.star {
|
||||
cats = append(cats, "user/reader/state/com.google/starred")
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"items": []map[string]any{{"id": id, "title": "Article", "categories": cats}}})
|
||||
body = string(raw)
|
||||
case strings.HasSuffix(r.URL.Path, "/token"):
|
||||
body = "write-token"
|
||||
if f.beforeEdit != nil {
|
||||
f.beforeEdit()
|
||||
}
|
||||
case strings.HasSuffix(r.URL.Path, "/edit-tag"):
|
||||
if r.Method != "POST" {
|
||||
t.Fatal("mutation method")
|
||||
}
|
||||
r.ParseForm()
|
||||
if len(r.Form) != 3 || r.Form.Get("T") != "write-token" || r.Form.Get("i") != id {
|
||||
t.Fatal("unexpected mutation fields", r.Form)
|
||||
}
|
||||
if tag := r.Form.Get("a"); tag != "" {
|
||||
switch tag {
|
||||
case "user/-/state/com.google/read":
|
||||
f.read = true
|
||||
case "user/-/state/com.google/starred":
|
||||
f.star = true
|
||||
default:
|
||||
t.Fatal("wrong tag", tag)
|
||||
}
|
||||
} else {
|
||||
switch r.Form.Get("r") {
|
||||
case "user/-/state/com.google/read":
|
||||
f.read = false
|
||||
case "user/-/state/com.google/starred":
|
||||
f.star = false
|
||||
default:
|
||||
t.Fatal("wrong tag")
|
||||
}
|
||||
}
|
||||
f.edits++
|
||||
if f.afterEdit != nil {
|
||||
f.afterEdit()
|
||||
}
|
||||
if f.timeout {
|
||||
return nil, errors.New("synthetic response lost after apply")
|
||||
}
|
||||
body = "OK"
|
||||
default:
|
||||
t.Fatal("unexpected path", r.URL.Path)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
}
|
||||
func TestFeedActionWritebackReceiptAndIsolation(t *testing.T) {
|
||||
s, token, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
w := feedRequestTest(s, token, "POST", "remote-state", a)
|
||||
if w.Code != 202 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "POST", "remote-state", a); w.Code != 202 {
|
||||
t.Fatal("replay", w.Code, w.Body)
|
||||
}
|
||||
changed := a
|
||||
changed.Desired = false
|
||||
if w = feedRequestTest(s, token, "POST", "remote-state", changed); w.Code != 412 {
|
||||
t.Fatal("changed replay", w.Code)
|
||||
}
|
||||
changed.RequestID = uuid.NewString()
|
||||
if w = feedRequestTest(s, token, "POST", "remote-state", changed); w.Code != 412 {
|
||||
t.Fatal("parallel intent", w.Code)
|
||||
}
|
||||
item, _ := s.store.FeedItem(ctx, domain, actor, v.UUID, "one")
|
||||
if item.Read {
|
||||
t.Fatal("optimistic cache mutation")
|
||||
}
|
||||
f := &feedRemoteFake{star: true}
|
||||
if e := s.syncFeedActions(ctx, f.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e := s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
if e != nil || got.Status != "confirmed" || f.edits != 1 {
|
||||
t.Fatal(got, e, f.edits)
|
||||
}
|
||||
item, _ = s.store.FeedItem(ctx, domain, actor, v.UUID, "one")
|
||||
if !item.Read || !item.Starred {
|
||||
t.Fatal("unrelated star overwritten", item)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "POST", "remote-state", a); w.Code != 202 {
|
||||
t.Fatal("receipt replay", w.Code)
|
||||
}
|
||||
if e = s.syncFeedActions(ctx, f.client(t)); e != nil || f.edits != 1 {
|
||||
t.Fatal("replayed write", e, f.edits)
|
||||
}
|
||||
// A second explicit intent already satisfied remotely causes no edit-tag.
|
||||
a.RequestID = uuid.NewString()
|
||||
if _, e = s.store.QueueFeedAction(ctx, domain, actor, a); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.syncFeedActions(ctx, f.client(t)); e != nil || f.edits != 1 {
|
||||
t.Fatal("redundant write", e)
|
||||
}
|
||||
other, e := s.store.CreatePasswordAccount(domain, "actionother", "long test password", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if got, e = s.store.FeedAction(ctx, domain, other.UUID, v.UUID, "one"); e != nil || got != nil {
|
||||
t.Fatal("other owner receipt", got, e)
|
||||
}
|
||||
a.RequestID = uuid.NewString()
|
||||
if _, e = s.store.QueueFeedAction(ctx, domain, other.UUID, a); e == nil {
|
||||
t.Fatal("other owner mutation")
|
||||
}
|
||||
v.Credential = ""
|
||||
v.WriteEnabled = false
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, v); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
a.SourceVersion++
|
||||
if _, e = s.store.QueueFeedAction(ctx, domain, actor, a); e == nil {
|
||||
t.Fatal("opt-out ignored")
|
||||
}
|
||||
}
|
||||
func TestFeedActionUnknownNeverResendsAndReadOnlyRecheck(t *testing.T) {
|
||||
s, _, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
if _, e := s.store.QueueFeedAction(ctx, domain, actor, a); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
f := &feedRemoteFake{star: true, timeout: true}
|
||||
client := f.client(t)
|
||||
if e := s.syncFeedActions(ctx, client); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e := s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
if e != nil || got.Status != "unknown" {
|
||||
t.Fatal(got, e)
|
||||
}
|
||||
item, _ := s.store.FeedItem(ctx, domain, actor, v.UUID, "one")
|
||||
if item.Read {
|
||||
t.Fatal("unconfirmed cache")
|
||||
}
|
||||
requests := f.requests
|
||||
if e = s.syncFeedActions(ctx, client); e != nil || f.requests != requests {
|
||||
t.Fatal("automatic retry", e)
|
||||
}
|
||||
if e = s.store.RecheckFeedAction(ctx, domain, actor, a.RequestID); e == nil {
|
||||
t.Fatal("must wait for claim expiry")
|
||||
}
|
||||
// Simulate the uncertainty cooldown without sleeping.
|
||||
v.Credential = ""
|
||||
v.WriteEnabled = false
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, v); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s.store.DB.Exec(`UPDATE feed_actions SET until_ms=0 WHERE request_id=?`, a.RequestID)
|
||||
if e = s.store.RecheckFeedAction(ctx, domain, actor, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.syncFeedActions(ctx, client); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e = s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
if e != nil || got.Status != "confirmed" || f.edits != 1 {
|
||||
t.Fatal("recheck sent a write", got, e, f.edits)
|
||||
}
|
||||
}
|
||||
func TestFeedActionConflictAndPostSendFence(t *testing.T) {
|
||||
for _, changed := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "remote_conflict", true: "source_changed"}[changed], func(t *testing.T) {
|
||||
s, _, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
if _, e := s.store.QueueFeedAction(ctx, domain, actor, a); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
f := &feedRemoteFake{star: true}
|
||||
f.afterEdit = func() {
|
||||
if changed {
|
||||
v.Credential = ""
|
||||
v.WriteEnabled = false
|
||||
if _, e := s.store.SaveFeedSource(ctx, domain, actor, v); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
} else {
|
||||
f.read = false
|
||||
}
|
||||
}
|
||||
if e := s.syncFeedActions(ctx, f.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e := s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
want := "conflict"
|
||||
if changed {
|
||||
want = "unknown"
|
||||
}
|
||||
if e != nil || got.Status != want || f.edits != 1 {
|
||||
t.Fatal(got, e)
|
||||
}
|
||||
item, e := s.store.FeedItem(ctx, domain, actor, v.UUID, "one")
|
||||
if e != nil || item.Read {
|
||||
t.Fatal("unconfirmed/fenced value stored", item, e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedActionFencesAndRecovery(t *testing.T) {
|
||||
for _, scenario := range []string{"config", "delete", "readonly", "extension", "crash"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
s, _, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
if _, e := s.store.QueueFeedAction(ctx, domain, actor, a); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if scenario == "crash" {
|
||||
due, e := s.store.DueFeedActions(ctx)
|
||||
if e != nil || len(due) != 1 {
|
||||
t.Fatal(e)
|
||||
}
|
||||
a, source, e := s.store.ClaimFeedAction(ctx, due[0])
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.ClaimFeed(ctx, v); !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal("fetch overlapped mutation", e)
|
||||
}
|
||||
if e = s.store.MarkFeedActionSending(ctx, a, source); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s.store.DB.Exec(`UPDATE feed_actions SET until_ms=0 WHERE request_id=?`, a.RequestID)
|
||||
due, e = s.store.DueFeedActions(ctx)
|
||||
if e != nil || len(due) != 0 {
|
||||
t.Fatal("crash requeued", due, e)
|
||||
}
|
||||
got, _ := s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
if got.Status != "unknown" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
return
|
||||
}
|
||||
f := &feedRemoteFake{star: true}
|
||||
f.beforeEdit = func() {
|
||||
var e error
|
||||
switch scenario {
|
||||
case "config":
|
||||
v.Credential = ""
|
||||
v.WriteEnabled = false
|
||||
_, e = s.store.SaveFeedSource(ctx, domain, actor, v)
|
||||
case "delete":
|
||||
e = s.store.FeedSourceAction(ctx, domain, actor, v.UUID, "delete", v.Version)
|
||||
case "readonly":
|
||||
e = s.store.SetPrincipalState(domain, actor, "readonly")
|
||||
case "extension":
|
||||
e = s.setSystemExtensionEnabled(domain, "organizer.feeds", false)
|
||||
}
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if e := s.syncFeedActions(ctx, f.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if f.edits != 0 {
|
||||
t.Fatal("sent after revocation")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedActionSingleFieldAndConcurrentIntent(t *testing.T) {
|
||||
for _, field := range []string{"read", "starred"} {
|
||||
for _, desired := range []bool{false, true} {
|
||||
t.Run(field+map[bool]string{false: "_remove", true: "_add"}[desired], func(t *testing.T) {
|
||||
s, _, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
a.Field = field
|
||||
a.Desired = desired
|
||||
results := make(chan error, 2)
|
||||
for range 2 {
|
||||
go func() {
|
||||
copy := a
|
||||
copy.RequestID = uuid.NewString()
|
||||
_, e := s.store.QueueFeedAction(ctx, domain, actor, copy)
|
||||
results <- e
|
||||
}()
|
||||
}
|
||||
success := 0
|
||||
for range 2 {
|
||||
e := <-results
|
||||
if e == nil {
|
||||
success++
|
||||
} else if !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if success != 1 {
|
||||
t.Fatal("concurrent intents accepted", success)
|
||||
}
|
||||
f := &feedRemoteFake{read: true, star: true}
|
||||
if field == "read" {
|
||||
f.read = !desired
|
||||
} else {
|
||||
f.star = !desired
|
||||
}
|
||||
if e := s.syncFeedActions(ctx, f.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if f.edits != 1 {
|
||||
t.Fatal("wrong edit count", f.edits)
|
||||
}
|
||||
if field == "read" {
|
||||
if f.read != desired || !f.star {
|
||||
t.Fatal("wrong field changed")
|
||||
}
|
||||
} else {
|
||||
if f.star != desired || !f.read {
|
||||
t.Fatal("wrong field changed")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -328,11 +328,11 @@ 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, catalogs ...*[]store.FeedRemoteSubscription) ([]store.FeedItem, error) {
|
||||
func freshRSSLogin(ctx context.Context, client *http.Client, v store.FeedSource, user, password string) (string, 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 {
|
||||
return nil, e
|
||||
return "", e
|
||||
}
|
||||
auth := ""
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
@@ -341,12 +341,38 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
|
||||
}
|
||||
}
|
||||
if auth == "" || len(auth) > 4096 || strings.ContainsAny(auth, "\r\n") {
|
||||
return nil, errors.New("credentials")
|
||||
return "", errors.New("credentials")
|
||||
}
|
||||
raw, _, _, e = feedRequest(ctx, client, "GET", base+"/reader/api/0/stream/contents/reading-list?output=json&n=200", auth, nil, nil)
|
||||
return auth, nil
|
||||
}
|
||||
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, "/")
|
||||
auth, e := freshRSSLogin(ctx, client, v, user, password)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
raw, _, _, e := feedRequest(ctx, client, "GET", base+"/reader/api/0/stream/contents/reading-list?output=json&n=200", auth, nil, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
items, e := parseFreshRSSItems(raw, base)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
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 items, nil
|
||||
}
|
||||
func parseFreshRSSItems(raw []byte, base string) ([]store.FeedItem, error) {
|
||||
var response struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
@@ -411,17 +437,6 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -465,6 +480,9 @@ func (s *Server) syncFeedSources(ctx context.Context, job *store.EventJob) error
|
||||
func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.EventJob, client *http.Client) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
defer cancel()
|
||||
if e := s.syncFeedActions(ctx, client); e != nil {
|
||||
return e
|
||||
}
|
||||
sources, e := s.store.DueFeedSources(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
@@ -474,6 +492,9 @@ func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.Event
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < 9*time.Second {
|
||||
break
|
||||
}
|
||||
if !s.systemExtensionEnabled(v.Domain, "organizer.feeds") {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func writeFeedHistoryJSON(w http.ResponseWriter, value any) {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func (s *Server) handleFeedHistory(w http.ResponseWriter, r *http.Request, domain, actor, key string) bool {
|
||||
if r.Method != "GET" || (key != "actions" && key != "action/export") {
|
||||
return false
|
||||
}
|
||||
if key == "action/export" {
|
||||
a, e := s.store.FeedActionRecord(r.Context(), domain, actor, r.URL.Query().Get("request_id"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
id, _ := uuid.Parse(a.RequestID)
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="pageswiki-feed-action-`+id.String()+`.json"`)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
writeFeedHistoryJSON(w, map[string]any{"format": "pageswiki.feed-action", "version": 1, "exported_ms": time.Now().UnixMilli(), "domain_uuid": domain, "owner_uuid": actor, "action": a})
|
||||
return true
|
||||
}
|
||||
q := r.URL.Query()
|
||||
query := store.FeedActionQuery{Source: q.Get("source"), Status: q.Get("status"), Before: -1, Key: q.Get("key")}
|
||||
if q.Has("before") {
|
||||
var e error
|
||||
query.Before, e = strconv.ParseInt(q.Get("before"), 10, 64)
|
||||
if e != nil || query.Before < 0 {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return true
|
||||
}
|
||||
}
|
||||
items, e := s.store.FeedActionHistory(r.Context(), domain, actor, query)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
more := len(items) > 50
|
||||
if more {
|
||||
items = items[:50]
|
||||
}
|
||||
writeFeedHistoryJSON(w, map[string]any{"actions": items, "more": more})
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func feedHistoryResponse(t *testing.T, s *Server, token, query string) ([]store.FeedActionRecord, bool) {
|
||||
t.Helper()
|
||||
w := feedRequestTest(s, token, "GET", "actions"+query, nil)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w.Header().Get("Cache-Control") != "private, no-store" {
|
||||
t.Fatal("private response cache policy")
|
||||
}
|
||||
var data struct {
|
||||
Actions []store.FeedActionRecord `json:"actions"`
|
||||
More bool `json:"more"`
|
||||
}
|
||||
if e := json.Unmarshal(w.Body.Bytes(), &data); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return data.Actions, data.More
|
||||
}
|
||||
|
||||
func TestFeedHistoryOrphansExportAndRecheck(t *testing.T) {
|
||||
s, token, domain, actor, source := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a, e := s.store.QueueFeedAction(ctx, domain, actor, newFeedAction(source))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
queued, _ := feedHistoryResponse(t, s, token, "?status=pending")
|
||||
if len(queued) != 1 || queued[0].Status != "queued" || queued[0].CanCheck {
|
||||
t.Fatal("queued history", queued)
|
||||
}
|
||||
fake := &feedRemoteFake{timeout: true}
|
||||
if e = s.syncFeedActions(ctx, fake.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ := feedHistoryResponse(t, s, token, "")
|
||||
if len(list) != 1 || list[0].Status != "unknown" || list[0].CanCheck || list[0].CheckAfterMS <= time.Now().UnixMilli() || !list[0].ItemPresent || !list[0].SourcePresent {
|
||||
t.Fatal("unknown cooldown", list)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`DELETE FROM feed_items WHERE source_uuid=?`, source.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_actions SET until_ms=0 WHERE request_id=?`, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Read-only connector opt-out does not disable read-only result checks.
|
||||
source.Credential, source.WriteEnabled = "", false
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "?status=unknown")
|
||||
if len(list) != 1 || list[0].ItemPresent || !list[0].CanCheck || list[0].ItemTitle != "" || list[0].SourceTitle != "Remote" {
|
||||
t.Fatal("evicted item lost", list)
|
||||
}
|
||||
w := feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Header().Get("Content-Disposition"), a.RequestID+".json") || w.Header().Get("X-Content-Type-Options") != "nosniff" {
|
||||
t.Fatal("export", w.Code, w.Header())
|
||||
}
|
||||
var exported struct {
|
||||
Format string `json:"format"`
|
||||
Action store.FeedActionRecord `json:"action"`
|
||||
}
|
||||
if e = json.Unmarshal(w.Body.Bytes(), &exported); e != nil || exported.Format != "pageswiki.feed-action" || exported.Action.RequestID != a.RequestID || exported.Action.Status != "unknown" {
|
||||
t.Fatal("export data", exported, e)
|
||||
}
|
||||
for _, secret := range []string{"credential", "secret", source.URL, `"claim"`, `"until_ms"`} {
|
||||
if strings.Contains(w.Body.String(), secret) {
|
||||
t.Fatal("export leaked internal credentials or worker metadata", secret)
|
||||
}
|
||||
}
|
||||
if w = feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 202 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if e = s.syncFeedActions(ctx, fake.client(t)); e != nil || fake.edits != 1 {
|
||||
t.Fatal("recheck sent a second mutation", fake.edits, e)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "")
|
||||
if len(list) != 0 {
|
||||
t.Fatal("confirmed action unresolved", list)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "?status=confirmed")
|
||||
if len(list) != 1 || list[0].Status != "confirmed" || list[0].ItemPresent {
|
||||
t.Fatal("evicted receipt missing", list)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='unknown' WHERE request_id=?`, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`DELETE FROM feed_sources WHERE uuid=?`, source.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "?source="+source.UUID)
|
||||
if len(list) != 1 || list[0].SourcePresent || list[0].ItemPresent || list[0].CanCheck || list[0].Error != "source_deleted" {
|
||||
t.Fatal("deleted source receipt lost", list)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 412 {
|
||||
t.Fatal("deleted source recheck accepted", w.Code)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil); w.Code != 200 {
|
||||
t.Fatal("deleted source export", w.Code)
|
||||
}
|
||||
source.Version, source.Credential = 0, ""
|
||||
source.URL = "https://different.example.org/api/greader.php"
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal("rebound orphan receipt", e)
|
||||
}
|
||||
other, e := s.store.CreatePasswordAccount(domain, "historyreuse", "long test password", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, other.UUID, source); !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal("rebound unresolved receipt across owners", e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='confirmed' WHERE request_id=?`, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal("rebound terminal receipt", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedHistoryPaginationValidationAndIsolation(t *testing.T) {
|
||||
s, token, domain, actor, source := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
// Same millisecond, stable unique tie-breaker; well above a page boundary.
|
||||
for i := 0; i < 107; i++ {
|
||||
if _, e := s.store.DB.Exec(`INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES(?,?,?,?,?,'read',1,1,'confirmed',1234)`, domain, actor, uuid.NewString(), source.UUID, fmt.Sprint(i)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
query, seen := "?status=all", map[string]bool{}
|
||||
for {
|
||||
list, more := feedHistoryResponse(t, s, token, query)
|
||||
if len(list) > 50 {
|
||||
t.Fatal("unbounded list")
|
||||
}
|
||||
for _, a := range list {
|
||||
if seen[a.RequestID] {
|
||||
t.Fatal("duplicate cursor record")
|
||||
}
|
||||
seen[a.RequestID] = true
|
||||
}
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
last := list[len(list)-1]
|
||||
query = fmt.Sprintf("?status=all&before=%d&key=%s", last.CreatedMS, last.RequestID)
|
||||
}
|
||||
if len(seen) != 107 {
|
||||
t.Fatal("cursor omissions", len(seen))
|
||||
}
|
||||
for _, query := range []string{"?status=bogus", "?source=bad", "?before=bad", "?before=-1", "?before=1", "?key=" + uuid.NewString(), "?before=1&key=bad"} {
|
||||
if w := feedRequestTest(s, token, "GET", "actions"+query, nil); w.Code != 422 {
|
||||
t.Fatal("invalid query", query, w.Code)
|
||||
}
|
||||
}
|
||||
other, e := s.store.CreatePasswordAccount(domain, "historyother", "long test password", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
otherToken, e := s.store.CreateAuthSession(domain, other.UUID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
otherList, _ := feedHistoryResponse(t, s, otherToken, "?status=all&source="+source.UUID)
|
||||
if len(otherList) != 0 {
|
||||
t.Fatal("other owner's HTTP history leaked")
|
||||
}
|
||||
list, e := s.store.FeedActionHistory(ctx, domain, other.UUID, store.FeedActionQuery{Source: source.UUID, Status: "all", Before: -1})
|
||||
if e != nil || len(list) != 0 {
|
||||
t.Fatal("other owner's actions leaked", list, e)
|
||||
}
|
||||
for request := range seen {
|
||||
if w := feedRequestTest(s, otherToken, "GET", "action/export?request_id="+request, nil); w.Code != 404 {
|
||||
t.Fatal("other owner's HTTP export", w.Code)
|
||||
}
|
||||
if _, e = s.store.FeedActionRecord(ctx, domain, other.UUID, request); !errors.Is(e, sql.ErrNoRows) {
|
||||
t.Fatal("other owner's receipt leaked", e)
|
||||
}
|
||||
break
|
||||
}
|
||||
if _, e = s.store.FeedActionHistory(ctx, uuid.NewString(), actor, store.FeedActionQuery{Status: "all", Before: -1}); !errors.Is(e, store.ErrAccessDenied) {
|
||||
t.Fatal("other domain", e)
|
||||
}
|
||||
for _, key := range []string{"actions", "action/export?request_id=" + uuid.NewString()} {
|
||||
if w := feedRequestTest(s, "", "GET", key, nil); w.Code != 401 {
|
||||
t.Fatal("anonymous access", w.Code)
|
||||
}
|
||||
}
|
||||
if w := feedRequestTest(s, token, "GET", "action/export?request_id=invalid", nil); w.Code != 422 {
|
||||
t.Fatal("invalid receipt identifier", w.Code)
|
||||
}
|
||||
if e = s.setSystemExtensionEnabled(domain, "organizer.feeds", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if w := feedRequestTest(s, token, "GET", "actions", nil); w.Code != 404 {
|
||||
t.Fatal("extension disabled", w.Code)
|
||||
}
|
||||
if _, e = s.store.FeedActionRecord(ctx, domain, actor, uuid.NewString()); !errors.Is(e, store.ErrAccessDenied) {
|
||||
t.Fatal("store disabled", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedHistoryReadonlyAndSourceDisabled(t *testing.T) {
|
||||
s, token, domain, actor, source := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a, e := s.store.QueueFeedAction(ctx, domain, actor, newFeedAction(source))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='unknown',until_ms=0 WHERE request_id=?`, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.store.SetPrincipalState(domain, actor, "readonly"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
token, e = s.store.CreateAuthSession(domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ := feedHistoryResponse(t, s, token, "")
|
||||
if len(list) != 1 || list[0].CanCheck {
|
||||
t.Fatal("readonly check permission", list)
|
||||
}
|
||||
if w := feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 403 {
|
||||
t.Fatal("readonly mutation", w.Code)
|
||||
}
|
||||
if w := feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil); w.Code != 200 {
|
||||
t.Fatal("readonly export", w.Code)
|
||||
}
|
||||
if e = s.store.SetPrincipalState(domain, actor, "active"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
token, e = s.store.CreateAuthSession(domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
source.Credential, source.Enabled = "", false
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "")
|
||||
if len(list) != 1 || list[0].CanCheck || !list[0].SourcePresent {
|
||||
t.Fatal("disabled source recheck", list)
|
||||
}
|
||||
}
|
||||
@@ -543,7 +543,12 @@ func TestFeedsChromium(t *testing.T) {
|
||||
if e = s.store.CompleteFeed(context.Background(), claim, items, "", "", "", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
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})
|
||||
fresh := store.FeedSource{UUID: uuid.NewString(), Provider: "freshrss", Title: "FreshRSS fixture", URL: "https://example.org/api/greader.php", Enabled: true, Interval: 300}
|
||||
fresh.Credential, e = s.store.SealFeedCredential(domain, actor, fresh.UUID, "fixture", "synthetic")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, e = s.store.SaveFeedSource(context.Background(), domain, actor, fresh)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
@@ -577,6 +582,37 @@ func TestFeedsChromium(t *testing.T) {
|
||||
web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
if r.URL.Path == "/fixture/run-feed-actions" && r.Method == "POST" {
|
||||
fake := &feedRemoteFake{id: "catalog-b"}
|
||||
if e := s.syncFeedActions(r.Context(), fake.client(t)); e != nil {
|
||||
http.Error(w, "test worker failed", 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/fixture/feed-history" && r.Method == "POST" {
|
||||
missing, orphan := uuid.NewString(), uuid.NewString()
|
||||
for _, entry := range []struct{ request, source, item string }{{missing, fresh.UUID, "history-evicted"}, {orphan, uuid.NewString(), `<img src=x onerror=alert(1)>`}} {
|
||||
if _, e := s.store.DB.Exec(`INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES(?,?,?,?,?,'read',1,1,'unknown',?)`, domain, actor, entry.request, entry.source, entry.item, time.Now().UnixMilli()); e != nil {
|
||||
t.Error(e)
|
||||
http.Error(w, "fixture insert failed", 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]string{"missing": missing, "orphan": orphan})
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/fixture/check-feed-history" && r.Method == "POST" {
|
||||
fake := &feedRemoteFake{id: "history-evicted", read: true}
|
||||
if e := s.syncFeedActions(r.Context(), fake.client(t)); e != nil || fake.edits != 0 {
|
||||
t.Errorf("history read-only check: %v edits=%d", e, fake.edits)
|
||||
http.Error(w, "test recheck failed", 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/fixture" {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
fmt.Fprint(w, "<!doctype html><body style='margin:0'><script>"+string(script)+"</script></body>")
|
||||
@@ -586,6 +622,12 @@ func TestFeedsChromium(t *testing.T) {
|
||||
}))
|
||||
defer web.Close()
|
||||
for _, width := range []string{"1440", "390"} {
|
||||
if _, e = s.store.DB.Exec(`DELETE FROM feed_actions`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_items SET is_read=0 WHERE source_uuid=?`, fresh.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
args := []string{"internal/server/testdata/vim-browser-smoke.mjs", web.URL + "/fixture?width=" + url.QueryEscape(width), t.TempDir(), "/tmp/pageswiki-feeds-" + width + ".png", width, "850"}
|
||||
out, e := exec.CommandContext(ctx, "node", args...).CombinedOutput()
|
||||
|
||||
Vendored
+20
-2
@@ -33,7 +33,25 @@
|
||||
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';
|
||||
[...d.querySelectorAll('.feed-source')].find(n=>n.textContent.includes('FreshRSS fixture')).querySelector('button:last-child').click();await wait(()=>d.querySelector('#feed-reader form'));
|
||||
const setting=d.querySelector('#feed-reader form');setting.querySelectorAll('input[type=checkbox]')[1].checked=true;setting.requestSubmit();await wait(()=>!d.querySelector('#feed-reader form')&&d.querySelectorAll('.feed-row').length===1);
|
||||
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')&&!d.querySelectorAll('#feed-reader .feed-actions button')[1].disabled);
|
||||
d.querySelectorAll('#feed-reader .feed-actions button')[1].click();await wait(()=>d.querySelector('.feed-action-status')?.textContent==='◷');assert(d.querySelector('.feed-row').classList.contains('unread'),'Queued state shown as confirmed');
|
||||
const run=await w.fetch('/fixture/run-feed-actions',{method:'POST'});assert(run.status===204,'Background worker failed');await wait(()=>d.querySelector('.feed-action-status')?.textContent==='✓');assert(!d.querySelector('.feed-row').classList.contains('unread'),'Confirmed state not reflected');
|
||||
// Restore the synthetic source to read-only for the second viewport run.
|
||||
const api='/_/api/v1/extension/organizer.feeds/',source=(await (await w.fetch(api+'sources')).json()).sources.find(s=>s.title==='FreshRSS fixture');
|
||||
await w.fetch(api+'sources',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({uuid:source.uuid,version:source.version,provider:source.provider,title:source.title,folder:source.folder,url:source.url,interval_seconds:source.interval_seconds,enabled:true,write_enabled:false})});
|
||||
const seed=await (await w.fetch('/fixture/feed-history',{method:'POST'})).json();
|
||||
d.getElementById('feed-history').click();await wait(()=>d.querySelectorAll('#feed-history-panel tbody tr').length===2);
|
||||
const receipt=id=>d.querySelector('#feed-history-panel tr[data-request-id="'+id+'"]');
|
||||
assert(d.querySelector('.feed-layout').classList.contains('action-history'),'History full panel');assert(!receipt(seed.missing).querySelector('.feed-history-check').disabled,'Evicted item check unavailable');assert(receipt(seed.orphan).querySelector('.feed-history-check').disabled,'Deleted source check available');assert(!receipt(seed.orphan).querySelector('img'),'Untrusted ID rendered as HTML');
|
||||
const exported=await (await w.fetch(receipt(seed.orphan).querySelector('.feed-history-export').href)).json();assert(exported.format==='pageswiki.feed-action'&&exported.action.request_id===seed.orphan&&!exported.action.source_present,'Orphan receipt export');
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'History overflow');
|
||||
receipt(seed.missing).querySelector('.feed-history-check').click();await wait(()=>receipt(seed.missing)?.querySelector('[data-state=check_queued]'));
|
||||
assert((await w.fetch('/fixture/check-feed-history',{method:'POST'})).status===204,'Recheck worker failed');d.getElementById('feed-history-reload').click();await wait(()=>!receipt(seed.missing)&&receipt(seed.orphan));
|
||||
const hs=d.getElementById('feed-history-state');hs.value='all';hs.dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]'));
|
||||
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));assert(!d.querySelector('.feed-layout').classList.contains('action-history'),'History escape');
|
||||
d.getElementById('feed-history').click();await wait(()=>receipt(seed.orphan));d.getElementById('feed-history-state').value='all';d.getElementById('feed-history-state').dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]'));
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'History final overflow');document.body.dataset.vimReady='1';
|
||||
}catch(e){const out=document.createElement('pre');out.id='error';out.textContent=e.stack;document.body.append(out);}
|
||||
})();
|
||||
+48
-23
@@ -44,6 +44,16 @@ var feedMigrations = []db.SQLMigration{{Version: 1, Name: "private_feed_reader",
|
||||
`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")},
|
||||
}, {
|
||||
Version: 5, Name: "feed_explicit_remote_actions", Statements: []string{
|
||||
`ALTER TABLE feed_sources ADD COLUMN write_enabled INTEGER NOT NULL DEFAULT 0`,
|
||||
`CREATE TABLE feed_actions(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,request_id TEXT NOT NULL,source_uuid TEXT NOT NULL,item_id TEXT NOT NULL,field TEXT NOT NULL,desired INTEGER NOT NULL,source_version INTEGER NOT NULL,status TEXT NOT NULL,claim TEXT NOT NULL DEFAULT '',until_ms INTEGER NOT NULL DEFAULT 0,created_ms INTEGER NOT NULL,error TEXT NOT NULL DEFAULT '',PRIMARY KEY(domain_uuid,owner_uuid,request_id))`,
|
||||
`CREATE INDEX feed_actions_due ON feed_actions(status,created_ms)`,
|
||||
`CREATE INDEX feed_actions_item ON feed_actions(domain_uuid,owner_uuid,source_uuid,item_id,created_ms DESC)`,
|
||||
`CREATE UNIQUE INDEX feed_actions_active ON feed_actions(source_uuid,item_id) WHERE status IN ('queued','preparing','sending','unknown','check_queued','checking')`,
|
||||
`CREATE TRIGGER feed_actions_source_change AFTER UPDATE OF version ON feed_sources BEGIN UPDATE feed_actions SET status=CASE WHEN status IN ('sending','unknown','check_queued','checking') THEN 'unknown' ELSE 'cancelled' END,error='source_changed' WHERE source_uuid=old.uuid AND status IN ('queued','preparing','sending','unknown','check_queued','checking'); END`,
|
||||
`CREATE TRIGGER feed_actions_source_delete AFTER DELETE ON feed_sources BEGIN UPDATE feed_actions SET status=CASE WHEN status IN ('sending','unknown','check_queued','checking') THEN 'unknown' ELSE 'cancelled' END,error='source_deleted' WHERE source_uuid=old.uuid AND status IN ('queued','preparing','sending','unknown','check_queued','checking'); END`,
|
||||
}, Assertions: []string{schemaColumns("feed_sources", "write_enabled"), schemaUnique("feed_actions", "domain_uuid,owner_uuid,request_id")},
|
||||
}}
|
||||
|
||||
// CaptureFeedNote creates an inert Wiki note and receipt atomically. It does not
|
||||
@@ -111,24 +121,25 @@ func (s *Store) CaptureFeedNote(ctx context.Context, domain, owner, request, sou
|
||||
}
|
||||
|
||||
type FeedSource struct {
|
||||
UUID string `json:"uuid"`
|
||||
Domain string `json:"-"`
|
||||
Owner string `json:"-"`
|
||||
Provider string `json:"provider"`
|
||||
Title string `json:"title"`
|
||||
Folder string `json:"folder"`
|
||||
URL string `json:"url"`
|
||||
Credential string `json:"-"`
|
||||
Version int64 `json:"version"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Interval int `json:"interval_seconds"`
|
||||
NextMS int64 `json:"next_ms"`
|
||||
Lease string `json:"-"`
|
||||
LeaseUntil int64 `json:"-"`
|
||||
LastMS int64 `json:"last_ms"`
|
||||
Error string `json:"error"`
|
||||
ETag string `json:"-"`
|
||||
Modified string `json:"-"`
|
||||
UUID string `json:"uuid"`
|
||||
Domain string `json:"-"`
|
||||
Owner string `json:"-"`
|
||||
Provider string `json:"provider"`
|
||||
Title string `json:"title"`
|
||||
Folder string `json:"folder"`
|
||||
URL string `json:"url"`
|
||||
Credential string `json:"-"`
|
||||
Version int64 `json:"version"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Interval int `json:"interval_seconds"`
|
||||
NextMS int64 `json:"next_ms"`
|
||||
Lease string `json:"-"`
|
||||
LeaseUntil int64 `json:"-"`
|
||||
LastMS int64 `json:"last_ms"`
|
||||
Error string `json:"error"`
|
||||
ETag string `json:"-"`
|
||||
Modified string `json:"-"`
|
||||
WriteEnabled bool `json:"write_enabled"`
|
||||
}
|
||||
type FeedItem struct {
|
||||
Source string `json:"source"`
|
||||
@@ -148,10 +159,10 @@ type FeedItem struct {
|
||||
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`
|
||||
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,write_enabled`
|
||||
|
||||
func scanFeedSource(row interface{ Scan(...any) error }) (v FeedSource, e error) {
|
||||
e = row.Scan(&v.UUID, &v.Domain, &v.Owner, &v.Provider, &v.Title, &v.Folder, &v.URL, &v.Credential, &v.Version, &v.Enabled, &v.Interval, &v.NextMS, &v.Lease, &v.LeaseUntil, &v.LastMS, &v.Error, &v.ETag, &v.Modified)
|
||||
e = row.Scan(&v.UUID, &v.Domain, &v.Owner, &v.Provider, &v.Title, &v.Folder, &v.URL, &v.Credential, &v.Version, &v.Enabled, &v.Interval, &v.NextMS, &v.Lease, &v.LeaseUntil, &v.LastMS, &v.Error, &v.ETag, &v.Modified, &v.WriteEnabled)
|
||||
return
|
||||
}
|
||||
func feedActor(ctx context.Context, q interface {
|
||||
@@ -216,6 +227,9 @@ func (s *Store) FeedSources(ctx context.Context, domain, owner string) ([]FeedSo
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v FeedSource) (FeedSource, error) {
|
||||
if v.WriteEnabled && v.Provider != "freshrss" {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
if _, e := uuid.Parse(v.UUID); e != nil {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
@@ -228,7 +242,7 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed
|
||||
if v.Version == 0 {
|
||||
old, lookup := scanFeedSource(tx.QueryRowContext(ctx, `SELECT `+feedSourceColumns+` FROM feed_sources WHERE uuid=?`, v.UUID))
|
||||
if lookup == nil {
|
||||
if old.Domain != domain || old.Owner != owner || old.Version != 1 || old.Provider != v.Provider || old.Title != v.Title || old.Folder != v.Folder || old.URL != v.URL || old.Interval != v.Interval || old.Enabled != v.Enabled {
|
||||
if old.Domain != domain || old.Owner != owner || old.Version != 1 || old.Provider != v.Provider || old.Title != v.Title || old.Folder != v.Folder || old.URL != v.URL || old.Interval != v.Interval || old.Enabled != v.Enabled || old.WriteEnabled != v.WriteEnabled {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
if old.Credential != v.Credential {
|
||||
@@ -249,6 +263,17 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed
|
||||
if !errors.Is(lookup, sql.ErrNoRows) {
|
||||
return lookup
|
||||
}
|
||||
// Do not rebind retained receipts to a different remote identity.
|
||||
// Both predicates use existing indexes: owner history and the global
|
||||
// partial index of unresolved operations. Other owners' terminal
|
||||
// receipts remain isolated by domain/owner in metadata lookups.
|
||||
var retired bool
|
||||
if e := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM feed_actions WHERE domain_uuid=? AND owner_uuid=? AND source_uuid=?) OR EXISTS(SELECT 1 FROM feed_actions WHERE source_uuid=? AND status IN ('queued','preparing','sending','unknown','check_queued','checking'))`, domain, owner, v.UUID, v.UUID).Scan(&retired); e != nil {
|
||||
return e
|
||||
}
|
||||
if retired {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
var n int
|
||||
if e := tx.QueryRowContext(ctx, `SELECT count(*) FROM feed_sources WHERE domain_uuid=? AND owner_uuid=?`, domain, owner).Scan(&n); e != nil {
|
||||
return e
|
||||
@@ -256,7 +281,7 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed
|
||||
if n >= 32 {
|
||||
return ErrTaskDAVLimit
|
||||
}
|
||||
_, e := tx.ExecContext(ctx, `INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,credential,version,enabled,interval_seconds) VALUES(?,?,?,?,?,?,?,?,1,?,?)`, v.UUID, domain, owner, v.Provider, v.Title, v.Folder, v.URL, v.Credential, v.Enabled, v.Interval)
|
||||
_, e := tx.ExecContext(ctx, `INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,credential,version,enabled,interval_seconds,write_enabled) VALUES(?,?,?,?,?,?,?,?,1,?,?,?)`, v.UUID, domain, owner, v.Provider, v.Title, v.Folder, v.URL, v.Credential, v.Enabled, v.Interval, v.WriteEnabled)
|
||||
return e
|
||||
}
|
||||
old, e := scanFeedSource(tx.QueryRowContext(ctx, `SELECT `+feedSourceColumns+` FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, v.UUID, domain, owner))
|
||||
@@ -267,7 +292,7 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed
|
||||
if old.Provider != v.Provider || old.URL != v.URL || v.Credential != "" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
result, e := tx.ExecContext(ctx, `UPDATE feed_sources SET title=?,folder=?,enabled=?,interval_seconds=?,version=version+1,next_ms=0,lease='',lease_until=0 WHERE uuid=? AND version=?`, v.Title, v.Folder, v.Enabled, v.Interval, v.UUID, v.Version)
|
||||
result, e := tx.ExecContext(ctx, `UPDATE feed_sources SET title=?,folder=?,enabled=?,interval_seconds=?,write_enabled=?,version=version+1,next_ms=0,lease='',lease_until=0 WHERE uuid=? AND version=?`, v.Title, v.Folder, v.Enabled, v.Interval, v.WriteEnabled, v.UUID, v.Version)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type FeedAction struct {
|
||||
Domain string `json:"-"`
|
||||
Owner string `json:"-"`
|
||||
RequestID string `json:"request_id"`
|
||||
Source string `json:"source"`
|
||||
ID string `json:"id"`
|
||||
Field string `json:"field"`
|
||||
Desired bool `json:"desired"`
|
||||
SourceVersion int64 `json:"source_version"`
|
||||
Status string `json:"status"`
|
||||
Claim string `json:"-"`
|
||||
UntilMS int64 `json:"-"`
|
||||
CreatedMS int64 `json:"created_ms"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
const feedActionColumns = `domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,claim,until_ms,created_ms,error`
|
||||
|
||||
func scanFeedAction(row interface{ Scan(...any) error }) (a FeedAction, e error) {
|
||||
e = row.Scan(&a.Domain, &a.Owner, &a.RequestID, &a.Source, &a.ID, &a.Field, &a.Desired, &a.SourceVersion, &a.Status, &a.Claim, &a.UntilMS, &a.CreatedMS, &a.Error)
|
||||
return
|
||||
}
|
||||
func (s *Store) FeedAction(ctx context.Context, domain, owner, source, id string) (*FeedAction, error) {
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
a, e := scanFeedAction(s.DB.QueryRowContext(ctx, `SELECT `+feedActionColumns+` FROM feed_actions WHERE domain_uuid=? AND owner_uuid=? AND source_uuid=? AND item_id=? ORDER BY created_ms DESC,rowid DESC LIMIT 1`, domain, owner, source, id))
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return &a, e
|
||||
}
|
||||
func (s *Store) QueueFeedAction(ctx context.Context, domain, owner string, a FeedAction) (FeedAction, error) {
|
||||
if _, e := uuid.Parse(a.RequestID); e != nil {
|
||||
return a, ErrTaskInvalid
|
||||
}
|
||||
if (a.Field != "read" && a.Field != "starred") || a.ID == "" || len(a.ID) > 1024 {
|
||||
return a, ErrTaskInvalid
|
||||
}
|
||||
a.Domain, a.Owner = domain, owner
|
||||
a.Error, a.Claim, a.UntilMS = "", "", 0
|
||||
e := s.feedWrite(ctx, domain, owner, func(tx *sql.Tx) error {
|
||||
old, e := scanFeedAction(tx.QueryRowContext(ctx, `SELECT `+feedActionColumns+` FROM feed_actions WHERE domain_uuid=? AND owner_uuid=? AND request_id=?`, domain, owner, a.RequestID))
|
||||
if e == nil {
|
||||
if old.Source != a.Source || old.ID != a.ID || old.Field != a.Field || old.Desired != a.Desired || old.SourceVersion != a.SourceVersion {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
a = old
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(e, sql.ErrNoRows) {
|
||||
return e
|
||||
}
|
||||
var allowed bool
|
||||
if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM feed_sources s JOIN feed_items i ON i.source_uuid=s.uuid WHERE s.domain_uuid=? AND s.owner_uuid=? AND s.uuid=? AND i.id=? AND s.provider='freshrss' AND s.enabled=1 AND s.write_enabled=1 AND s.version=?)`, domain, owner, a.Source, a.ID, a.SourceVersion).Scan(&allowed); e != nil {
|
||||
return e
|
||||
}
|
||||
if !allowed {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
var total, pending int
|
||||
if e = tx.QueryRowContext(ctx, `SELECT count(*),COALESCE(sum(status IN ('queued','preparing','sending','unknown','check_queued','checking')),0) FROM feed_actions WHERE domain_uuid=? AND owner_uuid=?`, domain, owner).Scan(&total, &pending); e != nil {
|
||||
return e
|
||||
}
|
||||
if total >= 10000 || pending >= 20 {
|
||||
return ErrTaskDAVLimit
|
||||
}
|
||||
if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM feed_actions WHERE source_uuid=? AND item_id=? AND status IN ('queued','preparing','sending','unknown','check_queued','checking'))`, a.Source, a.ID).Scan(&allowed); e != nil {
|
||||
return e
|
||||
}
|
||||
if allowed {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
a.Status, a.CreatedMS = "queued", time.Now().UnixMilli()
|
||||
_, e = tx.ExecContext(ctx, `INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES(?,?,?,?,?,?,?,?,?,?)`, domain, owner, a.RequestID, a.Source, a.ID, a.Field, a.Desired, a.SourceVersion, a.Status, a.CreatedMS)
|
||||
return e
|
||||
})
|
||||
return a, e
|
||||
}
|
||||
|
||||
// Recheck is deliberately read-only at the remote side, even with writeback OFF.
|
||||
func (s *Store) RecheckFeedAction(ctx context.Context, domain, owner, request string) error {
|
||||
return s.feedWrite(ctx, domain, owner, func(tx *sql.Tx) error {
|
||||
r, e := tx.ExecContext(ctx, `UPDATE feed_actions SET status='check_queued',error='' WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND status='unknown' AND until_ms<? AND EXISTS(SELECT 1 FROM feed_sources s WHERE s.uuid=feed_actions.source_uuid AND s.domain_uuid=feed_actions.domain_uuid AND s.owner_uuid=feed_actions.owner_uuid AND s.provider='freshrss' AND s.enabled=1)`, domain, owner, request, time.Now().UnixMilli())
|
||||
return feedActionAffected(r, e)
|
||||
})
|
||||
}
|
||||
func feedActionAffected(r sql.Result, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
n, e := r.RowsAffected()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) DueFeedActions(ctx context.Context) ([]FeedAction, error) {
|
||||
if s.ReadOnly {
|
||||
return nil, ErrReadOnly
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
// Recovery changes only our receipts, never retries an uncertain remote write.
|
||||
if _, e := s.DB.ExecContext(ctx, `UPDATE feed_actions SET status=CASE WHEN status IN ('sending','checking') THEN 'unknown' ELSE 'failed' END,error='expired' WHERE (status IN ('preparing','sending','checking') AND until_ms<?) OR (status='queued' AND created_ms<?)`, now, now-300000); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
rows, e := s.DB.QueryContext(ctx, `SELECT `+feedActionColumns+` FROM feed_actions WHERE status IN ('queued','check_queued') AND EXISTS(SELECT 1 FROM feed_sources s JOIN principals p ON p.uuid=s.owner_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=s.domain_uuid JOIN domains d ON d.uuid=s.domain_uuid WHERE s.uuid=feed_actions.source_uuid AND s.enabled=1 AND s.lease_until<? AND p.state='active' AND m.state='active' AND d.enabled=1 AND COALESCE(d.placement,'local')='local' AND NOT EXISTS(SELECT 1 FROM config c WHERE c.domain_uuid=s.domain_uuid AND c.key='system_extension_states' AND COALESCE(json_extract(CASE WHEN json_valid(c.value) THEN c.value ELSE '{"organizer.feeds":false}' END,'$."organizer.feeds"'),1)=0)) ORDER BY created_ms LIMIT 2`, now)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []FeedAction{}
|
||||
for rows.Next() {
|
||||
a, e := scanFeedAction(rows)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) ClaimFeedAction(ctx context.Context, a FeedAction) (FeedAction, FeedSource, error) {
|
||||
var source FeedSource
|
||||
e := s.feedWrite(ctx, a.Domain, a.Owner, func(tx *sql.Tx) error {
|
||||
var e error
|
||||
source, e = scanFeedSource(tx.QueryRowContext(ctx, `SELECT `+feedSourceColumns+` FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, a.Source, a.Domain, a.Owner))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
check := a.Status == "check_queued"
|
||||
if !source.Enabled || source.Provider != "freshrss" || (!check && (!source.WriteEnabled || source.Version != a.SourceVersion)) {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
a.Claim = uuid.NewString()
|
||||
a.UntilMS = now + 60000
|
||||
state := "preparing"
|
||||
if check {
|
||||
state = "checking"
|
||||
}
|
||||
r, e := tx.ExecContext(ctx, `UPDATE feed_sources SET lease=?,lease_until=? WHERE uuid=? AND lease_until<?`, a.Claim, a.UntilMS, a.Source, now)
|
||||
if e = feedActionAffected(r, e); e != nil {
|
||||
return e
|
||||
}
|
||||
r, e = tx.ExecContext(ctx, `UPDATE feed_actions SET status=?,claim=?,until_ms=? WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND status=? AND (status='check_queued' OR created_ms>?)`, state, a.Claim, a.UntilMS, a.Domain, a.Owner, a.RequestID, a.Status, now-300000)
|
||||
if e = feedActionAffected(r, e); e != nil {
|
||||
return e
|
||||
}
|
||||
a.Status = state
|
||||
source.Lease = a.Claim
|
||||
source.LeaseUntil = a.UntilMS
|
||||
return nil
|
||||
})
|
||||
return a, source, e
|
||||
}
|
||||
func (s *Store) MarkFeedActionSending(ctx context.Context, a FeedAction, source FeedSource) error {
|
||||
return s.feedWrite(ctx, a.Domain, a.Owner, func(tx *sql.Tx) error {
|
||||
r, e := tx.ExecContext(ctx, `UPDATE feed_actions SET status='sending' WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND claim=? AND status='preparing' AND until_ms>? AND EXISTS(SELECT 1 FROM feed_sources WHERE uuid=? AND enabled=1 AND write_enabled=1 AND version=? AND lease=?)`, a.Domain, a.Owner, a.RequestID, a.Claim, time.Now().UnixMilli(), a.Source, source.Version, a.Claim)
|
||||
return feedActionAffected(r, e)
|
||||
})
|
||||
}
|
||||
func (s *Store) CompleteFeedAction(ctx context.Context, a FeedAction, source FeedSource, status, code string, observed *FeedItem) error {
|
||||
if (observed != nil && observed.ID != a.ID) || ((status == "confirmed" || status == "conflict") && observed == nil) {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
if status != "confirmed" && status != "unknown" && status != "failed" && status != "conflict" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
switch code {
|
||||
case "", "network", "credentials", "invalid_feed", "remote_error", "conflict", "limit":
|
||||
default:
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
return s.feedWrite(ctx, a.Domain, a.Owner, func(tx *sql.Tx) error {
|
||||
r, e := tx.ExecContext(ctx, `UPDATE feed_sources SET lease='',lease_until=0 WHERE uuid=? AND version=? AND lease=? AND lease_until>? AND enabled=1`, a.Source, source.Version, a.Claim, time.Now().UnixMilli())
|
||||
if e = feedActionAffected(r, e); e != nil {
|
||||
return e
|
||||
}
|
||||
r, e = tx.ExecContext(ctx, `UPDATE feed_actions SET status=?,error=?,until_ms=CASE WHEN ?='unknown' THEN until_ms ELSE 0 END WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND claim=? AND status IN ('preparing','sending','checking')`, status, code, status, a.Domain, a.Owner, a.RequestID, a.Claim)
|
||||
if e = feedActionAffected(r, e); e != nil {
|
||||
return e
|
||||
}
|
||||
if observed != nil {
|
||||
_, e = tx.ExecContext(ctx, `UPDATE feed_items SET is_read=?,starred=? WHERE source_uuid=? AND id=?`, observed.Read, observed.Starred, a.Source, a.ID)
|
||||
}
|
||||
return e
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// FeedActionRecord is a receipt plus currently available local metadata. A
|
||||
// deleted source or evicted article must not hide an unresolved remote write.
|
||||
type FeedActionRecord struct {
|
||||
FeedAction
|
||||
SourceTitle string `json:"source_title"`
|
||||
ItemTitle string `json:"item_title"`
|
||||
SourcePresent bool `json:"source_present"`
|
||||
ItemPresent bool `json:"item_present"`
|
||||
CanCheck bool `json:"can_check"`
|
||||
CheckAfterMS int64 `json:"check_after_ms"`
|
||||
}
|
||||
|
||||
type FeedActionQuery struct {
|
||||
Source string
|
||||
Status string
|
||||
Before int64
|
||||
Key string
|
||||
}
|
||||
|
||||
const feedActionMetadata = `,COALESCE(s.title,''),COALESCE(i.title,''),s.uuid IS NOT NULL,i.id IS NOT NULL,COALESCE(s.enabled=1 AND s.provider='freshrss',0)`
|
||||
const feedActionJoins = ` FROM feed_actions a LEFT JOIN feed_sources s ON s.uuid=a.source_uuid AND s.domain_uuid=a.domain_uuid AND s.owner_uuid=a.owner_uuid LEFT JOIN feed_items i ON i.source_uuid=s.uuid AND i.id=a.item_id WHERE a.domain_uuid=? AND a.owner_uuid=?`
|
||||
|
||||
func feedActionRecordColumns() string {
|
||||
return "a." + strings.ReplaceAll(feedActionColumns, ",", ",a.") + feedActionMetadata
|
||||
}
|
||||
|
||||
func scanFeedActionRecord(row interface{ Scan(...any) error }, writable bool) (a FeedActionRecord, e error) {
|
||||
var enabled bool
|
||||
e = row.Scan(&a.Domain, &a.Owner, &a.RequestID, &a.Source, &a.ID, &a.Field, &a.Desired, &a.SourceVersion, &a.Status, &a.Claim, &a.UntilMS, &a.CreatedMS, &a.Error, &a.SourceTitle, &a.ItemTitle, &a.SourcePresent, &a.ItemPresent, &enabled)
|
||||
if a.Status == "unknown" {
|
||||
a.CheckAfterMS = a.UntilMS
|
||||
a.CanCheck = writable && enabled && a.UntilMS < time.Now().UnixMilli()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// FeedActionHistory returns at most 51 local receipts (50 plus a next-page
|
||||
// sentinel). The owner cap of 10,000 receipts bounds the sorting work even
|
||||
// without a new schema/index. No fetch, retry, expiry or deletion runs here.
|
||||
func (s *Store) FeedActionHistory(ctx context.Context, domain, owner string, q FeedActionQuery) ([]FeedActionRecord, error) {
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
where := ""
|
||||
switch q.Status {
|
||||
case "", "unresolved":
|
||||
where = ` AND a.status NOT IN ('confirmed','cancelled')`
|
||||
case "all":
|
||||
case "pending":
|
||||
where = ` AND a.status IN ('queued','preparing','sending','check_queued','checking')`
|
||||
case "unknown", "confirmed", "failed", "conflict", "cancelled":
|
||||
where = ` AND a.status='` + q.Status + `'`
|
||||
default:
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
args := []any{domain, owner}
|
||||
if q.Source != "" {
|
||||
if _, e := uuid.Parse(q.Source); e != nil {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
where += ` AND a.source_uuid=?`
|
||||
args = append(args, q.Source)
|
||||
}
|
||||
if q.Before >= 0 {
|
||||
if _, e := uuid.Parse(q.Key); e != nil {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
where += ` AND (a.created_ms<? OR (a.created_ms=? AND a.request_id<?))`
|
||||
args = append(args, q.Before, q.Before, q.Key)
|
||||
} else if q.Before != -1 || q.Key != "" {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
writable := !s.ReadOnly && feedActor(ctx, s.DB, domain, owner, true) == nil
|
||||
rows, e := s.DB.QueryContext(ctx, `SELECT `+feedActionRecordColumns()+feedActionJoins+where+` ORDER BY a.created_ms DESC,a.request_id DESC LIMIT 51`, args...)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []FeedActionRecord{}
|
||||
for rows.Next() {
|
||||
a, e := scanFeedActionRecord(rows, writable)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) FeedActionRecord(ctx context.Context, domain, owner, request string) (FeedActionRecord, error) {
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return FeedActionRecord{}, e
|
||||
}
|
||||
if _, e := uuid.Parse(request); e != nil {
|
||||
return FeedActionRecord{}, ErrTaskInvalid
|
||||
}
|
||||
writable := !s.ReadOnly && feedActor(ctx, s.DB, domain, owner, true) == nil
|
||||
return scanFeedActionRecord(s.DB.QueryRowContext(ctx, `SELECT `+feedActionRecordColumns()+feedActionJoins+` AND a.request_id=?`, domain, owner, request), writable)
|
||||
}
|
||||
@@ -150,3 +150,41 @@ func TestFeedCatalogMigrationRollbackAndRepeat(t *testing.T) {
|
||||
t.Fatal(integrity, e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedActionsMigrationRollbackAndRepeat(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
ctx := context.Background()
|
||||
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", feedMigrations[:4]); 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) VALUES('s','d','u','freshrss','Title','','https://example.org',7,1,300)`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
broken := append([]db.SQLMigration(nil), feedMigrations...)
|
||||
broken[4].Statements = append(append([]string(nil), feedMigrations[4].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_sources') WHERE name='write_enabled'`).Scan(&count); e != nil || count != 0 {
|
||||
t.Fatal("partial schema", count, e)
|
||||
}
|
||||
for range 2 {
|
||||
if e := st.ensureSchemaComponent("feeds"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if e := st.DB.QueryRow(`SELECT write_enabled FROM feed_sources WHERE uuid='s'`).Scan(&count); e != nil || count != 0 {
|
||||
t.Fatal("write enabled during upgrade", count, e)
|
||||
}
|
||||
if _, e := st.DB.Exec(`INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES('d','u','r','s','i','read',1,7,'sending',1); DELETE FROM feed_sources WHERE uuid='s'`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var status string
|
||||
if e := st.DB.QueryRow(`SELECT status FROM feed_actions WHERE request_id='r'`).Scan(&status); e != nil || status != "unknown" {
|
||||
t.Fatal("lost uncertain receipt", status, e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`PRAGMA integrity_check`).Scan(&status); e != nil || status != "ok" {
|
||||
t.Fatal(status, e)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
.feeds-page{height:100dvh;overflow:hidden;display:flex;flex-direction:column;background:var(--bg);color:var(--fg)}
|
||||
.feed-layout.action-history{grid-template-columns:12rem minmax(0,1fr)}.feed-layout.action-history .feed-index{display:none}.feed-layout.action-history #feed-reader{display:block}.feed-history-controls{display:flex;gap:.3rem;flex-wrap:wrap;margin:.4rem 0}.feed-history-controls select{max-width:100%}.feed-history table{width:100%;table-layout:fixed;border-collapse:collapse;font-size:.8rem}.feed-history th,.feed-history td{padding:.3rem .4rem;text-align:left;border-bottom:1px solid var(--border,#8885);vertical-align:middle;overflow-wrap:anywhere}.feed-history th:first-child{width:7.5rem}.feed-history th:nth-child(3){width:6rem}.feed-history th:last-child{width:7rem}.feed-history td:nth-child(2)>span,.feed-history small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.feed-history small{font-size:.72rem;opacity:.7}.feed-history-buttons{display:flex;gap:.2rem;justify-content:flex-end}.feed-history-buttons a{display:inline-flex;align-items:center;justify-content:center;min-width:1.8rem;min-height:1.8rem;border:1px solid var(--border,#6666);border-radius:.2rem;text-decoration:none}.feed-history [data-state=unknown],.feed-history [data-state=conflict],.feed-history [data-state=failed]{color:var(--danger,#e57a7a)}.feed-history .feed-warning:empty{display:none}
|
||||
@media(max-width:1100px){.feed-layout.action-history{grid-template-columns:10rem minmax(0,1fr)}}
|
||||
@media(max-width:600px){.feed-history thead{display:none}.feed-history tbody,.feed-history tr{display:block}.feed-history tr{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.15rem .3rem;padding:.5rem 0;border-bottom:1px solid var(--border,#8885)}.feed-history td{display:block;border:0;padding:0 .2rem;min-width:0}.feed-history td:first-child{grid-column:1;grid-row:1;font-size:.7rem;opacity:.7}.feed-history td:nth-child(2){grid-column:1;grid-row:2}.feed-history td:nth-child(3){grid-column:1;grid-row:3;font-size:.75rem}.feed-history td:last-child{grid-column:2;grid-row:1/4;align-self:center}.feed-history-buttons a{min-width:2.3rem;min-height:2.3rem}}
|
||||
.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}
|
||||
|
||||
+49
-8
@@ -11,18 +11,26 @@
|
||||
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;
|
||||
let actionTimer;
|
||||
const pendingAction=a=>a&&['queued','preparing','sending','unknown','check_queued','checking'].includes(a.status);
|
||||
async function updateAction(item){const version=detailSeq;const data=await request('action?'+new URLSearchParams({source:item.source,id:item.id}));if(version!==detailSeq||items[selected]!==item||editing)return;item.action=data.action;item.actionLoading=false;
|
||||
if(data.action&&['confirmed','conflict'].includes(data.action.status)){const fresh=(await request('item?'+new URLSearchParams({source:item.source,id:item.id}))).item;if(version!==detailSeq||items[selected]!==item||editing)return;Object.assign(item,fresh);drawRows();}renderItem(item);
|
||||
}
|
||||
function pollAction(item){clearTimeout(actionTimer);if(document.hidden||!item.action||!['queued','preparing','sending','check_queued','checking'].includes(item.action.status))return;actionTimer=setTimeout(()=>{if(items[selected]===item&&!editing)updateAction(item).catch(report);},2000);}
|
||||
document.addEventListener('visibilitychange',()=>{if(document.hidden)clearTimeout(actionTimer);else{const item=items[selected];if(item?.provider==='freshrss'&&!editing)updateAction(item).catch(report);}});
|
||||
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;
|
||||
toolbar.append(button('☰',t('Sources','購読元'),()=>layout.classList.toggle('sources-open')),sourceLabel,searchbox,filters,refresh);
|
||||
if(writable)toolbar.append(button('+',t('Add source','購読元を追加'),()=>sourceForm()));
|
||||
const transfer=button('⇄','OPML',opmlForm);transfer.id='feed-opml';toolbar.append(transfer);
|
||||
const history=button('◷',t('Operation history','操作履歴'),actionHistory);history.id='feed-history';toolbar.append(history);
|
||||
toolbar.append(button('?',t('Keyboard shortcuts','キー操作'),showHelp));
|
||||
let debounce;searchbox.addEventListener('input',()=>{clearTimeout(debounce);debounce=setTimeout(()=>{search=searchbox.value.trim();load(false).catch(report);},180);});
|
||||
const columns=document.getElementById('feed-columns');for(const s of ['',t('Date','日付'),t('Feed','配信元'),t('Subject','件名')])columns.append(el('span',s));
|
||||
function showHelp(){status.textContent=t('j/k move · Enter read · Esc index · / search · n unread · m read/unread · * star · r refresh','j/k 移動 · Enter 本文 · Esc 一覧 · / 検索 · n 次の未読 · m 既読/未読 · * star · r 更新');}
|
||||
function date(ms){return ms?new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{month:'2-digit',day:'2-digit'}).format(new Date(ms)):'—';}
|
||||
function closeReader(){editing=false;detailSeq++;detailController?.abort();layout.classList.remove('reading');rows.focus();}
|
||||
function closeReader(){editing=false;detailSeq++;detailController?.abort();layout.classList.remove('reading','action-history');rows.focus();}
|
||||
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);
|
||||
@@ -48,7 +56,7 @@
|
||||
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,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='';
|
||||
if(!append){detailSeq++;items=[];selected=-1;reader.replaceChildren();layout.classList.remove('reading','action-history');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);
|
||||
@@ -56,21 +64,53 @@
|
||||
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'});
|
||||
layout.classList.add('reading');reader.replaceChildren(el('p',t('Loading…','読み込み中…')));const item=(await request('item?'+new URLSearchParams({source:items[index].source,id:items[index].id}),{signal:detailController.signal})).item;if(version!==detailSeq)return;items[index]=item;renderItem(item);
|
||||
layout.classList.remove('action-history');layout.classList.add('reading');reader.replaceChildren(el('p',t('Loading…','読み込み中…')));const item=(await request('item?'+new URLSearchParams({source:items[index].source,id:items[index].id}),{signal:detailController.signal})).item;if(version!==detailSeq)return;items[index]=item;if(item.provider==='freshrss'){item.actionLoading=true;renderItem(item);await updateAction(item);}else renderItem(item);
|
||||
}
|
||||
function renderItem(item){reader.replaceChildren();const actions=el('div',undefined,'feed-actions');actions.append(button('←',t('Back to list','一覧へ戻る'),closeReader));
|
||||
const read=button(item.read?'●':'○',t('Toggle read state (m)','既読/未読 (m)'),()=>setState(!item.read,item.starred));const star=button(item.starred?'★':'☆',t('Toggle star (*)','star切替 (*)'),()=>setState(item.read,!item.starred));read.disabled=star.disabled=!writable||item.provider!=='local';actions.append(read,star);
|
||||
const canWrite=item.provider==='local'||sources.some(s=>s.uuid===item.source&&s.enabled&&s.write_enabled);
|
||||
const read=button(item.read?'●':'○',t('Toggle read state (m)','既読/未読 (m)'),()=>setState(!item.read,item.starred));const star=button(item.starred?'★':'☆',t('Toggle star (*)','star切替 (*)'),()=>setState(item.read,!item.starred));read.disabled=star.disabled=!writable||!canWrite||item.actionLoading||pendingAction(item.action);actions.append(read,star);
|
||||
if(item.action){const a=item.action,labels={queued:t('Queued','送信待ち'),preparing:t('Checking','確認中'),sending:t('Sending','送信中'),checking:t('Rechecking','再確認中'),check_queued:t('Recheck queued','再確認待ち'),confirmed:t('Confirmed','確認済み'),unknown:t('Result unknown — recheck after one minute','結果不明 — 1分後に再確認'),conflict:t('Changed elsewhere — review before retrying','状態が一致しません。確認してから再操作してください'),failed:t('Not sent','未送信'),cancelled:t('Cancelled','中止')};const label=labels[a.status]||a.status;
|
||||
const state=button(a.status==='unknown'?'↻':pendingAction(a)?'◷':a.status==='confirmed'?'✓':'!',label,async()=>{if(a.status!=='unknown')return;await post('action/check',{request_id:a.request_id});await updateAction(item);});state.className='feed-action-status';state.disabled=a.status!=='unknown'||!writable;state.title+=(a.error?' · '+a.error:'');actions.append(state);}
|
||||
if(item.url){const a=el('a',undefined,'feed-original');a.title=a.ariaLabel=t('Open original','原文を開く');a.href=item.url;a.target='_blank';a.rel='noopener noreferrer';const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),path=document.createElementNS(svg.namespaceURI,'path');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');path.setAttribute('d','M14 3h7v7M21 3l-11 11M10 5H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5');svg.append(path);a.append(svg);actions.append(a);}
|
||||
if(writable)actions.append(button(t('+ Wiki / Task','+ Wiki・タスク'),t('Capture with attribution','出典付きで取り込む'),()=>captureForm(item)));
|
||||
reader.append(actions,el('h1',item.title||t('(Untitled)','(無題)')),el('p',(item.feed||'')+' · '+(item.published_ms?new Date(item.published_ms).toLocaleString():t('Date unknown','日付不明')),'feed-meta'));
|
||||
if(item.provider==='freshrss')read.title=star.title=t('FreshRSS · read only','FreshRSS · 読取専用');
|
||||
if(item.provider==='freshrss'&&!canWrite)read.title=star.title=t('FreshRSS · read only','FreshRSS · 読取専用');
|
||||
const body=el('div',undefined,'feed-body');
|
||||
if(item.body_html){body.classList.add('feed-body-html');const shadow=body.attachShadow({mode:'open'}),style=el('style',':host{display:block;overflow-wrap:anywhere;line-height:1.6}p{margin:.6em 0}h1,h2,h3{line-height:1.3}a{color:var(--link,var(--accent,#659de4))}pre{white-space:pre-wrap;overflow-wrap:anywhere;padding:.5em;background:color-mix(in srgb,currentColor 5%,transparent)}blockquote{margin:.5em 0;padding-left:1em;border-left:3px solid var(--border,#8885)}table{border-collapse:collapse;max-width:100%;display:block;overflow:auto}th,td{padding:.3em .6em;border:1px solid var(--border,#8885)}');const content=el('div');content.innerHTML=item.body_html;shadow.append(style,content);}
|
||||
else body.textContent=item.body||t('(No article text)','(本文なし)');
|
||||
reader.append(body);
|
||||
pollAction(item);
|
||||
}
|
||||
async function setState(read,starred){const item=items[selected];if(!item||!writable||item.provider!=='local')return;const source=item.source,id=item.id;const data=await post('state',{source,id,read,starred,version:item.version});Object.assign(item,{read,starred,version:data.version});drawRows();if(items[selected]===item&&!editing)renderItem(item);}
|
||||
async function setState(read,starred){const item=items[selected];if(!item||!writable||item.actionLoading||pendingAction(item.action))return;const source=item.source,id=item.id;
|
||||
if(item.provider==='freshrss'){const config=sources.find(s=>s.uuid===source);if(!config?.enabled||!config?.write_enabled)return;const field=read!==item.read?'read':'starred',desired=field==='read'?read:starred;if(item[field]===desired)return;item.actionLoading=true;renderItem(item);try{await post('remote-state',{request_id:crypto.randomUUID(),source,id,field,desired,source_version:config.version});}finally{await updateAction(item);}return;}
|
||||
const data=await post('state',{source,id,read,starred,version:item.version});Object.assign(item,{read,starred,version:data.version});drawRows();if(items[selected]===item&&!editing)renderItem(item);}
|
||||
function field(form,label,value='',type='text'){const wrap=el('label',label),input=el('input');input.type=type;input.value=value;wrap.append(input);form.append(wrap);return input;}
|
||||
function actionHistory(){
|
||||
editing=true;const version=++detailSeq;detailController?.abort();controller?.abort();seq++;loading=false;more.disabled=false;clearTimeout(actionTimer);layout.classList.add('reading','action-history');status.textContent='';reader.replaceChildren();
|
||||
const section=el('section',undefined,'feed-history'),heading=el('div',undefined,'feed-actions');section.id='feed-history-panel';reader.append(section);
|
||||
heading.append(button('←',t('Back to list','一覧へ戻る'),closeReader),el('h1',t('Operation history','操作履歴')));section.append(heading);
|
||||
const controls=el('div',undefined,'feed-history-controls'),states=el('select'),sourceFilter=el('select');states.id='feed-history-state';states.ariaLabel=t('Operation status','操作状態');sourceFilter.ariaLabel=t('Source','購読元');
|
||||
for(const [value,en,jp]of [['unresolved','Needs attention','未解決'],['pending','In progress','処理中'],['unknown','Result unknown','結果不明'],['all','All','すべて'],['confirmed','Confirmed','確認済み'],['failed','Not sent','未送信'],['conflict','Conflict','不一致'],['cancelled','Cancelled','中止']]){const o=el('option',t(en,jp));o.value=value;states.append(o);}
|
||||
for(const [value,label]of [['',t('All sources','すべての購読元')],...sources.filter(s=>s.provider==='freshrss').map(s=>[s.uuid,s.title])]){const o=el('option',label);o.value=value;sourceFilter.append(o);}
|
||||
const reloadHistory=button('↻',t('Reload history','履歴を再読込'),()=>fetchHistory(false));reloadHistory.id='feed-history-reload';controls.append(states,sourceFilter,reloadHistory);section.append(controls);
|
||||
const table=el('table'),head=el('thead'),headRow=el('tr'),body=el('tbody');for(const label of [t('Date','日時'),t('Article / operation','記事・操作'),t('Status','状態'),t('Actions','操作')]){const th=el('th',label);th.scope='col';headRow.append(th);}head.append(headRow);table.append(head,body);section.append(table);
|
||||
const empty=el('p',t('No operations','操作なし'),'feed-warning'),notice=el('p',undefined,'feed-warning'),nextPage=button('↓',t('More operations','続きを表示'),()=>fetchHistory(true));notice.role='status';empty.hidden=true;nextPage.hidden=true;section.append(empty,notice,nextPage);
|
||||
let cursor=null,generation=0,busy=false,abort;
|
||||
const labels={queued:t('Queued','送信待ち'),preparing:t('Checking','確認中'),sending:t('Sending','送信中'),check_queued:t('Recheck queued','再確認待ち'),checking:t('Rechecking','再確認中'),unknown:t('Result unknown','結果不明'),confirmed:t('Confirmed','確認済み'),failed:t('Not sent','未送信'),conflict:t('Conflict','不一致'),cancelled:t('Cancelled','中止')};
|
||||
const errors={network:t('Network error','通信エラー'),credentials:t('Authentication failed','認証失敗'),remote_error:t('Remote error','接続先エラー'),invalid_feed:t('Invalid response','応答不正'),limit:t('Limit exceeded','上限超過'),expired:t('Expired','期限切れ'),source_changed:t('Source settings changed','購読元設定が変更されました'),source_deleted:t('Source deleted','購読元削除済み'),conflict:t('Remote state differs','外部の状態が一致しません')};
|
||||
function row(a){const tr=el('tr');tr.dataset.requestId=a.request_id;const when=el('td',new Date(a.created_ms).toLocaleString(ja?'ja-JP':'en-GB',{month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit'})),subject=el('td'),state=el('td',labels[a.status]||a.status),actions=el('td');when.title=new Date(a.created_ms).toLocaleString();state.dataset.state=a.status;state.title=errors[a.error]||a.error||'';
|
||||
const title=a.item_title||a.id,name=a.source_title||a.source,operation=a.field==='read'?(a.desired?t('Read','既読'):t('Unread','未読')):(a.desired?t('Star','star追加'):t('Unstar','star解除'));
|
||||
const text=el('span',title);text.title=title;subject.append(text,el('small',name+' · '+operation));if(!a.source_present)subject.append(el('small',t('Source deleted','購読元削除済み')));else if(!a.item_present)subject.append(el('small',t('Outside article cache','記事キャッシュ外')));
|
||||
const tools=el('div',undefined,'feed-history-buttons');actions.append(tools);
|
||||
if(a.item_present){const view=button('↗',t('Read article','記事を読む'),async()=>{let index=items.findIndex(i=>i.source===a.source&&i.id===a.id);if(index<0){const data=await request('item?'+new URLSearchParams({source:a.source,id:a.id}));if(detailSeq!==version)return;items.unshift(data.item);index=0;drawRows();}await open(index);});tools.append(view);}
|
||||
if(a.status==='unknown'){const check=button('↻',t('Recheck remote state without resending','再送せず外部状態を再確認'),async()=>{check.disabled=true;try{await post('action/check',{request_id:a.request_id});await fetchHistory(false);}catch(e){notice.textContent=e.message;check.disabled=false;}});check.className='feed-history-check';check.disabled=!writable||!a.can_check;if(!a.source_present)check.title=t('Deleted source cannot be rechecked','削除した購読元は再確認できません');else if(a.check_after_ms>Date.now())check.title=t('Recheck after ','再確認可能時刻: ')+new Date(a.check_after_ms).toLocaleTimeString();else if(!a.can_check)check.title=t('Requires an enabled source and write permission','購読元の有効化と操作権限が必要です');tools.append(check);}
|
||||
const save=el('a','↓');save.className='feed-history-export';save.href=api+'action/export?'+new URLSearchParams({request_id:a.request_id});save.download='pageswiki-feed-action.json';save.title=save.ariaLabel=t('Save operation receipt (JSON)','操作記録を保存(JSON)');tools.append(save);tr.append(when,subject,state,actions);return tr;}
|
||||
async function fetchHistory(append){if(version!==detailSeq||!section.isConnected||append&&(busy||!cursor))return;abort?.abort();abort=new AbortController();const n=++generation;busy=true;nextPage.disabled=true;notice.textContent='';if(!append){cursor=null;nextPage.hidden=true;empty.hidden=true;body.replaceChildren();}
|
||||
try{const q=new URLSearchParams({status:states.value,source:sourceFilter.value});if(append){q.set('before',cursor.created_ms);q.set('key',cursor.request_id);}const data=await request('actions?'+q,{signal:abort.signal});if(n!==generation||version!==detailSeq||!section.isConnected)return;if(!append)body.replaceChildren();body.append(...data.actions.map(row));cursor=data.more?data.actions.at(-1):null;nextPage.hidden=!cursor;empty.hidden=body.children.length!==0;
|
||||
}catch(e){if(e.name!=='AbortError'&&n===generation&§ion.isConnected)notice.textContent=e.message;}finally{if(n===generation){busy=false;nextPage.disabled=false;}}
|
||||
}
|
||||
states.onchange=sourceFilter.onchange=()=>fetchHistory(false);fetchHistory(false);
|
||||
}
|
||||
function opmlForm(){
|
||||
editing=true;detailSeq++;detailController?.abort();layout.classList.add('reading');reader.replaceChildren();
|
||||
const section=el('section',undefined,'feed-opml'),heading=el('div',undefined,'feed-actions');heading.append(el('h1','OPML'),button('←',t('Back','戻る'),closeReader));section.append(heading);reader.append(section);
|
||||
@@ -105,11 +145,12 @@
|
||||
const user=field(form,t('FreshRSS user','FreshRSSユーザー')),password=field(form,t('FreshRSS API password','FreshRSS APIパスワード'),'','password');password.autocomplete='new-password';
|
||||
const interval=field(form,t('Refresh interval (minutes, 5–1440)','更新間隔(分、5〜1440)'),String((source?.interval_seconds||1800)/60),'number');interval.min='5';interval.max='1440';interval.required=true;
|
||||
const enabled=field(form,t('Enabled','有効'),'','checkbox');enabled.checked=source?source.enabled:true;
|
||||
const toggle=()=>{user.parentElement.hidden=password.parentElement.hidden=!!source||provider.value!=='freshrss';user.required=password.required=!source&&provider.value==='freshrss';};provider.onchange=toggle;toggle();
|
||||
const write=field(form,t('Allow FreshRSS read/star changes','FreshRSSの既読・star変更を許可'),'','checkbox');write.checked=!!source?.write_enabled;
|
||||
const toggle=()=>{write.parentElement.hidden=provider.value!=='freshrss';user.parentElement.hidden=password.parentElement.hidden=!!source||provider.value!=='freshrss';user.required=password.required=!source&&provider.value==='freshrss';};provider.onchange=toggle;toggle();
|
||||
if(source)form.append(el('p',t('Last success: ','最終成功: ')+(source.last_ms?new Date(source.last_ms).toLocaleString():'—')+' · '+(source.error||'OK'),'feed-meta'));
|
||||
const sourceID=source?.uuid||crypto.randomUUID();
|
||||
const save=el('button',t('Save','保存'));save.type='submit';buttons.append(save,button(t('Cancel','取消'),'',closeReader));if(source)buttons.append(button(t('Delete source','購読元を削除'),'',async()=>{if(!confirm(t('Delete this source, cached articles and local read/star state?','購読元・取得記事・内蔵の既読/star状態を削除しますか?')))return;await post('sources/'+source.uuid+'/delete',{version:source.version});currentSource='';await reload();}));form.append(buttons);
|
||||
form.onsubmit=async event=>{event.preventDefault();save.disabled=true;try{await post('sources',{uuid:sourceID,version:source?.version||0,provider:provider.value,title:title.value,folder:folder.value,url:url.value,interval_seconds:Number(interval.value)*60,enabled:enabled.checked,username:user.value,password:password.value});password.value='';await reload();status.textContent=t('Saved','保存しました');}catch(e){report(e);}finally{save.disabled=false;}};title.focus();
|
||||
form.onsubmit=async event=>{event.preventDefault();save.disabled=true;try{await post('sources',{uuid:sourceID,version:source?.version||0,provider:provider.value,title:title.value,folder:folder.value,url:url.value,interval_seconds:Number(interval.value)*60,enabled:enabled.checked,write_enabled:provider.value==='freshrss'&&write.checked,username:user.value,password:password.value});password.value='';await reload();status.textContent=t('Saved','保存しました');}catch(e){report(e);}finally{save.disabled=false;}};title.focus();
|
||||
}
|
||||
function captureForm(item){
|
||||
editing=true;detailSeq++;reader.replaceChildren();const form=el('form');reader.append(form);form.append(el('h1',t('Attributed Wiki note / task','出典付きWikiメモ・タスク')));
|
||||
|
||||
@@ -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=4"></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=6"></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=4" defer></script></body></html>{{ end }}
|
||||
</main><script src="/static/js/feeds.js?v=6" defer></script></body></html>{{ end }}
|
||||
Reference in new issue
Block a user