Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4869c7c8b | ||
|
|
ea1ca432c5 | ||
|
|
c2bc637704 | ||
|
|
a5f90f933d | ||
|
|
78da33d549 | ||
|
|
50a90bcc14 | ||
|
|
bf9a9c2847 | ||
|
|
1057be6d2b | ||
|
|
e4c184d71c |
No files matched your search
+98
-9
@@ -72,13 +72,16 @@ API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用
|
||||
| `POST sources/{uuid}/refresh` | 次回背景取得を予約。画面から外部通信しない |
|
||||
| `POST sources/{uuid}/delete` | versionを照合してsource・cache・内蔵read/starを削除 |
|
||||
| `GET items` | source/unread/starred/件名・配信元で絞り込み、100件単位のkeysetページング |
|
||||
| `GET catalog?source=…` | 本人のFreshRSS購読・カテゴリの取得済み一覧。外部通信なし |
|
||||
| `GET catalog?source=…` | 本人のFreshRSS購読・カテゴリの取得済み一覧。`subscriptions`と空フォルダも含む`folders`。外部通信なし |
|
||||
| `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で再送を識別 |
|
||||
| `POST capture-preview` | Wiki親Pathのプレースホルダを展開。保存・外部通信なし |
|
||||
| `GET opml/export` | 本人の内蔵購読をOPML 2.0としてダウンロード |
|
||||
| `POST opml/preview` | ファイルを解析し、追加可能・登録済み・重複・未対応等を返す。保存・外部通信なし |
|
||||
| `POST opml/import` | 選択行を再解析・検査し、確認時の購読設定と一致する場合だけ原子的に追加 |
|
||||
@@ -90,7 +93,10 @@ 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更新前にバックアップを取得し、
|
||||
送信済みの可能性があるものはunknown、未送信はcancelledにします。
|
||||
v6でsourceに`remote_folders`を追加します。既存の購読・記事・設定version・取得予約・worker claim・
|
||||
書戻しreceiptは変更しません。初回の背景取得までは既存の購読情報から分類を組み立て、
|
||||
空フォルダは次の取得成功時に追加します。DB更新前にバックアップを取得し、
|
||||
旧バイナリへの切戻しだけで追加schemaが巻き戻るとは扱いません。
|
||||
既存テーブルを破壊・再構成しません。SQLiteのforeign_keys設定に依存せず削除を完遂するtriggerを
|
||||
持ちます。内蔵read/starを本文cacheから分離し、記事を保持窓から落としても状態は黙って消しません。
|
||||
@@ -113,7 +119,7 @@ sourceのprovider・URL・資格情報の変更は別sourceを作る契約です
|
||||
| 内蔵記事cache | 1 source最大500件、text本文32 KiB・HTML本文128 KiB。HTML上限超過はtextへフォールバックし、text切詰めを明示 |
|
||||
| 内蔵read/star | 1 source最大10,000件。上限では新規状態保存を拒否し、既存状態を捨てない |
|
||||
| FreshRSS | reading-list最新200件の窓を取得。更新成功時はその窓で置換し、全履歴同期とはしない |
|
||||
| FreshRSS購読一覧 | 最大1,000購読、1購読64カテゴリ、保存JSON 1 MiB。記事と同じ取得予算で収集 |
|
||||
| FreshRSS購読・分類一覧 | 最大1,000購読・1,000フォルダ、1購読64カテゴリ、保存JSON合計1 MiB。記事と同じ取得予算で収集 |
|
||||
| 再試行 | 次の設定間隔まで待機。手動予約にも最終成功から60秒の制限、取得中の重複claim拒否 |
|
||||
|
||||
内蔵は条件付きGET、304ではcacheを保持します。どちらのproviderも通信・認証・構文失敗で
|
||||
@@ -123,17 +129,48 @@ extension無効化は画面・API・取得・完了保存に適用します。
|
||||
|
||||
### FreshRSSの購読とカテゴリ
|
||||
|
||||
背景取得ではlogin後にreading-listと`subscription/list`を読み、両方に成功した場合だけ
|
||||
記事・購読一覧を同じtransactionで置換します。一方の取得失敗、上限超過、不正なsnapshotでは
|
||||
前回の両cacheを保持します。記事が取得窓内にない購読も一覧には残します。
|
||||
背景取得ではlogin後にreading-list・`subscription/list`・`tag/list`を読み、すべてに成功した場合だけ
|
||||
記事・購読一覧・分類一覧を同じtransactionで置換します。一部の取得失敗、上限超過、不正なsnapshotでは
|
||||
前回のcache全体を保持します。記事が取得窓内にない購読も一覧には残します。
|
||||
`tag/list`は`type=folder`だけを分類として取り込み、記事タグとシステムの状態タグは除外します。
|
||||
購読一覧のカテゴリとIDで統合し、購読元のない空フォルダも保持します。
|
||||
|
||||
左ペインでFreshRSS sourceを選ぶと、接続先→分類フォルダ→購読元のツリーを表示します。
|
||||
フォルダ名は記事の絞り込み、隣の矢印は開閉と役割を分けます。開閉状態は接続先UUID単位で
|
||||
ブラウザのlocalStorageに保存し、利用できない場合もその画面内では保持します。
|
||||
閉じたフォルダは購読元のDOMを作らず、展開時は50件ずつ描画します。購読名・分類名で検索すると
|
||||
該当購読を重複なしで一覧化します。名前に含まれる`/`は文字として扱い、独自の階層には分割しません。
|
||||
|
||||
左ペインでFreshRSS sourceを選ぶとカテゴリ選択・購読名の検索・購読一覧を表示します。
|
||||
カテゴリは表示名でなくremote category ID、購読は`origin.streamId`とsubscription IDを対応させます。
|
||||
同名でも混同せず、複数カテゴリに属する購読も扱います。`GET items`の`feed`/`category`は
|
||||
同名でも混同せず、複数カテゴリに属する購読は各フォルダに表示します。記事の分類絞り込みは
|
||||
記事タグではなく同期した購読元の所属を使い、FreshRSSでの分類移動に追従します。
|
||||
分類のない購読は「未分類」に表示し、購読一覧にない記事を未分類へ混在させません。
|
||||
`GET items`の`feed`/`category`/`category_mode=uncategorized`は
|
||||
source指定と組み合わせ、既存の未読・star・検索・keysetページングと併用できます。
|
||||
`category`と`category_mode`の同時指定は拒否します。
|
||||
絞り込み対象は最新200記事のcache内に限られ、購読を選んでも履歴全件を外部取得しません。
|
||||
購読の追加・削除やカテゴリの編集はFreshRSS側で行います。
|
||||
|
||||
ショートカットヘルプは`?`で開閉し、`Esc`または閉じるボタンでも閉じます。
|
||||
ヘルプだけを閉じる操作では閲覧中の記事や入力フォームを変更せず、エラー等のstatus表示も保持します。
|
||||
|
||||
`sharing.x`が有効なDomainでは、本文の操作列にX共有アイコンを表示します。
|
||||
共有するのは記事の件名と原文URLで、RSS画面や非公開WikiのURLではありません。
|
||||
URLはintentの`url`にだけ渡し、`text`へ重複させません。原文URLのない記事では表示しません。
|
||||
通常の`target=_blank`リンクを一つだけ使い、JavaScriptによる二重openや自動投稿は行いません。
|
||||
|
||||
個人設定の「RSSの記事リンクの開き方」は`rss_link_mode`として保存します。既定は`tab`、
|
||||
`embedded`を選ぶと原文リンクとHTML本文中の外部HTTP(S)リンクを同一タブ内の大きなdialogで開きます。
|
||||
外部ページはクリック時だけiframeへ読み込み、閉じる際に破棄します。元の記事・一覧の状態は維持します。
|
||||
Ctrl/Command/Shift付きのクリック等はブラウザ標準の別タブ操作を維持し、X共有アイコンも対象外です。
|
||||
設定はRSS画面の再読込後に反映します。個人設定はタスク拡張のpreferencesに保存し、無効時は別タブを使います。
|
||||
|
||||
iframeは`allow-scripts`だけのsandboxと`no-referrer`を使い、親画面への操作・同一origin権限・
|
||||
フォーム送信・popup等は許可しません。PagesWiki自身のoriginはiframe化しません。
|
||||
リンク先のCSP/X-Frame-Options、ブラウザのmixed-content制限を回避するproxyは用意しません。
|
||||
表示できないページやログイン・フォーム操作が必要な場合は、dialog内の別タブアイコンを使います。
|
||||
表示可否をcross-origin DOMの読取で判定したり、失敗を装って自動で別タブへ遷移したりはしません。
|
||||
|
||||
## 既読とstarの書戻し
|
||||
|
||||
server-authoritative stateと未送信の操作を分けます。操作ごとのrequest_idで重複を防ぎ、成功応答前に確定済みと表示しません。newsboat等で同時変更された場合、古いローカルcacheをまとめて送り返しません。接続解除・認可失効時は未送信変更を勝手に再送しません。
|
||||
@@ -174,6 +211,39 @@ readbackは観測結果であり、exactly-onceやリモートCASの保証とは
|
||||
背景タブでは停止します。記事の既読・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)。
|
||||
@@ -225,6 +295,23 @@ previewはsource UUID・設定versionのsnapshotを返し、適用時に一致
|
||||
|
||||
既定はURL、出典、短いメモの保存です。全文保存は取得可能性・利用条件・個人用途等を確認する独立操作とし、feedが短いからといって有料記事を自動取得しません。保存先が自動公開範囲なら内容と添付の公開を明示確認します。
|
||||
|
||||
タスク拡張が有効な場合、Wiki親Pathの初期値はDomain・本人単位の個人設定`wiki_prefix`を使います。
|
||||
「個人設定 → メール・RSS取り込みの既定Wiki親Path」で設定し、メール取り込みと共通です。
|
||||
RSS画面を読み込んだ時点の値を初期表示し、取り込みごとの上書き・空欄への変更を許します。
|
||||
空欄でタスク作成を選んだ場合はWikiを作らず、個人設定の値を再適用しません。
|
||||
未設定またはタスク拡張が無効な場合は空欄です。プロジェクトのWiki配下への暗黙の補完はRSSでは行いません。
|
||||
保存時の公開範囲確認とACL検査は省略しません。既存preferencesを利用するため追加のschema変更はありません。
|
||||
|
||||
親Pathでは`{YYYY}`・`{MM}`・`{DD}`・`{Subject}`を使用できます。日付は取り込み時のドメインの
|
||||
タイムゾーン、Subjectは編集可能な取り込み件名です。件名中の区切り文字・URI演算子・制御文字・
|
||||
空白はハイフンに変換し、180バイト以内の単一Path要素へ整形します。空になる場合は`untitled`です。
|
||||
未対応トークンや不正なPathは拒否します。メールcaptureでも同じ展開規則を適用します。
|
||||
|
||||
RSS取り込みは本文上のdialogで行い、本文を置き換えません。トークン挿入ボタンと実際の保存先を
|
||||
表示し、件名・親Path・保存種別を変更した場合はプレビューを更新して公開範囲の確認をやり直します。
|
||||
展開済みPathを確認後の要求へ固定し、UUIDの末尾(Wiki単独は`rss-`、タスク併設は`mail-`)で
|
||||
同名記事の衝突を避けます。表示された親Path自体を記事ファイルとして上書きする仕様ではありません。
|
||||
|
||||
Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。既存Pathを上書きせず、Page・Path・
|
||||
初回Revision・活動outbox・再送receiptを同じDB transactionで保存します。権限はtransaction内でも
|
||||
再確認します。初期版の単独保存は通常Wiki空間のみで、独自所有契約を持つ`/u`・`/g`は対象外です。
|
||||
@@ -241,12 +328,14 @@ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。
|
||||
- [x] RSS-1:read-only FreshRSS connectorと合成fixture。実接続の受入は別。
|
||||
- [x] RSS-2:安全な共通一覧、出典付きWiki保存、任意のタスク化、ダッシュボード。
|
||||
- [x] RSS-3:opt-inの既読/star書戻し、操作receipt、背景処理、readback、結果不明の再確認、失効・競合・排他の合成試験。
|
||||
- [ ] RSS-3b:未解決操作の総覧、cache窓から落ちた記事や削除sourceの操作記録確認、保全付きreceiptの整理。既存のGET action/action/checkは記事IDで利用できる。
|
||||
- [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受入。
|
||||
- [ ] RSS-6:大規模利用時の公平性、host別並列上限、Retry-After/backoff、資格情報rotation UI。
|
||||
- [x] RSS-7:FreshRSSの購読一覧・カテゴリを使うnavigation。同名ID分離、複数カテゴリ、cache内絞り込み、背景での原子的更新、失敗時保持。
|
||||
- [x] RSS-7b:分類フォルダの継承、空フォルダ・未分類、開閉状態保存、50件ずつの購読描画、分類移動への追従。schema v6の再実行・失敗rollbackと1440px/390pxの合成試験。
|
||||
|
||||
隔離試験はRSS/Atom・FreshRSS login/read、欠落ID・巨大/不正feed、条件付きGET、失敗時cache保持、
|
||||
本人分離・失効・readonly、二重送信・版競合・旧worker拒否、migration再実行/失敗rollback、
|
||||
|
||||
@@ -81,7 +81,20 @@ code-server・Kroki・独立CLI・ネットワーク構成は変更しない。
|
||||
最終バックアップの両ルートともchecksum付きdry-runの差分はゼロ。
|
||||
旧v0.10.0イメージは`rollback-before-rss-20261108`タグで保持し、ローカルlatestは新イメージに揃えた。
|
||||
今回作成した隔離リハーサル用の一時コピーとコンテナは片付けたが、旧バックアップは削除していない。
|
||||
完了時のディスク空きは約4GiB。保全先への転送確認と保持世代の合意後に、容量整理を優先する。
|
||||
完了時のディスク空きは約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へ増えた。
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
@@ -38,7 +39,18 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
s.renderWithContext(w, r, "feeds.gohtml", map[string]any{"Title": "RSS", "FeedWritable": active})
|
||||
prefix := ""
|
||||
linkMode := "tab"
|
||||
if s.systemExtensionEnabled(domain, "organizer.tasks") {
|
||||
preferences, e := s.store.TaskPreferences(r.Context(), domain, actor)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
prefix = preferences.WikiPrefix
|
||||
linkMode = preferences.RSSLinkMode
|
||||
}
|
||||
s.renderWithContext(w, r, "feeds.gohtml", map[string]any{"Title": "RSS", "FeedWritable": active, "FeedWikiPrefix": prefix, "FeedLinkMode": linkMode, "FeedShareX": s.systemExtensionEnabled(domain, "sharing.x")})
|
||||
return
|
||||
}
|
||||
key := strings.TrimPrefix(r.URL.Path, feedsAPI)
|
||||
@@ -50,13 +62,28 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case key == "catalog" && r.Method == "GET":
|
||||
catalog, e := s.store.FeedCatalog(r.Context(), domain, actor, r.URL.Query().Get("source"))
|
||||
case key == "capture-preview" && r.Method == "POST":
|
||||
var input struct {
|
||||
Prefix string `json:"prefix"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
if !taskJSON(w, r, &input) {
|
||||
return
|
||||
}
|
||||
prefix, e := store.ExpandWikiPrefix(input.Prefix, input.Title, time.Now().In(s.getLocation(domain)))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"subscriptions": catalog})
|
||||
writeEventJSON(w, 200, map[string]string{"prefix": prefix})
|
||||
return
|
||||
case key == "catalog" && r.Method == "GET":
|
||||
catalog, e := s.store.FeedCatalogSnapshot(r.Context(), domain, actor, r.URL.Query().Get("source"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, catalog)
|
||||
return
|
||||
case key == "note" && r.Method == "POST":
|
||||
var input struct {
|
||||
@@ -170,7 +197,7 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
items, e := s.store.FeedItems(r.Context(), domain, actor, q.Get("source"), q.Get("filter"), q.Get("q"), before, q.Get("key"), q.Get("feed"), q.Get("category"))
|
||||
items, e := s.store.FeedItems(r.Context(), domain, actor, q.Get("source"), q.Get("filter"), q.Get("q"), before, q.Get("key"), q.Get("feed"), q.Get("category"), q.Get("category_mode"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
|
||||
@@ -132,6 +132,9 @@ func (s *Server) syncFeedActions(ctx context.Context, client *http.Client) error
|
||||
}
|
||||
|
||||
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"))
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRSSLinkPreference(t *testing.T) {
|
||||
s, token, domain, actor, _ := feedFixture(t)
|
||||
p, err := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if err != nil || p.RSSLinkMode != "tab" {
|
||||
t.Fatal(p.RSSLinkMode, err)
|
||||
}
|
||||
p.RSSLinkMode = "embedded"
|
||||
if w := taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
p, err = s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if err != nil || p.RSSLinkMode != "embedded" {
|
||||
t.Fatal(p.RSSLinkMode, err)
|
||||
}
|
||||
p.RSSLinkMode = "unsafe"
|
||||
if w := taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 422 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedCapturePreview(t *testing.T) {
|
||||
s, token, _, _, _ := feedFixture(t)
|
||||
for _, tt := range []struct {
|
||||
prefix string
|
||||
status int
|
||||
}{{"/notes/{YYYY}/{MM}/{DD}/{Subject}", 200}, {"/notes/{unknown}", 422}, {"/a/../b", 422}} {
|
||||
w := feedRequestTest(s, token, "POST", "capture-preview", map[string]string{"prefix": tt.prefix, "title": "日本語 / test"})
|
||||
if w.Code != tt.status {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w.Code == 200 {
|
||||
var data map[string]string
|
||||
if e := json.Unmarshal(w.Body.Bytes(), &data); e != nil || strings.ContainsAny(data["prefix"], "{}") || !strings.HasSuffix(data["prefix"], "/日本語---test") {
|
||||
t.Fatal(data, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if w := feedRequestTest(s, "", "POST", "capture-preview", map[string]string{"prefix": "/notes"}); w.Code != 401 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
}
|
||||
calls := 0
|
||||
failCatalog := false
|
||||
failFolders := false
|
||||
client := &http.Client{Transport: feedTransportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
body := ""
|
||||
@@ -63,7 +64,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
t.Error("article request")
|
||||
}
|
||||
body = `{"items":[{"id":"a","title":"First","origin":{"title":"Same title","streamId":"feed/1"},"categories":["user/alice/label/Tech"]},{"id":"b","title":"Second","origin":{"title":"Same title","streamId":"feed/2"},"categories":["user/alice/label/Other"]}]}`
|
||||
if failCatalog {
|
||||
if failCatalog || failFolders {
|
||||
body = `{"items":[]}`
|
||||
}
|
||||
case strings.HasSuffix(r.URL.Path, "/subscription/list"):
|
||||
@@ -74,6 +75,11 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
return nil, errors.New("synthetic timeout")
|
||||
}
|
||||
body = testFeedCatalog
|
||||
case strings.HasSuffix(r.URL.Path, "/tag/list"):
|
||||
if failFolders {
|
||||
return nil, errors.New("synthetic folder failure")
|
||||
}
|
||||
body = `{"tags":[{"id":"user/-/label/Empty/Folder","type":"folder"},{"id":"user/-/label/Not a folder","type":"tag"}]}`
|
||||
default:
|
||||
t.Fatalf("unexpected external request %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
@@ -89,7 +95,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
run()
|
||||
if calls != 3 {
|
||||
if calls != 4 {
|
||||
t.Fatal("fetch count", calls)
|
||||
}
|
||||
w := feedRequestTest(s, token, "GET", "catalog?source="+v.UUID, nil)
|
||||
@@ -127,9 +133,16 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
if _, e := s.store.FeedCatalog(ctx, uuid.NewString(), actor, v.UUID); e == nil {
|
||||
t.Fatal("cross-domain catalog leak")
|
||||
}
|
||||
if calls != 3 {
|
||||
if calls != 4 {
|
||||
t.Fatal("foreground external request")
|
||||
}
|
||||
failFolders = true
|
||||
run()
|
||||
kept, e := s.store.FeedCatalogSnapshot(ctx, domain, actor, v.UUID)
|
||||
if e != nil || len(kept.Folders) != 3 || len(kept.Subscriptions) != 3 {
|
||||
t.Fatal("folder failure erased snapshot", kept, e)
|
||||
}
|
||||
failFolders = false
|
||||
failCatalog = true
|
||||
run()
|
||||
catalog, e := s.store.FeedCatalog(ctx, domain, actor, v.UUID)
|
||||
|
||||
@@ -345,7 +345,7 @@ func freshRSSLogin(ctx context.Context, client *http.Client, v store.FeedSource,
|
||||
}
|
||||
return auth, nil
|
||||
}
|
||||
func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, user, password string, catalogs ...*[]store.FeedRemoteSubscription) ([]store.FeedItem, error) {
|
||||
func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, user, password string, catalogs ...*store.FeedCatalogSnapshot) ([]store.FeedItem, error) {
|
||||
base := strings.TrimRight(v.URL, "/")
|
||||
auth, e := freshRSSLogin(ctx, client, v, user, password)
|
||||
if e != nil {
|
||||
@@ -368,7 +368,23 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
*catalogs[0] = catalog
|
||||
raw, _, _, e = feedRequest(ctx, client, "GET", base+"/reader/api/0/tag/list?output=json", auth, nil, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
folders, e := parseFreshRSSFolders(raw)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
folders, e = store.FeedFolders(catalog, folders)
|
||||
if e != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
snapshot := store.FeedCatalogSnapshot{Subscriptions: catalog, Folders: folders}
|
||||
if _, _, e = snapshot.Encode(); e != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
*catalogs[0] = snapshot
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -504,7 +520,7 @@ func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.Event
|
||||
}
|
||||
child, stop := context.WithTimeout(ctx, 8*time.Second)
|
||||
var items []store.FeedItem
|
||||
var catalog []store.FeedRemoteSubscription
|
||||
var catalog store.FeedCatalogSnapshot
|
||||
etag, modified := v.ETag, v.Modified
|
||||
unchanged := false
|
||||
if !validCalendarSourceURL(v.URL) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func parseFreshRSSFolders(raw []byte) ([]store.FeedCategory, error) {
|
||||
if len(raw) > 4<<20 || !utf8.Valid(raw) {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
var response struct {
|
||||
Tags []struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
} `json:"tags"`
|
||||
}
|
||||
if json.Unmarshal(raw, &response) != nil || response.Tags == nil || len(response.Tags) > 10000 {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
folders := []store.FeedCategory{}
|
||||
seen := map[string]bool{}
|
||||
for _, tag := range response.Tags {
|
||||
// Article tags and system state tags are not subscription folders.
|
||||
if tag.Type != "folder" {
|
||||
continue
|
||||
}
|
||||
prefix, label, ok := strings.Cut(tag.ID, "/label/")
|
||||
if !ok || !strings.HasPrefix(prefix, "user/") || len(prefix) <= 5 || label == "" || !store.ValidFeedRemoteID(tag.ID) || seen[tag.ID] {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
seen[tag.ID] = true
|
||||
folders = append(folders, store.FeedCategory{ID: tag.ID, Label: feedText(label, 512)})
|
||||
}
|
||||
if _, e := store.FeedFolders(nil, folders); e != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
return folders, nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestFreshRSSFoldersParsing(t *testing.T) {
|
||||
folders, e := parseFreshRSSFolders([]byte(`{"tags":[{"id":"user/-/state/com.google/starred"},{"id":"user/-/label/ArticleTag","type":"tag"},{"id":"user/-/label/技術/Linux","type":"folder"}]}`))
|
||||
if e != nil || len(folders) != 1 || folders[0].Label != "技術/Linux" {
|
||||
t.Fatal(folders, e)
|
||||
}
|
||||
for _, raw := range []string{`{}`, `{"tags":null}`, `{"tags":[{"id":"invalid","type":"folder"}]}`, `{"tags":[{"id":"user/-/label/","type":"folder"}]}`, `{"tags":[{"id":"user/-/label/A","type":"folder"},{"id":"user/-/label/A","type":"folder"}]}`} {
|
||||
if _, e = parseFreshRSSFolders([]byte(raw)); e == nil {
|
||||
t.Fatal("invalid folder accepted", raw)
|
||||
}
|
||||
}
|
||||
tags := []map[string]string{}
|
||||
for i := 0; i < 1001; i++ {
|
||||
tags = append(tags, map[string]string{"id": fmt.Sprintf("user/-/label/%d", i), "type": "folder"})
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"tags": tags})
|
||||
if _, e = parseFreshRSSFolders(raw); e == nil {
|
||||
t.Fatal("unbounded folders")
|
||||
}
|
||||
if _, e = store.FeedFolders([]store.FeedRemoteSubscription{{ID: "feed/1", Categories: []store.FeedCategory{{ID: "cat", Label: "A"}}}}, []store.FeedCategory{{ID: "cat", Label: "B"}}); e == nil {
|
||||
t.Fatal("conflicting labels")
|
||||
}
|
||||
large := store.FeedCatalogSnapshot{}
|
||||
for i := 0; i < 1000; i++ {
|
||||
large.Subscriptions = append(large.Subscriptions, store.FeedRemoteSubscription{ID: fmt.Sprintf("feed/%d", i), Title: strings.Repeat("s", 512)})
|
||||
large.Folders = append(large.Folders, store.FeedCategory{ID: fmt.Sprintf("user/-/label/%d", i), Label: strings.Repeat("f", 512)})
|
||||
}
|
||||
if _, e := store.FeedCatalogJSON(large.Subscriptions); e != nil {
|
||||
t.Fatal("catalog alone should fit", e)
|
||||
}
|
||||
if _, _, e := large.Encode(); e != store.ErrTaskDAVLimit {
|
||||
t.Fatal("combined snapshot limit", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedFolderMembershipAndUncategorized(t *testing.T) {
|
||||
s, token, domain, actor, source := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, e := s.store.DB.Exec(`UPDATE feed_sources SET next_ms=0 WHERE uuid=?`, source.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
sources, e := s.store.FeedSources(ctx, domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, v := range sources {
|
||||
if v.UUID == source.UUID {
|
||||
source = v
|
||||
}
|
||||
}
|
||||
claim, e := s.store.ClaimFeed(ctx, source)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
cat := store.FeedCategory{ID: "user/-/label/New/Folder", Label: "New/Folder"}
|
||||
snapshot := store.FeedCatalogSnapshot{Subscriptions: []store.FeedRemoteSubscription{{ID: "feed/1", Title: "Moved", Categories: []store.FeedCategory{cat}}, {ID: "feed/2", Title: "Unclassified", Categories: []store.FeedCategory{}}}, Folders: []store.FeedCategory{{ID: "user/-/label/Empty", Label: "Empty"}}}
|
||||
items := []store.FeedItem{{ID: "a", Title: "Moved", RemoteFeed: "feed/1", RemoteCategories: []string{"user/-/label/Old"}}, {ID: "b", Title: "Unclassified", RemoteFeed: "feed/2", RemoteCategories: []string{"user/-/label/ArticleTag"}}, {ID: "c", Title: "Unknown subscription", RemoteFeed: "feed/unknown"}}
|
||||
if e = s.store.CompleteFeed(ctx, claim, items, "", "", "", false, snapshot); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
query string
|
||||
want string
|
||||
}{{"category=" + url.QueryEscape(cat.ID), "a"}, {"category_mode=uncategorized", "b"}, {"category=user%2F-%2Flabel%2FOld", ""}, {"category=user%2F-%2Flabel%2FEmpty", ""}} {
|
||||
w := feedRequestTest(s, token, "GET", "items?source="+source.UUID+"&"+test.query, nil)
|
||||
var data struct {
|
||||
Items []store.FeedItem `json:"items"`
|
||||
}
|
||||
json.Unmarshal(w.Body.Bytes(), &data)
|
||||
if w.Code != 200 || (test.want == "" && len(data.Items) != 0) || (test.want != "" && (len(data.Items) != 1 || data.Items[0].ID != test.want)) {
|
||||
t.Fatal(test.query, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
for _, query := range []string{"category_mode=uncategorized", "source=" + source.UUID + "&category_mode=bad", "source=" + source.UUID + "&category_mode=uncategorized&category=" + url.QueryEscape(cat.ID)} {
|
||||
if w := feedRequestTest(s, token, "GET", "items?"+query, nil); w.Code != 422 {
|
||||
t.Fatal(query, w.Code)
|
||||
}
|
||||
}
|
||||
got, e := s.store.FeedCatalogSnapshot(ctx, domain, actor, source.UUID)
|
||||
if e != nil || len(got.Folders) != 2 {
|
||||
t.Fatal(got, e)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -531,6 +531,15 @@ func TestFeedsChromium(t *testing.T) {
|
||||
t.Skip("opt-in Chromium")
|
||||
}
|
||||
s, token, domain, actor, source := feedFixture(t)
|
||||
prefs, err := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prefs.WikiPrefix = "/notes/{YYYY}/{MM}/{DD}/{Subject}"
|
||||
prefs.RSSLinkMode = "embedded"
|
||||
if _, err = s.store.SaveTaskPreferences(context.Background(), domain, actor, prefs, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claim, e := s.store.ClaimFeed(context.Background(), source)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
@@ -569,7 +578,7 @@ func TestFeedsChromium(t *testing.T) {
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "catalog-a", Title: "Catalog first", RemoteFeed: "feed/1", RemoteCategories: []string{"user/alice/label/Tech"}}, {ID: "catalog-b", Title: "Catalog second", RemoteFeed: "feed/2", RemoteCategories: []string{"user/alice/label/Other"}}}, "", "", "", false, catalog); e != nil {
|
||||
if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "catalog-a", Title: "Catalog first", RemoteFeed: "feed/1", RemoteCategories: []string{"user/alice/label/Tech"}}, {ID: "catalog-b", Title: "Catalog second", RemoteFeed: "feed/2", RemoteCategories: []string{"user/alice/label/Other"}}}, "", "", "", false, store.FeedCatalogSnapshot{Subscriptions: catalog, Folders: []store.FeedCategory{{ID: "user/-/label/Empty/Folder", Label: "Empty/Folder"}}}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s.store.BackgroundJobsDisabled = true
|
||||
@@ -582,6 +591,11 @@ 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/embedded" {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
io.WriteString(w, `<h1>Isolated external article fixture</h1><script>parent.postMessage('rss-external-fixture-loaded','*')</script>`)
|
||||
return
|
||||
}
|
||||
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 {
|
||||
@@ -591,6 +605,28 @@ func TestFeedsChromium(t *testing.T) {
|
||||
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>")
|
||||
@@ -600,7 +636,7 @@ func TestFeedsChromium(t *testing.T) {
|
||||
}))
|
||||
defer web.Close()
|
||||
for _, width := range []string{"1440", "390"} {
|
||||
if _, e = s.store.DB.Exec(`DELETE FROM feed_actions WHERE source_uuid=?`, fresh.UUID); e != nil {
|
||||
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 {
|
||||
|
||||
@@ -256,7 +256,8 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
writeEventJSON(w, 422, map[string]string{"error": "wiki_prefix_required"})
|
||||
return
|
||||
}
|
||||
if !store.ValidTaskWikiPrefix(prefix) {
|
||||
prefix, err = store.ExpandWikiPrefix(prefix, item.Title, time.Now().In(s.getLocation(domain)))
|
||||
if err != nil {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
|
||||
Vendored
+30
-7
@@ -4,12 +4,17 @@
|
||||
const frame=document.createElement('iframe');frame.style='display:block;width:100%;height:100vh;border:0';document.body.append(frame);
|
||||
try{
|
||||
await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/feeds';});const d=frame.contentDocument,w=frame.contentWindow;
|
||||
for(const key of Object.keys(w.localStorage))if(key.startsWith('pageswiki.feed-folders.v1:'))w.localStorage.removeItem(key);
|
||||
await wait(()=>d.querySelectorAll('.feed-row').length===100);
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'Viewport overflow');
|
||||
assert(d.title.startsWith('RSS ·'),'RSS title');assert(d.getElementById('feed-status').textContent==='','Unrequested status copy');assert(w.getComputedStyle(d.getElementById('feed-status')).display==='none','Empty status takes space');
|
||||
for(const a of d.querySelectorAll('.organizer-nav a')){assert(a.getAttribute('aria-label'),'Unnamed navigation');if(w.innerWidth<=700)assert(w.getComputedStyle(a.querySelector('span')).display==='none','Mobile tab label visible');}
|
||||
d.getElementById('feed-rows').focus();d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'j',bubbles:true}));
|
||||
await wait(()=>d.querySelector('#feed-reader .feed-body'));const html=d.querySelector('#feed-reader .feed-body').shadowRoot;assert(html?.querySelector('h2')&&html.querySelector('table')&&html.querySelector('strong'),'HTML not rendered');assert(!html.querySelector('script,img,iframe,form'),'Active article HTML');assert(!w.rssAttack,'Script executed');assert(html.querySelector('a').target==='_blank','Article link target');assert(d.querySelector('.feed-original svg')&&!d.querySelector('.feed-original').textContent,'Original link not icon');
|
||||
const share=d.querySelector('.feed-share-x'),intent=new URL(share.href);assert(share.target==='_blank'&&share.rel.includes('noopener')&&intent.searchParams.get('url')==='https://example.org/article'&&intent.searchParams.get('text').includes('日本語のRSS記事')&&!intent.searchParams.get('text').includes('https://'),'RSS share URL or duplicate URL in text');
|
||||
assert(d.getElementById('feeds-app').dataset.linkMode==='embedded','Link preference missing');assert(!d.querySelector('.feed-external iframe'),'External page fetched before click');const externalURL=new URL('/fixture/embedded',w.location.href);externalURL.hostname='localhost';let externalLoaded=0;w.addEventListener('message',e=>{if(e.data==='rss-external-fixture-loaded'&&e.origin==='null')externalLoaded++;});const original=d.querySelector('.feed-original');original.href=externalURL.href;original.click();await wait(()=>d.querySelector('.feed-external[open] iframe'));await wait(()=>externalLoaded===1);let previewFrame=d.querySelector('.feed-external iframe');assert(previewFrame.src===externalURL.href&&previewFrame.getAttribute('sandbox')==='allow-scripts'&&previewFrame.referrerPolicy==='no-referrer','Unsafe external frame');assert(d.querySelector('.feed-external a').target==='_blank','Missing fallback');d.querySelector('.feed-external button').click();await wait(()=>!d.querySelector('.feed-external'));assert(d.querySelector('#feed-reader .feed-body'),'External preview lost article');const articleLink=html.querySelector('a');articleLink.href=externalURL.href;articleLink.click();await wait(()=>externalLoaded===2);d.querySelector('.feed-external').close();await wait(()=>!d.querySelector('.feed-external'));
|
||||
const help=d.getElementById('feed-help'),helpButton=d.querySelector('[aria-controls="feed-help"]'),key=k=>d.dispatchEvent(new w.KeyboardEvent('keydown',{key:k,bubbles:true}));
|
||||
d.getElementById('feed-status').textContent='Synthetic status';key('?');await wait(()=>!help.hidden);assert(helpButton.getAttribute('aria-expanded')==='true','Help toggle state');key('Escape');assert(help.hidden&&d.querySelector('.feed-layout').classList.contains('reading'),'Closing help changed reader');assert(d.getElementById('feed-status').textContent==='Synthetic status','Help erased status');key('?');await wait(()=>!help.hidden);key('?');await wait(()=>help.hidden);helpButton.click();await wait(()=>!help.hidden);help.querySelector('button').click();await wait(()=>help.hidden);assert(helpButton.getAttribute('aria-expanded')==='false','Help state not reset');d.getElementById('feed-status').textContent='';
|
||||
d.querySelectorAll('.feed-row')[1].click();await wait(()=>d.querySelector('#feed-reader .feed-body')&&!d.querySelector('#feed-reader .feed-body').shadowRoot);assert(d.querySelector('#feed-reader .feed-body').textContent.includes('<script>'),'Literal text not preserved');d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')?.shadowRoot);
|
||||
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'*',bubbles:true}));await wait(()=>d.querySelector('.feed-row[aria-selected=true]').textContent.includes('★'));
|
||||
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));await wait(()=>!d.querySelector('.feed-layout').classList.contains('reading'));
|
||||
@@ -17,7 +22,8 @@
|
||||
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'/',bubbles:true}));await wait(()=>d.activeElement.type==='search');d.activeElement.value='119';d.activeElement.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===1);
|
||||
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));
|
||||
d.querySelector('#feed-reader .feed-actions button:last-child').click();await wait(()=>d.querySelector('#feed-reader form'));
|
||||
const form=d.querySelector('#feed-reader form'),inputs=form.querySelectorAll('input');inputs[2].value='/notes/feed-ui';inputs[2].dispatchEvent(new w.Event('input'));inputs[5].checked=true;form.requestSubmit();await wait(()=>d.querySelector('#feed-reader a[href^="/v/uuid:"]'));
|
||||
assert(!['rgba(0, 0, 0, 0)','transparent'].includes(w.getComputedStyle(d.querySelector('.feed-capture')).backgroundColor),'Capture dialog background transparent');
|
||||
const form=d.querySelector('#feed-reader form'),inputs=form.querySelectorAll('input');assert(inputs[2].value==='/notes/{YYYY}/{MM}/{DD}/{Subject}','Wiki default not filled');assert(form.closest('dialog').open&&d.querySelector('#feed-reader .feed-body'),'Capture replaced article');assert(form.querySelector('a[href="/-/sys/config?panel=organizer"]'),'Default settings link missing');await wait(()=>form.querySelector('output').textContent.includes('/rss-'));assert(!form.querySelector('output').textContent.includes('{'),'Template not expanded');inputs[2].value='/notes/feed-ui';inputs[2].dispatchEvent(new w.Event('input'));await wait(()=>form.querySelector('output').textContent.startsWith('/notes/feed-ui/rss-'));inputs[5].checked=true;form.requestSubmit();await wait(()=>d.querySelector('#feed-reader a[href^="/v/uuid:"]'));d.querySelector('.feed-capture button').click();await wait(()=>!d.querySelector('.feed-capture'));assert(d.querySelector('#feed-reader .feed-body'),'Closing capture lost article');
|
||||
const search=d.querySelector('#feed-toolbar input');search.value='';search.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===100);d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'Reader overflow');
|
||||
d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));
|
||||
@@ -27,10 +33,15 @@
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML overflow');d.querySelector('.feed-import-options input[type=checkbox]').checked=false;d.getElementById('feed-opml-preview').requestSubmit();await wait(()=>!d.getElementById('feed-opml-preview'));
|
||||
assert(d.getElementById('feed-sources').textContent.includes('Import '+w.innerWidth),'Imported source missing');d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));choose();await wait(()=>d.querySelectorAll('#feed-opml-preview tbody tr').length===3);assert(d.querySelector('#feed-opml-preview tbody input').disabled,'Duplicate after import');
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML preview overflow');
|
||||
[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='FreshRSS fixture').click();await wait(()=>d.querySelectorAll('.feed-subscriptions button').length===4&&d.querySelectorAll('.feed-row').length===2);
|
||||
const category=d.getElementById('feed-category');category.value='user/alice/label/Tech';category.dispatchEvent(new w.Event('change'));await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog first'));
|
||||
assert(d.querySelectorAll('.feed-subscriptions button').length===2,'Category navigation');
|
||||
d.getElementById('feed-category').value='';d.getElementById('feed-category').dispatchEvent(new w.Event('change'));await wait(()=>d.querySelectorAll('.feed-row').length===2);
|
||||
const freshButton=()=>[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='FreshRSS fixture');freshButton().click();await wait(()=>d.querySelectorAll('.feed-folder').length===4&&d.querySelectorAll('.feed-row').length===2);
|
||||
const folder=id=>[...d.querySelectorAll('.feed-folder')].find(n=>n.dataset.category===id),tech=()=>folder('user/alice/label/Tech');
|
||||
tech().querySelector('.feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog first'));
|
||||
assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='false','Selecting folder expands it unexpectedly');tech().querySelector('.feed-folder-toggle').click();await wait(()=>tech().querySelector('button[data-feed="feed/1"]'));
|
||||
const empty=folder('user/-/label/Empty/Folder');assert(empty.querySelector('.feed-folder-name span').textContent==='Empty/Folder','Slash label split');empty.querySelector('.feed-folder-toggle').click();assert(!empty.querySelector('button[data-feed]'),'Empty folder fabricated a feed');empty.querySelector('.feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===0);
|
||||
d.querySelector('.feed-folder[data-mode="uncategorized"] .feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===0);
|
||||
d.querySelector('.feed-catalog .feed-tree-all').click();await wait(()=>d.querySelectorAll('.feed-row').length===2);
|
||||
[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='Synthetic news').click();await wait(()=>!d.querySelector('.feed-catalog'));freshButton().click();await wait(()=>tech()?.querySelector('button[data-feed="feed/1"]'));assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='true','Folder expansion not retained');
|
||||
folder('user/alice/label/Other').querySelector('.feed-folder-toggle').click();await wait(()=>d.querySelector('.feed-subscriptions button[data-feed="feed/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');
|
||||
[...d.querySelectorAll('.feed-source')].find(n=>n.textContent.includes('FreshRSS fixture')).querySelector('button:last-child').click();await wait(()=>d.querySelector('#feed-reader form'));
|
||||
@@ -41,7 +52,19 @@
|
||||
// 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})});
|
||||
if(w.innerWidth<=600)d.querySelector('#feed-toolbar button').click();
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'Catalog overflow');document.body.dataset.vimReady='1';
|
||||
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');
|
||||
const probe=document.createElement('iframe');probe.hidden=true;document.body.append(probe);await new Promise(resolve=>{probe.onload=resolve;probe.src='/v/feeds?source='+encodeURIComponent(source.uuid);});await wait(()=>probe.contentDocument.querySelector('.feed-folder[data-category="user/alice/label/Tech"] .feed-folder-toggle')?.getAttribute('aria-expanded')==='true');probe.remove();
|
||||
freshButton().click();await wait(()=>tech()?.querySelector('button[data-feed="feed/1"]'));if(w.innerWidth<=700){d.querySelector('#feed-toolbar button').click();await wait(()=>d.querySelector('.feed-layout').classList.contains('sources-open'));assert(w.getComputedStyle(d.getElementById('feed-sources')).display!=='none','Mobile folders hidden');}assert(d.documentElement.scrollWidth<=w.innerWidth,'Folder tree overflow');document.body.dataset.vimReady='1';
|
||||
}catch(e){const out=document.createElement('pre');out.id='error';out.textContent=e.stack;document.body.append(out);}
|
||||
})();
|
||||
+47
-6
@@ -54,6 +54,10 @@ var feedMigrations = []db.SQLMigration{{Version: 1, Name: "private_feed_reader",
|
||||
`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")},
|
||||
}, {
|
||||
Version: 6, Name: "freshrss_empty_folders", Statements: []string{
|
||||
`ALTER TABLE feed_sources ADD COLUMN remote_folders TEXT NOT NULL DEFAULT '[]'`,
|
||||
}, Assertions: []string{schemaColumns("feed_sources", "remote_folders")},
|
||||
}}
|
||||
|
||||
// CaptureFeedNote creates an inert Wiki note and receipt atomically. It does not
|
||||
@@ -263,6 +267,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
|
||||
@@ -319,7 +334,7 @@ func (s *Store) FeedSourceAction(ctx context.Context, domain, owner, id, action
|
||||
}
|
||||
func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, query string, before int64, beforeID string, scope ...string) ([]FeedItem, error) {
|
||||
remoteFeed, category := "", ""
|
||||
if len(scope) > 2 {
|
||||
if len(scope) > 3 {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
if len(scope) > 0 {
|
||||
@@ -328,6 +343,13 @@ func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, qu
|
||||
if len(scope) > 1 {
|
||||
category = scope[1]
|
||||
}
|
||||
mode := ""
|
||||
if len(scope) > 2 {
|
||||
mode = scope[2]
|
||||
}
|
||||
if mode != "" && (mode != "uncategorized" || source == "" || category != "") {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
if (remoteFeed != "" && !ValidFeedRemoteID(remoteFeed)) || (category != "" && !ValidFeedRemoteID(category)) || ((remoteFeed != "" || category != "") && source == "") {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
@@ -337,7 +359,14 @@ func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, qu
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
rows, e := s.DB.QueryContext(ctx, `SELECT i.source_uuid,i.id,i.title,i.url,i.published_ms,i.feed,CASE WHEN s.folder<>'' THEN s.folder ELSE i.folder END,CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END,CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END,COALESCE(t.version,0),s.provider FROM feed_items i JOIN feed_sources s ON s.uuid=i.source_uuid LEFT JOIN feed_states t ON t.source_uuid=i.source_uuid AND t.id=i.id WHERE s.domain_uuid=? AND s.owner_uuid=? AND (?='' OR s.uuid=?) AND (?='' OR instr(lower(i.title),lower(?))>0 OR instr(lower(i.feed),lower(?))>0) AND (?<0 OR i.published_ms<? OR (i.published_ms=? AND (i.source_uuid||':'||i.id)<?)) AND (?<>'unread' OR (CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END)=0) AND (?<>'starred' OR (CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END)=1) AND (?='' OR i.remote_feed=?) AND (?='' OR EXISTS(SELECT 1 FROM json_each(i.remote_categories) WHERE value=?)) ORDER BY i.published_ms DESC,i.source_uuid||':'||i.id DESC LIMIT 101`, domain, owner, source, source, query, query, query, before, before, before, beforeID, filter, filter, remoteFeed, remoteFeed, category, category)
|
||||
args := []any{domain, owner, source, source, query, query, query, before, before, before, beforeID, filter, filter, remoteFeed, remoteFeed, category, category}
|
||||
extra := ""
|
||||
if mode == "uncategorized" {
|
||||
// The uncorrelated list is built once, not a catalog scan per article.
|
||||
extra = ` AND i.remote_feed IN (SELECT json_extract(c.value,'$.id') FROM feed_sources cs,json_each(cs.remote_catalog) c WHERE cs.uuid=? AND cs.domain_uuid=? AND cs.owner_uuid=? AND json_array_length(c.value,'$.categories')=0)`
|
||||
args = append(args, source, domain, owner)
|
||||
}
|
||||
rows, e := s.DB.QueryContext(ctx, `SELECT i.source_uuid,i.id,i.title,i.url,i.published_ms,i.feed,CASE WHEN s.folder<>'' THEN s.folder ELSE i.folder END,CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END,CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END,COALESCE(t.version,0),s.provider FROM feed_items i JOIN feed_sources s ON s.uuid=i.source_uuid LEFT JOIN feed_states t ON t.source_uuid=i.source_uuid AND t.id=i.id WHERE s.domain_uuid=? AND s.owner_uuid=? AND (?='' OR s.uuid=?) AND (?='' OR instr(lower(i.title),lower(?))>0 OR instr(lower(i.feed),lower(?))>0) AND (?<0 OR i.published_ms<? OR (i.published_ms=? AND (i.source_uuid||':'||i.id)<?)) AND (?<>'unread' OR (CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END)=0) AND (?<>'starred' OR (CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END)=1) AND (?='' OR i.remote_feed=?) AND (?='' OR EXISTS(SELECT 1 FROM json_each(i.remote_categories) WHERE value=?))`+extra+` ORDER BY i.published_ms DESC,i.source_uuid||':'||i.id DESC LIMIT 101`, args...)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
@@ -454,17 +483,29 @@ func (s *Store) ClaimFeed(ctx context.Context, v FeedSource) (FeedSource, error)
|
||||
}
|
||||
|
||||
// Failed fetches preserve the previous cache. Version and claim token fence stale workers.
|
||||
func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem, etag, modified, code string, unchanged bool, catalogs ...[]FeedRemoteSubscription) error {
|
||||
func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem, etag, modified, code string, unchanged bool, catalogs ...FeedCatalogSnapshot) error {
|
||||
if len(catalogs) > 1 {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
var catalog string
|
||||
var catalog, folders string
|
||||
if len(catalogs) == 1 {
|
||||
var e error
|
||||
catalog, e = FeedCatalogJSON(catalogs[0])
|
||||
catalog, folders, e = catalogs[0].Encode()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if v.Provider == "freshrss" {
|
||||
membership := map[string][]string{}
|
||||
for _, sub := range catalogs[0].Subscriptions {
|
||||
for _, c := range sub.Categories {
|
||||
membership[sub.ID] = append(membership[sub.ID], c.ID)
|
||||
}
|
||||
}
|
||||
items = append([]FeedItem(nil), items...)
|
||||
for n := range items {
|
||||
items[n].RemoteCategories = membership[items[n].RemoteFeed]
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(items) > 500 || len(etag) > 1024 || len(modified) > 1024 {
|
||||
return ErrTaskInvalid
|
||||
@@ -500,7 +541,7 @@ func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem
|
||||
return nil
|
||||
}
|
||||
if catalog != "" {
|
||||
if _, e = tx.ExecContext(ctx, `UPDATE feed_sources SET remote_catalog=? WHERE uuid=?`, catalog, v.UUID); e != nil {
|
||||
if _, e = tx.ExecContext(ctx, `UPDATE feed_sources SET remote_catalog=?,remote_folders=? WHERE uuid=?`, catalog, folders, v.UUID); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ func (s *Store) QueueFeedAction(ctx context.Context, domain, owner string, a Fee
|
||||
// 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.enabled=1)`, domain, owner, request, time.Now().UnixMilli())
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -18,6 +18,51 @@ type FeedRemoteSubscription struct {
|
||||
Categories []FeedCategory `json:"categories"`
|
||||
}
|
||||
|
||||
type FeedCatalogSnapshot struct {
|
||||
Subscriptions []FeedRemoteSubscription `json:"subscriptions"`
|
||||
Folders []FeedCategory `json:"folders"`
|
||||
}
|
||||
|
||||
// Merge membership-derived folders with explicit folders, including empty
|
||||
// ones. IDs, not labels or slash-delimited paths, are the identity boundary.
|
||||
func FeedFolders(catalog []FeedRemoteSubscription, folders []FeedCategory) ([]FeedCategory, error) {
|
||||
out := []FeedCategory{}
|
||||
seen := map[string]string{}
|
||||
add := func(c FeedCategory) error {
|
||||
if !ValidFeedRemoteID(c.ID) || len(c.Label) > 512 || !utf8.ValidString(c.Label) {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
if label, ok := seen[c.ID]; ok {
|
||||
if label != c.Label {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
seen[c.ID] = c.Label
|
||||
out = append(out, c)
|
||||
if len(out) > 1000 {
|
||||
return ErrTaskDAVLimit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(folders) > 1000 {
|
||||
return nil, ErrTaskDAVLimit
|
||||
}
|
||||
for _, c := range folders {
|
||||
if e := add(c); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
for _, sub := range catalog {
|
||||
for _, c := range sub.Categories {
|
||||
if e := add(c); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func ValidFeedRemoteID(id string) bool {
|
||||
return id != "" && len(id) <= 2048 && utf8.ValidString(id) && !strings.ContainsAny(id, "\x00\r\n")
|
||||
}
|
||||
@@ -59,17 +104,47 @@ func FeedCatalogJSON(catalog []FeedRemoteSubscription) (string, error) {
|
||||
return string(raw), nil
|
||||
}
|
||||
|
||||
func (s *Store) FeedCatalog(ctx context.Context, domain, owner, source string) ([]FeedRemoteSubscription, error) {
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return nil, e
|
||||
// Validate the complete snapshot before persisting or reporting fetch success.
|
||||
func (v FeedCatalogSnapshot) Encode() (string, string, error) {
|
||||
catalog, e := FeedCatalogJSON(v.Subscriptions)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
var raw string
|
||||
if e := s.DB.QueryRowContext(ctx, `SELECT remote_catalog FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, source, domain, owner).Scan(&raw); e != nil {
|
||||
return nil, e
|
||||
folders, e := FeedFolders(v.Subscriptions, v.Folders)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
var catalog []FeedRemoteSubscription
|
||||
if e := json.Unmarshal([]byte(raw), &catalog); e != nil {
|
||||
return nil, e
|
||||
raw, e := json.Marshal(folders)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
return catalog, nil
|
||||
if len(raw)+len(catalog) > 1<<20 {
|
||||
return "", "", ErrTaskDAVLimit
|
||||
}
|
||||
return catalog, string(raw), nil
|
||||
}
|
||||
|
||||
func (s *Store) FeedCatalog(ctx context.Context, domain, owner, source string) ([]FeedRemoteSubscription, error) {
|
||||
v, e := s.FeedCatalogSnapshot(ctx, domain, owner, source)
|
||||
return v.Subscriptions, e
|
||||
}
|
||||
|
||||
func (s *Store) FeedCatalogSnapshot(ctx context.Context, domain, owner, source string) (FeedCatalogSnapshot, error) {
|
||||
v := FeedCatalogSnapshot{}
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return v, e
|
||||
}
|
||||
var raw, folders string
|
||||
if e := s.DB.QueryRowContext(ctx, `SELECT remote_catalog,remote_folders FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, source, domain, owner).Scan(&raw, &folders); e != nil {
|
||||
return v, e
|
||||
}
|
||||
if e := json.Unmarshal([]byte(raw), &v.Subscriptions); e != nil {
|
||||
return v, e
|
||||
}
|
||||
if e := json.Unmarshal([]byte(folders), &v.Folders); e != nil {
|
||||
return v, e
|
||||
}
|
||||
var e error
|
||||
v.Folders, e = FeedFolders(v.Subscriptions, v.Folders)
|
||||
return v, 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)
|
||||
}
|
||||
@@ -188,3 +188,41 @@ func TestFeedActionsMigrationRollbackAndRepeat(t *testing.T) {
|
||||
t.Fatal(status, e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedFoldersMigrationRollbackAndRepeat(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
ctx := context.Background()
|
||||
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", feedMigrations[:5]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
const catalog = `[{"id":"feed/1","title":"Title","categories":[{"id":"category","label":"Folder"}]}]`
|
||||
if _, e := st.DB.Exec(`INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,version,enabled,interval_seconds,lease,next_ms,remote_catalog) VALUES('s','d','u','freshrss','Title','','https://example.org',7,1,300,'worker',999,?);
|
||||
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,'queued',1)`, catalog); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
broken := append([]db.SQLMigration(nil), feedMigrations...)
|
||||
broken[5].Statements = append(append([]string(nil), feedMigrations[5].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='remote_folders'`).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)
|
||||
}
|
||||
}
|
||||
var version, next int
|
||||
var got, folders, lease, status string
|
||||
if e := st.DB.QueryRow(`SELECT version,next_ms,lease,remote_catalog,remote_folders FROM feed_sources WHERE uuid='s'`).Scan(&version, &next, &lease, &got, &folders); e != nil || version != 7 || next != 999 || lease != "worker" || got != catalog || folders != "[]" {
|
||||
t.Fatal("existing state changed", version, next, lease, got, folders, e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`SELECT status FROM feed_actions WHERE request_id='r'`).Scan(&status); e != nil || status != "queued" {
|
||||
t.Fatal("pending action changed", status, e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`PRAGMA integrity_check`).Scan(&status); e != nil || status != "ok" {
|
||||
t.Fatal(status, e)
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,34 @@ func ValidTaskWikiPrefix(p string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Expand only the documented placeholders. Subject is one safe path component,
|
||||
// never a source of separators or URI operators. Callers choose the timezone.
|
||||
func ExpandWikiPrefix(template, subject string, now time.Time) (string, error) {
|
||||
if len(template) > 500 || !utf8.ValidString(template) || !utf8.ValidString(subject) {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
name := strings.Map(func(r rune) rune {
|
||||
if unicode.IsControl(r) || unicode.IsSpace(r) || strings.ContainsRune(`/\?#%:{}<>"|`, r) {
|
||||
return '-'
|
||||
}
|
||||
return r
|
||||
}, subject)
|
||||
name = strings.Trim(name, " .-_")
|
||||
for len(name) > 180 {
|
||||
_, n := utf8.DecodeLastRuneInString(name)
|
||||
name = name[:len(name)-n]
|
||||
}
|
||||
name = strings.Trim(name, " .-_")
|
||||
if name == "" {
|
||||
name = "untitled"
|
||||
}
|
||||
result := strings.NewReplacer("{YYYY}", now.Format("2006"), "{MM}", now.Format("01"), "{DD}", now.Format("02"), "{Subject}", name).Replace(template)
|
||||
if strings.ContainsAny(result, "{}") || !ValidTaskWikiPrefix(result) {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// The CLI derives the request UUID from origin, user and Message-ID (or a raw
|
||||
// mail hash). Keep subjects in the title, never in the URL's identity segment.
|
||||
func TaskCaptureWikiPath(prefix, title, request string) string {
|
||||
|
||||
@@ -64,6 +64,7 @@ type TaskPreferences struct {
|
||||
Version int64 `json:"version"`
|
||||
ProjectUUID string `json:"project_uuid"`
|
||||
WikiPrefix string `json:"wiki_prefix"`
|
||||
RSSLinkMode string `json:"rss_link_mode"`
|
||||
AssigneeUUID string `json:"assignee_uuid"`
|
||||
DueDays *int `json:"due_days"`
|
||||
StartDays *int `json:"start_days"`
|
||||
@@ -80,7 +81,7 @@ type TaskPreferences struct {
|
||||
}
|
||||
|
||||
func (s *Store) TaskPreferences(ctx context.Context, domain, actor string) (TaskPreferences, error) {
|
||||
p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, ReminderTime: "09:00", DigestTime: "09:00", Timezone: "UTC"}
|
||||
p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, ReminderTime: "09:00", DigestTime: "09:00", Timezone: "UTC", RSSLinkMode: "tab"}
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return p, err
|
||||
}
|
||||
@@ -120,7 +121,13 @@ func (s *Store) SaveTaskPreferences(ctx context.Context, domain, actor string, p
|
||||
if s.ReadOnly {
|
||||
return p, ErrReadOnly
|
||||
}
|
||||
if !ValidTaskWikiPrefix(p.WikiPrefix) {
|
||||
if _, err := ExpandWikiPrefix(p.WikiPrefix, "subject", now); err != nil {
|
||||
return p, ErrTaskInvalid
|
||||
}
|
||||
if p.RSSLinkMode == "" {
|
||||
p.RSSLinkMode = "tab"
|
||||
}
|
||||
if p.RSSLinkMode != "tab" && p.RSSLinkMode != "embedded" {
|
||||
return p, ErrTaskInvalid
|
||||
}
|
||||
// Older clients do not send this field. Preserve their default clock.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExpandWikiPrefix(t *testing.T) {
|
||||
now := time.Date(2026, 12, 31, 18, 0, 0, 0, time.UTC).In(time.FixedZone("JST", 9*3600))
|
||||
for _, tt := range []struct{ template, subject, want string }{
|
||||
{"/notes/{YYYY}/{MM}/{DD}/{Subject}", "日本語 / ../ x?y#z", "/notes/2027/01/01/日本語---..--x-y-z"},
|
||||
{"/notes/{Subject}", "../", "/notes/untitled"},
|
||||
{"/notes/{Subject}", "{YYYY}", "/notes/YYYY"},
|
||||
{"/notes", "unused", "/notes"},
|
||||
{"", "", ""},
|
||||
} {
|
||||
got, err := ExpandWikiPrefix(tt.template, tt.subject, now)
|
||||
if err != nil || got != tt.want {
|
||||
t.Fatalf("%q: %q, %v; want %q", tt.template, got, err, tt.want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"/notes/{YY}", "/notes/{{Subject}}", "/notes/{Subject", "/a/../b/{YYYY}", "/_/api/{Subject}", "relative/{YYYY}"} {
|
||||
if _, err := ExpandWikiPrefix(bad, "subject", now); err == nil {
|
||||
t.Fatal("accepted", bad)
|
||||
}
|
||||
}
|
||||
got, err := ExpandWikiPrefix("/notes/{Subject}", strings.Repeat("日本語", 200), now)
|
||||
if err != nil || len(got) > len("/notes/")+180 || !ValidTaskWikiPrefix(got) {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
.feeds-page{height:100dvh;overflow:hidden;display:flex;flex-direction:column;background:var(--bg);color:var(--fg)}
|
||||
.feed-external{width:calc(100vw - 1.5rem);height:calc(100dvh - 1.5rem);max-width:none;max-height:none;box-sizing:border-box;margin:auto;padding:0;background:var(--bg,#111);color:var(--fg);border:1px solid var(--border,#8885);border-radius:.5rem;overflow:hidden}.feed-external[open]{display:flex;flex-direction:column}.feed-external::backdrop{background:#0009}.feed-external-bar{display:flex;align-items:center;gap:.5rem;padding:.3rem .5rem;flex-shrink:0}.feed-external-bar span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.feed-external-bar a{padding:.3rem;text-decoration:none;font-size:1.2rem}.feed-external iframe{flex:1;width:100%;min-height:0;border:0;background:#fff}@media(max-width:600px){.feed-external{width:100vw;height:100dvh;border:0;border-radius:0}}
|
||||
.feed-help{display:flex;align-items:center;gap:.5rem;padding:.25rem 0;font-size:.78rem;flex-shrink:0}.feed-help[hidden]{display:none}.feed-help span{flex:1;min-width:0;overflow-wrap:anywhere}.feed-help button{flex-shrink:0}
|
||||
.feed-capture{width:min(42rem,calc(100vw - 2rem));max-height:calc(100dvh - 2rem);box-sizing:border-box;overflow:auto;background:var(--bg,#111);color:var(--fg);border:1px solid var(--border,#8885);border-radius:.6rem;padding:1rem;box-shadow:0 1rem 4rem #0007}.feed-capture::backdrop{background:#0008}.feed-capture-heading{display:flex;align-items:center;justify-content:space-between;gap:.5rem}.feed-capture h2{font-size:1.05rem;margin:0}.feed-capture-heading,.feed-capture-field,.feed-capture-tokens,.feed-capture-destination,.feed-capture-actions,.feed-capture .feed-warning{grid-column:1/-1}#feeds-app .feed-capture form{grid-template-columns:1fr 1fr;gap:.65rem}#feeds-app .feed-capture .feed-capture-check{display:flex;align-items:center;gap:.4rem}#feeds-app .feed-capture input[type=checkbox]{width:1rem;min-height:1rem;flex-shrink:0}.feed-capture-check:has([name=confirm]){grid-column:1/-1}.feed-capture-tokens,.feed-capture-actions{display:flex;gap:.35rem;flex-wrap:wrap}.feed-capture-actions{justify-content:flex-end}.feed-capture-destination{font-size:.75rem;overflow-wrap:anywhere;opacity:.8}.feed-capture .feed-warning:empty{display:none}.feed-capture-field:has([name=prefix]){position:relative}.feed-capture-field:has([name=prefix]) a{position:absolute;right:.1rem;top:0;text-decoration:none}@media(max-width:600px){#feeds-app .feed-capture form{grid-template-columns:1fr}.feed-capture{padding:.75rem}}
|
||||
.feed-folder-row{display:flex;align-items:center;min-width:0}#feeds-app .feed-folder-toggle{flex:0 0 1.7rem;border:0;padding:.15rem;min-width:1.7rem}#feeds-app .feed-folder-name{display:flex;align-items:center;gap:.3rem;flex:1;min-width:0;text-align:left;border:0;font-size:.78rem;padding:.2rem}.feed-folder-name span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.feed-folder-name svg{width:1rem;height:1rem;flex-shrink:0;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linejoin:round}.feed-folder>.feed-subscriptions{padding-left:1.1rem;border-left:1px solid var(--border,#8885);margin-left:.8rem}.feed-catalog .feed-subscriptions[hidden]{display:none}.feed-folder small{font-size:.7rem;opacity:.7;padding:.3rem}.feed-catalog button[aria-current=true]{background:color-mix(in srgb,var(--accent,#659de4) 22%,transparent)!important}.feed-tree-all{width:100%;text-align:left}.feed-folders{min-width:0}
|
||||
.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}
|
||||
|
||||
+98
-27
@@ -10,7 +10,9 @@
|
||||
async function request(path,options={}){const response=await fetch(api+path,{credentials:'same-origin',cache:'no-store',...options,headers:{'Content-Type':'application/json',...options.headers}});if(response.redirected||response.status===401)throw Error(t('Please sign in again.','再度ログインしてください。'));const data=await response.json().catch(()=>({}));if(!response.ok)throw Error(response.status===412?t('Changed elsewhere or refresh is cooling down. Reload before retrying.','別の操作と競合したか、更新の待機時間中です。再読込して確認してください。'):t('Request failed: ','操作に失敗しました: ')+(data.error||response.status));return data;}
|
||||
const post=(path,body)=>request(path,{method:'POST',body:JSON.stringify(body)});
|
||||
let sources=[],items=[],selected=-1,currentSource='',filter='',search='',next=null,loading=false,seq=0,detailSeq=0,editing=false,controller,detailController;
|
||||
let remoteFeed='',remoteCategory='',catalog=[],catalogSeq=0,catalogController;
|
||||
let remoteFeed='',remoteCategory='',categoryMode='',catalog=[],catalogFolders=[],catalogLoaded=false,catalogSearch='',catalogSeq=0,catalogController;
|
||||
const folderStates=new Map();
|
||||
function folderState(source){if(folderStates.has(source))return folderStates.get(source);let state=new Set();try{const raw=localStorage.getItem('pageswiki.feed-folders.v1:'+source);if(raw&&raw.length<=1<<20){const saved=JSON.parse(raw);if(Array.isArray(saved)&&saved.length<=1001)state=new Set(saved.filter(x=>typeof x==='string'&&x.length<=2100));}}catch{}folderStates.set(source,state);return state;}
|
||||
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;
|
||||
@@ -24,12 +26,15 @@
|
||||
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);
|
||||
toolbar.append(button('?',t('Keyboard shortcuts','キー操作'),showHelp));
|
||||
const history=button('◷',t('Operation history','操作履歴'),actionHistory);history.id='feed-history';toolbar.append(history);
|
||||
const helpButton=button('?',t('Keyboard shortcuts','キー操作'),showHelp),help=el('div',undefined,'feed-help');help.id='feed-help';help.hidden=true;helpButton.setAttribute('aria-controls',help.id);helpButton.setAttribute('aria-expanded','false');
|
||||
help.append(el('span',t('j/k move · Enter read · Esc index · / search · n unread · m read/unread · * star · r refresh · ? / Esc close help','j/k 移動 · Enter 本文 · Esc 一覧 · / 検索 · n 次の未読 · m 既読/未読 · * star · r 更新 · ? / Esc ヘルプを閉じる')),button('×',t('Close help','ヘルプを閉じる'),hideHelp));status.before(help);toolbar.append(helpButton);
|
||||
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 hideHelp(){if(help.contains(document.activeElement))helpButton.focus();help.hidden=true;helpButton.setAttribute('aria-expanded','false');}
|
||||
function showHelp(){if(!help.hidden){hideHelp();return;}help.hidden=false;helpButton.setAttribute('aria-expanded','true');}
|
||||
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);
|
||||
@@ -37,33 +42,60 @@
|
||||
}
|
||||
}
|
||||
function drawCatalog(parent){
|
||||
const nav=el('div',undefined,'feed-catalog'),categories=el('select'),names=new Map();categories.ariaLabel=t('FreshRSS category','FreshRSSカテゴリ');categories.id='feed-category';
|
||||
for(const sub of catalog)for(const cat of sub.categories)names.set(cat.id,cat.label);
|
||||
for(const [id,name]of [['',t('All categories','すべてのカテゴリ')],...Array.from(names).sort((a,b)=>a[1].localeCompare(b[1]))]){const option=el('option',name);option.value=id;categories.append(option);}categories.value=remoteCategory;
|
||||
categories.onchange=()=>{remoteCategory=categories.value;remoteFeed='';drawSources();load(false).catch(report);};nav.append(categories);
|
||||
const find=el('input');find.type='search';find.placeholder=find.ariaLabel=t('Find subscription','購読を絞り込む');nav.append(find);
|
||||
const list=el('div',undefined,'feed-subscriptions');nav.append(list);parent.append(nav);
|
||||
const draw=()=>{list.replaceChildren();const subs=catalog.filter(sub=>(!remoteCategory||sub.categories.some(c=>c.id===remoteCategory))&&sub.title.toLocaleLowerCase().includes(find.value.toLocaleLowerCase())).sort((a,b)=>a.title.localeCompare(b.title));
|
||||
const add=(id,title)=>{const b=button(title,title,async()=>{remoteFeed=id;for(const node of list.children)node.setAttribute('aria-current',String(node===b));layout.classList.remove('sources-open');await load(false);});b.dataset.feed=id;b.setAttribute('aria-current',String(id===remoteFeed));list.append(b);};add('',t('All subscriptions','すべての購読'));for(const sub of subs)add(sub.id,sub.title||sub.id);
|
||||
if(!catalogLoaded)return;
|
||||
const nav=el('nav',undefined,'feed-catalog');nav.ariaLabel=t('FreshRSS folders','FreshRSSのフォルダ');const source=currentSource,state=folderState(source),groups=new Map();
|
||||
for(const c of catalogFolders)groups.set(c.id,{id:c.id,label:c.label,mode:'',subs:[]});
|
||||
const uncategorized={id:'',label:t('Uncategorized','未分類'),mode:'uncategorized',subs:[]};
|
||||
for(const sub of catalog){if(!sub.categories.length)uncategorized.subs.push(sub);for(const c of sub.categories){if(!groups.has(c.id))groups.set(c.id,{id:c.id,label:c.label,mode:'',subs:[]});groups.get(c.id).subs.push(sub);}}
|
||||
const ordered=[...groups.values()].sort((a,b)=>a.label.localeCompare(b.label)||a.id.localeCompare(b.id));if(uncategorized.subs.length)ordered.push(uncategorized);
|
||||
const key=g=>JSON.stringify([g.mode,g.id]),valid=new Set(ordered.map(key));for(const k of state)if(!valid.has(k))state.delete(k);
|
||||
const persist=()=>{try{localStorage.setItem('pageswiki.feed-folders.v1:'+source,JSON.stringify([...state]));}catch{}};
|
||||
const mark=()=>{for(const b of nav.querySelectorAll('button[data-category]'))b.setAttribute('aria-current',String((b.dataset.feed||'')===remoteFeed&&b.dataset.category===remoteCategory&&b.dataset.mode===categoryMode));};
|
||||
const choose=async(id,mode,feed='')=>{remoteCategory=id;categoryMode=mode;remoteFeed=feed;mark();layout.classList.remove('sources-open');await load(false);};
|
||||
const select=(label,g,feed='')=>{const b=button(label,label,()=>choose(g.id,g.mode,feed));b.dataset.category=g.id;b.dataset.mode=g.mode;if(feed)b.dataset.feed=feed;b.setAttribute('aria-current',String(feed===remoteFeed&&g.id===remoteCategory&&g.mode===categoryMode));return b;};
|
||||
const all=select(t('All subscriptions','すべての購読'),{id:'',mode:''});all.className='feed-tree-all';nav.append(all);
|
||||
const find=el('input');find.type='search';find.placeholder=find.ariaLabel=t('Find subscription / folder','購読・フォルダを検索');find.value=catalogSearch;nav.append(find);
|
||||
const list=el('div',undefined,'feed-folders');nav.append(list);parent.append(nav);
|
||||
function subscriptions(target,subs,g){let count=0;const sorted=[...subs].sort((a,b)=>a.title.localeCompare(b.title)||a.id.localeCompare(b.id));const more=button('↓',t('More subscriptions','購読元をさらに表示'),append);
|
||||
function append(){more.remove();for(const sub of sorted.slice(count,count+50)){const group=g||{id:'',mode:''},b=select(sub.title||sub.id,group,sub.id);b.title=(sub.title||sub.id)+(sub.categories.length?' · '+sub.categories.map(c=>c.label).join(' / '):'');target.append(b);}count+=50;if(count<sorted.length)target.append(more);}append();
|
||||
}
|
||||
const draw=()=>{list.replaceChildren();const query=find.value.trim().toLocaleLowerCase();catalogSearch=find.value;
|
||||
if(query){const matches=catalog.filter(s=>s.title.toLocaleLowerCase().includes(query)||s.categories.some(c=>c.label.toLocaleLowerCase().includes(query)));const results=el('div',undefined,'feed-subscriptions');list.append(results);subscriptions(results,matches,null);if(!matches.length)results.append(el('small',t('No subscriptions','購読なし')));return;}
|
||||
for(const g of ordered){const group=el('div',undefined,'feed-folder'),line=el('div',undefined,'feed-folder-row'),children=el('div',undefined,'feed-subscriptions');group.dataset.category=g.id;group.dataset.mode=g.mode;
|
||||
const name=select(g.label||g.id,g);name.className='feed-folder-name';name.title=(g.label||g.id)+(g.id?' · '+g.id:'');const label=el('span',g.label||g.id);name.replaceChildren();
|
||||
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','M3 6h7l2 3h9v11H3z');svg.append(path);name.append(svg,label);
|
||||
let open=state.has(key(g));const toggle=button('',t('Expand folder','フォルダを展開')+' · '+g.label,()=>{open=!open;if(open)state.add(key(g));else state.delete(key(g));persist();paint();});toggle.className='feed-folder-toggle';
|
||||
const paint=()=>{toggle.textContent=open?'▾':'▸';toggle.setAttribute('aria-expanded',String(open));toggle.title=toggle.ariaLabel=(open?t('Collapse folder','フォルダを折りたたむ'):t('Expand folder','フォルダを展開'))+' · '+g.label;children.hidden=!open;children.replaceChildren();if(open){subscriptions(children,g.subs,g);if(!g.subs.length)children.append(el('small',t('Empty folder','空のフォルダ')));}};
|
||||
line.append(toggle,name);group.append(line,children);list.append(group);paint();
|
||||
}mark();
|
||||
};find.oninput=draw;draw();
|
||||
}
|
||||
async function loadCatalog(){catalogController?.abort();catalogController=new AbortController();const version=++catalogSeq;catalog=[];if(sources.find(s=>s.uuid===currentSource)?.provider!=='freshrss')return;
|
||||
const data=await request('catalog?'+new URLSearchParams({source:currentSource}),{signal:catalogController.signal});if(version!==catalogSeq)return;catalog=data.subscriptions;drawSources();
|
||||
async function loadCatalog(){catalogController?.abort();catalogController=new AbortController();const version=++catalogSeq;catalogLoaded=false;catalog=[];catalogFolders=[];if(sources.find(s=>s.uuid===currentSource)?.provider!=='freshrss')return;
|
||||
const data=await request('catalog?'+new URLSearchParams({source:currentSource}),{signal:catalogController.signal});if(version!==catalogSeq)return;catalog=data.subscriptions;catalogFolders=data.folders||[];catalogLoaded=true;drawSources();
|
||||
}
|
||||
async function chooseSource(id){currentSource=id;remoteFeed=remoteCategory='';catalog=[];drawSources();layout.classList.remove('reading');editing=false;await Promise.all([loadCatalog(),load(false)]);if(sources.find(s=>s.uuid===id)?.provider!=='freshrss')layout.classList.remove('sources-open');}
|
||||
async function chooseSource(id){currentSource=id;remoteFeed=remoteCategory=categoryMode=catalogSearch='';catalog=[];catalogFolders=[];catalogLoaded=false;drawSources();layout.classList.remove('reading');editing=false;await Promise.all([loadCatalog(),load(false)]);if(sources.find(s=>s.uuid===id)?.provider!=='freshrss')layout.classList.remove('sources-open');}
|
||||
function rowNode(item,index){const row=el('div',undefined,'feed-row'+(item.read?'':' unread'));row.id='feed-row-'+index;row.setAttribute('role','option');row.setAttribute('aria-selected',String(index===selected));for(const text of [(item.starred?'★':item.read?' ':'●'),date(item.published_ms),item.feed||sources.find(s=>s.uuid===item.source)?.title||'',item.title||t('(Untitled)','(無題)')])row.append(el('span',text));row.title=item.title;row.onclick=()=>open(index).catch(report);return row;}
|
||||
function drawRows(){rows.replaceChildren(...items.map(rowNode));more.hidden=!next;more.textContent='↓';more.title=more.ariaLabel=t('More articles','続きを表示');if(!items.length)rows.append(el('p',t('No articles','記事なし'),'feed-warning'));}
|
||||
async function load(append){if(append&&(!next||loading))return;controller?.abort();controller=new AbortController();const version=++seq;loading=true;more.disabled=true;
|
||||
try{const q=new URLSearchParams({source:currentSource,filter,q:search,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='';
|
||||
try{const q=new URLSearchParams({source:currentSource,filter,q:search,feed:remoteFeed,category:remoteCategory,category_mode:categoryMode});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','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);
|
||||
async function reload(){sources=(await request('sources')).sources;if(!sources.some(s=>s.uuid===currentSource)){currentSource=remoteFeed=remoteCategory='';}drawSources();await loadCatalog();if(remoteCategory&&!catalog.some(s=>s.categories.some(c=>c.id===remoteCategory)))remoteCategory='';if(remoteFeed&&!catalog.some(s=>s.id===remoteFeed))remoteFeed='';drawSources();await load(false);}
|
||||
async function reload(){sources=(await request('sources')).sources;if(!sources.some(s=>s.uuid===currentSource)){currentSource=remoteFeed=remoteCategory=categoryMode='';}drawSources();await loadCatalog();if(remoteCategory&&!catalogFolders.some(c=>c.id===remoteCategory))remoteCategory='';if(remoteFeed&&!catalog.some(s=>s.id===remoteFeed))remoteFeed='';drawSources();await load(false);}
|
||||
async function queueRefresh(){const targets=sources.filter(s=>s.enabled&&(!currentSource||currentSource===s.uuid));for(const s of targets)await post('sources/'+s.uuid+'/refresh',{version:s.version});status.textContent=t('Refresh queued','更新を予約しました');}
|
||||
toolbar.append(button('⟳',t('Reload cached list','取得済み一覧を再読込'),reload));
|
||||
async function open(index){if(index<0||index>=items.length)return;editing=false;selected=index;detailController?.abort();detailController=new AbortController();const version=++detailSeq;for(const [i,row]of [...rows.querySelectorAll('.feed-row')].entries())row.setAttribute('aria-selected',String(i===index));rows.setAttribute('aria-activedescendant','feed-row-'+index);document.getElementById('feed-row-'+index)?.scrollIntoView({block:'nearest'});
|
||||
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);
|
||||
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 openArticleLink(event,href){
|
||||
if(root.dataset.linkMode!=='embedded'||event.button!==0||event.ctrlKey||event.metaKey||event.altKey||event.shiftKey)return;
|
||||
let url;try{url=new URL(href,location.href);}catch{return;}if(!['https:','http:'].includes(url.protocol)||url.origin===location.origin||url.username||url.password)return;
|
||||
event.preventDefault();const wasEditing=editing;editing=true;detailSeq++;clearTimeout(actionTimer);
|
||||
const dialog=el('dialog',undefined,'feed-external'),bar=el('div',undefined,'feed-external-bar'),name=el('span',url.hostname),external=el('a','↗'),frame=el('iframe');dialog.ariaLabel=t('Original article preview','原文プレビュー');name.title=url.href;
|
||||
external.href=url.href;external.target='_blank';external.rel='noopener noreferrer';external.title=external.ariaLabel=t('Open in a new tab if embedding is blocked','埋め込みできない場合は新しいタブで開く');
|
||||
const close=button('×',t('Close preview','プレビューを閉じる'),()=>dialog.close());bar.append(name,external,close);frame.title=dialog.ariaLabel;frame.setAttribute('sandbox','allow-scripts');frame.referrerPolicy='no-referrer';frame.src=url.href;dialog.append(bar,frame);root.append(dialog);
|
||||
dialog.addEventListener('keydown',e=>e.stopPropagation());dialog.addEventListener('close',()=>{frame.src='about:blank';dialog.remove();editing=wasEditing;const item=items[selected];if(item&&!editing)pollAction(item);});dialog.showModal();close.focus();
|
||||
}
|
||||
function renderItem(item){reader.replaceChildren();const actions=el('div',undefined,'feed-actions');actions.append(button('←',t('Back to list','一覧へ戻る'),closeReader));
|
||||
const canWrite=item.provider==='local'||sources.some(s=>s.uuid===item.source&&s.enabled&&s.write_enabled);
|
||||
@@ -71,12 +103,15 @@
|
||||
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);}
|
||||
const original=actions.querySelector('.feed-original');if(original)original.addEventListener('click',e=>openArticleLink(e,original.href));
|
||||
if(item.url&&root.dataset.shareX==='true'){const share=el('a',undefined,'feed-share-x feed-original');share.title=share.ariaLabel=t('Share original article on X','原文の記事をXでシェア');share.href='https://twitter.com/intent/tweet?'+new URLSearchParams({text:item.title||'',url:item.url});share.target='_blank';share.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','M18 3h3l-7 8 8 10h-6l-5-7-6 7H2l7-9L2 3h6l5 6z');svg.append(path);share.append(svg);actions.append(share);}
|
||||
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'&&!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)','(本文なし)');
|
||||
if(body.shadowRoot)body.shadowRoot.addEventListener('click',e=>{const link=e.target.closest?.('a[href]');if(link)openArticleLink(e,link.href);});
|
||||
reader.append(body);
|
||||
pollAction(item);
|
||||
}
|
||||
@@ -84,6 +119,32 @@
|
||||
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);
|
||||
@@ -126,22 +187,32 @@
|
||||
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メモ・タスク')));
|
||||
editing=true;detailSeq++;clearTimeout(actionTimer);const dialog=el('dialog',undefined,'feed-capture'),form=el('form');dialog.ariaLabel=t('Capture Wiki / task','Wiki・タスク追加');reader.append(dialog);dialog.append(form);
|
||||
const close=()=>{if(!busy)dialog.close();},heading=el('div',undefined,'feed-capture-heading');heading.append(el('h2',t('Capture Wiki / task','Wiki・タスク追加')),button('×',t('Close','閉じる'),close));form.append(heading);
|
||||
dialog.addEventListener('close',()=>{clearTimeout(previewTimer);generation++;dialog.remove();editing=false;pollAction(item);});dialog.addEventListener('cancel',e=>{if(busy)e.preventDefault();});dialog.addEventListener('keydown',e=>e.stopPropagation());
|
||||
const title=field(form,t('Title','件名'),item.title.slice(0,250));title.required=true;title.maxLength=300;
|
||||
const task=field(form,t('Also create a task','タスクを作成する'),'','checkbox');task.disabled=root.dataset.tasks!=='true';
|
||||
const prefix=field(form,t('Wiki parent Path (empty = task only)','Wikiの親Path(空ならタスクのみ)'),'');prefix.placeholder='/notes/feeds';prefix.required=true;
|
||||
const prefix=field(form,t('Wiki parent Path (empty = task only)','Wikiの親Path(空ならタスクのみ)'),root.dataset.wikiPrefix||'');prefix.placeholder='/notes/feeds';prefix.required=true;prefix.maxLength=500;
|
||||
if(root.dataset.tasks==='true'){const settings=el('a','⚙');settings.href='/-/sys/config?panel=organizer';settings.target='_blank';settings.rel='noopener';settings.title=settings.ariaLabel=t('Configure default Wiki parent path in personal settings','個人設定で既定のWiki親Pathを設定');prefix.parentElement.append(settings);}
|
||||
const tokens=el('div',undefined,'feed-capture-tokens');for(const token of ['{YYYY}','{MM}','{DD}','{Subject}'])tokens.append(button(token,t('Insert ','挿入: ')+token,()=>{prefix.setRangeText(token,prefix.selectionStart??prefix.value.length,prefix.selectionEnd??prefix.value.length,'end');prefix.dispatchEvent(new Event('input',{bubbles:true}));prefix.focus();}));form.append(tokens);
|
||||
const destination=el('output',undefined,'feed-capture-destination');destination.ariaLabel=t('Destination','保存先');form.append(destination);
|
||||
const notes=field(form,t('Your note','メモ'));const copy=field(form,t('Include cached text (explicit copy)','取得済み本文も保存する(明示コピー)'),'','checkbox');
|
||||
const confirm=field(form,t('I checked the destination publication policy and the material to copy.','保存先の公開範囲と、コピーする内容を確認しました。'),'','checkbox');confirm.required=true;
|
||||
const validate=()=>{prefix.required=!task.checked;confirm.required=!!prefix.value.trim()||!task.checked;};task.onchange=prefix.oninput=validate;
|
||||
const save=el('button',t('Create','作成'));save.type='submit';form.append(save,button(t('Cancel','取消'),'',()=>{editing=false;renderItem(item);}));let pending=null;
|
||||
form.onsubmit=async event=>{event.preventDefault();const body='Source: '+item.url+'\nFeed: '+item.feed+'\n\n'+notes.value+(copy.checked?'\n\n'+item.body:'');const spec={title:title.value,notes:notes.value,prefix:prefix.value.trim(),body,task:task.checked};const fingerprint=JSON.stringify(spec);if(!pending||pending.fingerprint!==fingerprint)pending={fingerprint,request_id:crypto.randomUUID()};save.disabled=true;
|
||||
for(const [name,input]of Object.entries({title,task,prefix,notes,copy,confirm})){input.name=name;if(input.type==='checkbox')input.parentElement.classList.add('feed-capture-check');else input.parentElement.classList.add('feed-capture-field');}
|
||||
const notice=el('p',undefined,'feed-warning');notice.role='status';const actions=el('div',undefined,'feed-capture-actions'),save=el('button',t('Create','作成'));save.type='submit';actions.append(button(t('Cancel','取消'),'',close),save);form.append(notice,actions);
|
||||
let pending=null,generation=0,previewTimer,resolved=null,busy=false;const requestID=crypto.randomUUID();
|
||||
const preview=()=>{clearTimeout(previewTimer);const n=++generation;resolved=null;confirm.checked=false;prefix.required=!task.checked;confirm.required=!!prefix.value.trim()||!task.checked;save.disabled=true;notice.textContent='';destination.textContent='';
|
||||
if(!prefix.value.trim()){resolved='';destination.textContent=task.checked?t('Task only','タスクのみ'):'';save.disabled=!task.checked;return;}
|
||||
previewTimer=setTimeout(async()=>{try{const data=await post('capture-preview',{prefix:prefix.value.trim(),title:title.value});if(n!==generation||!dialog.isConnected)return;resolved=data.prefix;destination.textContent=resolved.replace(/\/$/,'')+'/'+(task.checked?'mail-':'rss-')+requestID;save.disabled=false;}catch(e){if(n===generation&&dialog.isConnected){notice.textContent=t('Check the parent Path and placeholders.','親Pathとプレースホルダを確認してください。');}}},180);
|
||||
};task.onchange=prefix.oninput=title.oninput=preview;copy.onchange=()=>{confirm.checked=false;};dialog.showModal();preview();title.focus();
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy||resolved===null||!form.reportValidity())return;const body='Source: '+item.url+'\nFeed: '+item.feed+'\n\n'+notes.value+(copy.checked?'\n\n'+item.body:'');const spec={title:title.value,notes:notes.value,prefix:resolved,body,task:task.checked};const fingerprint=JSON.stringify(spec);if(!pending||pending.fingerprint!==fingerprint)pending={fingerprint,request_id:requestID};busy=true;save.disabled=true;
|
||||
try{let data;if(task.checked){const input={request_id:pending.request_id,title:title.value,notes:(notes.value+'\nSource: '+item.url).trim()};if(spec.prefix){input.wiki_prefix=spec.prefix;input.wiki_body=body;}const res=await fetch('/_/api/v1/extension/organizer.tasks/capture',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(input)});data=await res.json().catch(()=>({}));if(!res.ok||res.redirected)throw Error(t('Capture failed: ','作成に失敗: ')+(data.error||res.status));}
|
||||
else data=await post('note',{request_id:pending.request_id,source:item.source,id:item.id,path:spec.prefix.replace(/\/$/,'')+'/rss-'+pending.request_id,title:title.value,body,confirm_publication:confirm.checked});
|
||||
reader.replaceChildren(el('p',t('Created.','作成しました。')));if(data.item){const a=el('a',t('Open task','タスクを開く'));a.href='/v/plan/task/'+encodeURIComponent(data.item.uuid);reader.append(a);}const page=data.page_uuid||data.item?.page_uuid;if(page){const a=el('a',t('Open Wiki','Wikiを開く'));a.href='/v/uuid:'+encodeURIComponent(page);reader.append(el('p'),a);}editing=false;
|
||||
}catch(e){report(e);}finally{save.disabled=false;}
|
||||
dialog.replaceChildren(el('h2',t('Created','作成しました')));if(data.item){const a=el('a',t('Open task','タスクを開く'));a.href='/v/plan/task/'+encodeURIComponent(data.item.uuid);dialog.append(a);}const page=data.page_uuid||data.item?.page_uuid;if(page){const a=el('a',t('Open Wiki','Wikiを開く'));a.href='/v/uuid:'+encodeURIComponent(page);dialog.append(el('p'),a);}const done=button(t('Close','閉じる'),'',close);dialog.append(el('p'),done);done.focus();
|
||||
}catch(e){notice.textContent=e.message;}finally{busy=false;save.disabled=resolved===null;}
|
||||
};
|
||||
}
|
||||
document.addEventListener('keydown',event=>{if(event.defaultPrevented||event.isComposing||event.ctrlKey||event.altKey||event.metaKey)return;const input=event.target.closest?.('input,textarea,select,[contenteditable=true]');if(input){if(event.key==='Escape'){event.target.blur();event.preventDefault();}return;}if(event.key==='Enter'&&event.target.closest?.('button,a'))return;if(editing){if(event.key==='Escape'){closeReader();event.preventDefault();}return;}
|
||||
document.addEventListener('keydown',event=>{if(event.defaultPrevented||event.isComposing||event.ctrlKey||event.altKey||event.metaKey)return;if(event.key==='Escape'&&!help.hidden){hideHelp();event.preventDefault();return;}const input=event.target.closest?.('input,textarea,select,[contenteditable=true]');if(input){if(event.key==='Escape'){event.target.blur();event.preventDefault();}return;}if(event.key==='?'&&!help.hidden){hideHelp();event.preventDefault();return;}if(event.key==='Enter'&&event.target.closest?.('button,a'))return;if(editing){if(event.key==='Escape'){closeReader();event.preventDefault();}return;}
|
||||
let action;switch(event.key){case 'j':case 'ArrowDown':action=()=>open(Math.min(items.length-1,selected+1));break;case 'k':case 'ArrowUp':action=()=>open(Math.max(0,selected-1));break;case 'Enter':case 'l':action=()=>open(Math.max(0,selected));break;case 'Escape':case 'h':action=closeReader;break;case '/':action=()=>searchbox.focus();break;case 'r':if(writable)action=queueRefresh;break;case 'm':action=()=>setState(!items[selected]?.read,!!items[selected]?.starred);break;case '*':action=()=>setState(!!items[selected]?.read,!items[selected]?.starred);break;case 'n':action=()=>{const i=items.findIndex((x,i)=>i>selected&&!x.read);if(i>=0)return open(i);};break;case '?':action=showHelp;break;}if(action){event.preventDefault();Promise.resolve().then(action).catch(report);}
|
||||
});
|
||||
(async()=>{const q=new URLSearchParams(location.search);currentSource=q.get('source')||'';await reload();if(q.has('settings')&&writable){sourceForm();return;}if(q.has('id')&¤tSource){let index=items.findIndex(x=>x.source===currentSource&&x.id===q.get('id'));if(index<0){const data=await request('item?'+new URLSearchParams({source:currentSource,id:q.get('id')}));items.unshift(data.item);index=0;drawRows();}await open(index);}})().catch(report);
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
const word={tasks:['Tasks','タスク'],report:['Activity report','達成度・作業レポート'],settings:['Task defaults and email','タスクの既定値・メール'],contacts:['Contacts','連絡先'],completed:['Completed','完了件数'],points:['Points','ポイント'],work:['Work hours','作業時間'],focus:['Pomodoro hours','集中時間'],save:['Save','保存'],saved:['Saved','保存しました'],refresh:['Refresh','更新'],project_uuid:['Default project','既定のプロジェクト'],assignee_uuid:['Assignee UUID (annotation only)','担当者UUID(管理用メモ)'],due_days:['Due in days','期限までの日数'],start_days:['Start in days','着手までの日数'],planned_days:['Plan in days','取り組む日までの日数'],review_days:['Review in days','見直しまでの日数'],estimate_minutes:['Estimated minutes','見込み工数(分)'],complexity:['Complexity (1–5)','複雑度(1〜5)'],digest_enabled:['Email daily task list to my account email','毎日のやることリストを自分のメールに送る'],digest_time:['Delivery time','配信時刻'],timezone:['IANA timezone','タイムゾーン(IANA)'],none:['None','なし'],empty:['No records in this period.','この期間の記録はありません。'],partial:['Partial results: narrow the period.','件数上限に達しました。期間を狭めてください。'],error:['Request failed. Input is retained.','処理に失敗しました。入力は保持しています。'],email_required:['Set your account email first.','先にプロフィールにメールアドレスを設定してください。'],smtp_unavailable:['Ask an administrator to configure SMTP.','管理者によるSMTP設定が必要です。']};
|
||||
const t=k=>(word[k]||[k,k])[ja?1:0],el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
|
||||
Object.assign(word,{notify_due:['Notify on due dates','期限日に通知する'],notify_planned:['Notify on planned dates','取り組む日に通知する'],reminder_time:['Default notification time','通知の既定時刻']});
|
||||
Object.assign(word,{wiki_prefix:['Default Wiki parent path for mail','メール本文の既定Wiki親Path']});
|
||||
Object.assign(word,{wiki_prefix:['Default Wiki parent path for mail / RSS','メール・RSS取り込みの既定Wiki親Path']});
|
||||
Object.assign(word,{rss_link_mode:['Open RSS article links','RSSの記事リンクの開き方']});
|
||||
const status=root.querySelector('#productivity-status'),content=root.querySelector('#productivity-content');
|
||||
root.querySelectorAll('[data-word]').forEach(n=>n.textContent=t(n.dataset.word));root.querySelector('h1,h2,h3').textContent=t(root.dataset.view==='settings'?'settings':'report');
|
||||
async function request(path,options={}){const timeout=AbortSignal.timeout(15000);const r=await fetch(api+path,{credentials:'same-origin',cache:'no-store',signal:signal?AbortSignal.any([signal,timeout]):timeout,...options,headers:{'Content-Type':'application/json',...options.headers}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t(d.error||'error'));return d;}
|
||||
@@ -14,11 +15,12 @@
|
||||
const data=await request('preferences'),p=data.preferences;const form=el('form');form.className='productivity-settings';const fields={};
|
||||
const projects=await request('items?kind=project&view=all&limit=100');
|
||||
if(p.project_uuid&&!projects.items.some(x=>x.uuid===p.project_uuid)){try{const current=await request('items/'+encodeURIComponent(p.project_uuid));if(current.item.kind==='project')projects.items.unshift(current.item);}catch{ /* Keep the saved reference visible without exposing inaccessible data. */ }}
|
||||
for(const key of ['project_uuid','wiki_prefix','assignee_uuid','due_days','start_days','planned_days','review_days','estimate_minutes','complexity','notify_due','notify_planned','reminder_time','digest_enabled','digest_time','timezone']){
|
||||
for(const key of ['project_uuid','wiki_prefix','rss_link_mode','assignee_uuid','due_days','start_days','planned_days','review_days','estimate_minutes','complexity','notify_due','notify_planned','reminder_time','digest_enabled','digest_time','timezone']){
|
||||
if(key==='notify_due')form.append(el('h3',ja?'新規タスクのInbox通知':'Inbox reminders for new tasks'));
|
||||
if(key==='digest_enabled')form.append(el('h3',ja?'日次メール':'Daily email'));
|
||||
const label=el('label',t(key));label.className='productivity-setting';const input=el(key==='project_uuid'?'select':'input');input.name=key;
|
||||
const label=el('label',t(key));label.className='productivity-setting';const input=el(['project_uuid','rss_link_mode'].includes(key)?'select':'input');input.name=key;
|
||||
if(key==='project_uuid'){const empty=el('option',t('none'));empty.value='';input.append(empty);for(const item of projects.items){const option=el('option',item.title);option.value=item.uuid;input.append(option);}if(p[key]&&!projects.items.some(x=>x.uuid===p[key])){const current=el('option',p[key]);current.value=p[key];input.append(current);}}
|
||||
else if(key==='rss_link_mode'){for(const [value,label]of [['tab',ja?'新しいタブ':'New tab'],['embedded',ja?'本文上のポップアップ':'Popup over article']]){const option=el('option',label);option.value=value;input.append(option);}p[key] ||= 'tab';}
|
||||
else if(['digest_enabled','notify_due','notify_planned'].includes(key)){input.type='checkbox';input.checked=!!p[key];input.setAttribute('role','switch');}
|
||||
else if(key.endsWith('_days')||['estimate_minutes','complexity'].includes(key)){input.type='number';input.min=key==='complexity'?1:0;input.max=key.endsWith('_days')?3650:key==='complexity'?5:10080;input.step=1;}
|
||||
else input.type=['digest_time','reminder_time'].includes(key)?'time':'text';
|
||||
@@ -26,7 +28,7 @@
|
||||
if(key==='project_uuid')for(const option of input.options)option.defaultSelected=option.selected=option.value===(p.project_uuid||'');
|
||||
else if(input.type==='checkbox')input.defaultChecked=input.checked;
|
||||
else input.defaultValue=input.value;
|
||||
if(key==='wiki_prefix'){input.placeholder='/private/mail';input.maxLength=500;const help=el('p',ja?'メール本文をWikiに保存する親Pathです。空欄ならプロジェクトのWiki配下を使います。保存した本文はそのPathの公開範囲・閲覧権限に従います。':'Parent path for mail Wiki pages. If blank, use the project Wiki subtree. Saved mail inherits the destination path’s visibility and read permissions.');help.className='productivity-note';form.append(help);}
|
||||
if(key==='wiki_prefix'){input.placeholder='/notes/{YYYY}/{MM}/{Subject}';input.maxLength=500;const help=el('p',ja?'メール・RSS取り込みの保存先。{YYYY}・{MM}・{DD}は作成日(ドメインのタイムゾーン)、{Subject}は件名です。RSSでは入力欄を空にすればタスクのみ作成できます。設定が空欄の場合、メールはプロジェクトのWiki配下を使い、RSSは未入力になります。保存内容はそのPathの公開範囲・閲覧権限に従います。':'Mail / RSS capture destination. {YYYY}, {MM}, {DD} use the creation date in the Domain timezone; {Subject} uses the title. Clear the RSS field for task-only capture. If unset, mail uses the project Wiki subtree and RSS leaves the field blank. Content inherits destination visibility and permissions.');help.className='productivity-note';form.append(help);}
|
||||
if(key==='reminder_time'){const help=el('p',ja?'新規タスクの対応する日付が設定されている場合だけ通知します。既存タスクは変更しません。通知時刻は保存時のドメインのタイムゾーン('+data.timezone+')を使用します。':'Reminders apply only to new tasks with the corresponding date. Existing tasks are unchanged. Times use the Domain timezone on save ('+data.timezone+').');help.className='productivity-note';form.append(help);}
|
||||
}
|
||||
const note=el('p',ja?'日数は作成日からの暦日です。空欄は未設定、0は当日。担当者の指定では閲覧権限は付与されません。メールは今日の計画・期限到来分を最大100件送ります。SMTPは管理者設定を使用し、配信時刻にはキュー待ちの遅延があります。':'Offsets are calendar days from creation; blank means unset, 0 means today. Assignment does not grant access. Email includes up to 100 tasks planned or due today, using administrator SMTP settings. Queue delays may apply.');note.className='productivity-note';form.append(note);
|
||||
|
||||
@@ -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=8"></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 }}">
|
||||
<main id="feeds-app" data-writable="{{ .FeedWritable }}" data-tasks="{{ .TasksEnabled }}" data-wiki-prefix="{{ .FeedWikiPrefix }}" data-share-x="{{ .FeedShareX }}" data-link-mode="{{ .FeedLinkMode }}">
|
||||
<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=5" defer></script></body></html>{{ end }}
|
||||
</main><script src="/static/js/feeds.js?v=8" defer></script></body></html>{{ end }}
|
||||
@@ -4,4 +4,4 @@
|
||||
{{ template "organizer-nav" . }}
|
||||
<main id="organizer-dashboard" data-writable="{{ .TaskWritable }}" data-calendar="{{ .CalendarEnabled }}" data-today="{{ .Today }}" data-timezone="{{ .Timezone }}">
|
||||
<header class="dashboard-toolbar"><div><h1>{{ T "organizer.dashboard" }}</h1><small>{{ .Today }} · {{ .Timezone }}</small></div><div id="dashboard-controls"></div></header><p id="dashboard-status" role="status" aria-live="polite"></p><div id="dashboard-grid"></div>
|
||||
</main><script src="/static/js/organizer-dashboard.js?v=1" defer></script><script src="/static/js/task-productivity.js?v=6" defer></script></body></html>{{ end }}
|
||||
</main><script src="/static/js/organizer-dashboard.js?v=1" defer></script><script src="/static/js/task-productivity.js?v=7" defer></script></body></html>{{ end }}
|
||||
@@ -6,4 +6,4 @@
|
||||
{{ if .FeedsEnabled }}<section><h2>{{ T "feeds.title" }}</h2><p>{{ T "feeds.help" }}</p><a href="/v/feeds?settings=1">⚙ {{ T "feeds.title" }}</a></section>{{ end }}
|
||||
{{ if .TasksEnabled }}<section id="task-productivity" data-view="settings" data-writable="{{ .TaskWritable }}"><h2></h2><p id="productivity-status" role="status" aria-live="polite"></p><div id="productivity-content"></div></section><section id="task-digest-history" data-writable="{{ .TaskWritable }}"></section>{{ end }}
|
||||
{{ if .CalendarEnabled }}<section id="organizer-calendar-defaults" data-writable="{{ .TaskWritable }}"><h2>{{ T "organizer.calendar_defaults" }}</h2><p role="status"></p><div data-calendar-defaults></div></section>{{ end }}
|
||||
</section></div></main><script src="/static/js/task-productivity.js?v=6" defer></script><script src="/static/js/task-digest-history.js?v=1" defer></script><script src="/static/js/organizer-settings.js?v=1" defer></script></body></html>{{ end }}
|
||||
</section></div></main><script src="/static/js/task-productivity.js?v=7" defer></script><script src="/static/js/task-digest-history.js?v=1" defer></script><script src="/static/js/organizer-settings.js?v=1" defer></script></body></html>{{ end }}
|
||||
Reference in new issue
Block a user