Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19e12f96a8 | ||
|
|
433169c7e7 | ||
|
|
8988e5a2f8 | ||
|
|
b4792bb175 | ||
|
|
50b8b0323f |
No files matched your search
@@ -9,6 +9,8 @@ language-neutral; existing English source documents remain here for traceability
|
|||||||
and future aligned translations, not as automatically current English editions.
|
and future aligned translations, not as automatically current English editions.
|
||||||
|
|
||||||
- Concepts and boundaries: chapters 1–6.
|
- Concepts and boundaries: chapters 1–6.
|
||||||
|
- [Task capture, work reporting and private address book](ja/task-productivity-contacts.md):
|
||||||
|
shared Web/CLI API, neomutt, defaults, daily digest and home search commands.
|
||||||
- Existing product and runtime: chapters 7–11.
|
- Existing product and runtime: chapters 7–11.
|
||||||
- Organizer / task / calendar / RSS / mail / HTML editing proposals: chapters 12–17.
|
- Organizer / task / calendar / RSS / mail / HTML editing proposals: chapters 12–17.
|
||||||
- Operations, i18n, ordered work, decisions and sources: chapters 18–22.
|
- Operations, i18n, ordered work, decisions and sources: chapters 18–22.
|
||||||
|
|||||||
@@ -1,5 +1,20 @@
|
|||||||
# Architecture Implementation Roadmap
|
# Architecture Implementation Roadmap
|
||||||
|
|
||||||
|
## Task productivity and private contacts (2026-11-01)
|
||||||
|
|
||||||
|
- [x] Add idempotent task capture API and neomutt configuration reference.
|
||||||
|
- [x] Extend pages-cli with task planning, start/stop records, reports and private contact lookup.
|
||||||
|
- [x] Add per-user defaults, accomplishment heatmap and opt-in daily SMTP task digest.
|
||||||
|
- [x] Add home search commands with project/calendar suggestions and explicit creation confirmation.
|
||||||
|
- [x] Add private contacts CRUD, trash/restore, vCard import/export and unknown-property preservation.
|
||||||
|
- [x] Add private CardDAV serving with isolated credentials, conditional writes, bounded reports and sync tokens; revision preview/restore and whole-book export (2026-11-02).
|
||||||
|
- [ ] Shared address books, external CardDAV connectors, physical-device compatibility, work-record corrections and manual digest retry.
|
||||||
|
|
||||||
|
See [CardDAV operation and limits](../operations/carddav-contacts.md). The private profile is not full CardDAV compliance; production rollout is tracked separately.
|
||||||
|
|
||||||
|
See [contracts and remaining scope](ja/task-productivity-contacts.md). These checks describe
|
||||||
|
the implemented slice; production rollout and test evidence are recorded separately.
|
||||||
|
|
||||||
## Current highest priority (2026-10-31)
|
## Current highest priority (2026-10-31)
|
||||||
|
|
||||||
The user-prioritized [daily UX / browser / editor / CLI backlog](ja/priority-ux-20261031.md)
|
The user-prioritized [daily UX / browser / editor / CLI backlog](ja/priority-ux-20261031.md)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 14. 予定・iCalendar・CalDAV・連絡先
|
# 14. 予定・iCalendar・CalDAV・連絡先
|
||||||
|
|
||||||
状態:カレンダー部分は2026-09-22にローカル正本・Plan UI・限定CalDAVを実装開始。最新の契約・実装範囲・残作業は [カレンダー詳細設計](calendar-implementation.md) を参照。以下の旧順序/URI案より同設計を優先する。連絡先と外部同期は引き続き設計案。
|
状態:カレンダー部分は2026-09-22にローカル正本・Plan UI・限定CalDAVを実装開始。最新の契約・実装範囲・残作業は [カレンダー詳細設計](calendar-implementation.md) を参照。2026-11-01に個人アドレス帳のCRUD・vCard入出力・neomutt検索、2026-11-02に個人CardDAV提供・履歴復元・一括exportを実装した。[個人アドレス帳の実装契約](task-productivity-contacts.md)と[CardDAV運用](../../operations/carddav-contacts.md)を以下の旧URI案より優先する。共有アドレス帳と外部CardDAV connectorは引き続き設計案。
|
||||||
|
|
||||||
## 四つのレイヤー
|
## 四つのレイヤー
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ address bookの所有者・共有範囲、contact UUID、remote UID、複数メ
|
|||||||
|
|
||||||
## URL/API案と実装順
|
## URL/API案と実装順
|
||||||
|
|
||||||
人向けは `/v/organizer`、APIは `/_/api/v1/extension/organizer.{calendar|contacts}/…` を候補とします。**未実装・未予約**です。DAV提供面はroot discovery、認証、標準メソッドとルーターの衝突を調査してから決めます。Wiki PathをそのままDAV collectionにしません。
|
旧案の `/v/organizer` ではなく、連絡先の実装は `/v/plan/contacts`、APIは `/_/api/v1/extension/organizer.contacts/`、CardDAV提供面は `/_/api/v1/carddav/` を使います。Wiki PathをそのままDAV collectionにしません。以下の順序案のうち、個人アドレス帳と限定DAV提供は実装済み、共有と外部connectorは後続です。
|
||||||
|
|
||||||
1. ICS/vCard fixture、入出力preview、警告、重複防止。
|
1. ICS/vCard fixture、入出力preview、警告、重複防止。
|
||||||
2. local calendar/agenda・連絡先一覧、権限・version試験。
|
2. local calendar/agenda・連絡先一覧、権限・version試験。
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
## この設計書の読み方
|
## この設計書の読み方
|
||||||
|
|
||||||
|
2026-11-01追加:[タスク作成・作業記録・達成度レポート・日次メール・個人アドレス帳](task-productivity-contacts.md)。[neomuttとCLIの操作リファレンス](../../operations/neomutt-tasks.md)も参照。
|
||||||
|
|
||||||
- **実装済み**:利用できる機能の範囲。関連する制約や未監査部分も併記します。
|
- **実装済み**:利用できる機能の範囲。関連する制約や未監査部分も併記します。
|
||||||
- **設計案**:今回具体化した方針。API・テーブル・既定値は、実装や互換性試験で確定させます。
|
- **設計案**:今回具体化した方針。API・テーブル・既定値は、実装や互換性試験で確定させます。
|
||||||
- **TODO**:未実装の作業。記述やURL例が存在しても利用可能とは限りません。
|
- **TODO**:未実装の作業。記述やURL例が存在しても利用可能とは限りません。
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
||||||
|
|
||||||
v0.3.0のOIDCログインは利用者の動作確認済み。後続変更として、OIDC承認時の追加ローカルTOTPを廃止し、CLIの `auto` 言語選択と既存Pageの新規言語版編集を実装した。この後続変更はソース段階であり、本番サーバー/PATH上のCLIには未反映。
|
v0.3.0のOIDCログインは利用者の動作確認済み。v0.4.0ではOIDC承認時の追加ローカルTOTPを廃止し、CLIの `auto` 言語選択と既存Pageの新規言語版編集を実装した。2026-11-01 21:48 JSTに本番サーバー/PATH上のCLIへ反映済み。[v0.4.0反映記録](../../operations/deployments/2026-11-01-v0.4.0.md)。
|
||||||
|
|
||||||
## 原設計との整合
|
## 原設計との整合
|
||||||
|
|
||||||
@@ -169,7 +169,7 @@ OIDC無効の403と区別する。エラー時のログイン要求は自動再
|
|||||||
同日の後続変更でも全Goテスト(キャッシュなし)、全Go vet、CLI関連store/serverのrace検査、
|
同日の後続変更でも全Goテスト(キャッシュなし)、全Go vet、CLI関連store/serverのrace検査、
|
||||||
Python 22件、承認画面と既存CookieログインのChromium試験が成功した。
|
Python 22件、承認画面と既存CookieログインのChromium試験が成功した。
|
||||||
`TestRemoteCLILanguageForkRequiresWritePermission`で、有効なreadonlyセッションからの言語版作成が403になり、Revisionが残らないことも確認した。
|
`TestRemoteCLILanguageForkRequiresWritePermission`で、有効なreadonlyセッションからの言語版作成が403になり、Revisionが残らないことも確認した。
|
||||||
この後続変更は未リリース・未デプロイであり、上記v0.3.0の反映記録とは区別する。
|
この後続変更はv0.4.0で配布し、同日21:48 JSTに本番へ反映した。実ユーザーの文書編集は行わず、利用者による操作確認に委ねる。
|
||||||
|
|
||||||
ソースのチェックポイント:`.deployment-backups/dev-cli-oidc-20261101/source-after.tar.gz`
|
ソースのチェックポイント:`.deployment-backups/dev-cli-oidc-20261101/source-after.tar.gz`
|
||||||
(SHA-256 `3e4228cd53b4220dffe43a80b4ed02c0bd757a8b3845829b7d3a77a64b0e9c4b`)。
|
(SHA-256 `3e4228cd53b4220dffe43a80b4ed02c0bd757a8b3845829b7d3a77a64b0e9c4b`)。
|
||||||
@@ -181,5 +181,5 @@ OIDC関連18ファイルのみで、本番DB・鍵・セッション・前段の
|
|||||||
1. Ctrl+Pによる検索選択、補完の引用文字/途中カーソル対応、永続履歴の明示opt-in。
|
1. Ctrl+Pによる検索選択、補完の引用文字/途中カーソル対応、永続履歴の明示opt-in。
|
||||||
2. 新規Page+Path+初回Revisionの原子的な作成API、create/upload-only権限、並行作成の衝突。既存Pageの言語分岐は実装済み。
|
2. 新規Page+Path+初回Revisionの原子的な作成API、create/upload-only権限、並行作成の衝突。既存Pageの言語分岐は実装済み。
|
||||||
3. 競合の対話選択・復旧コマンド、巨大転送のstreamingとキャンセル、mget/mput(globのlocal/remoteを明示)。
|
3. 競合の対話選択・復旧コマンド、巨大転送のstreamingとキャンセル、mget/mput(globのlocal/remoteを明示)。
|
||||||
4. OIDC引き継ぎの本番schema適用・サーバ/CLI配布と利用者確認はv0.3.0で完了。追加TOTP省略と言語編集改善の配布は未実施。schema v1の定義は変更しない。
|
4. OIDC引き継ぎの本番schema適用・サーバ/CLI配布と利用者確認はv0.3.0で完了。追加TOTP省略と言語編集改善はv0.4.0で配布済み。schema v1の定義は変更しない。
|
||||||
5. OS keyring、Windows対応、非公開の短縮リンク引き継ぎ。自動的な公開shareは行わない。
|
5. OS keyring、Windows対応、非公開の短縮リンク引き継ぎ。自動的な公開shareは行わない。
|
||||||
@@ -4,6 +4,10 @@
|
|||||||
|
|
||||||
## 優先順
|
## 優先順
|
||||||
|
|
||||||
|
2026-11-02:[個人CardDAV提供と履歴復元・一括export](../../operations/carddav-contacts.md)を実装。専用資格情報、条件付き更新、変更tokenと削除tombstone、bounded REPORTを追加。共有アドレス帳・外部CardDAV connector・実機互換確認は同資料の後続範囲。本番反映は別途管理する。
|
||||||
|
|
||||||
|
2026-11-01:[タスク作成・作業記録・達成度・日次メール・個人アドレス帳](task-productivity-contacts.md)を追加。Web/CLI/neomuttの共通capture、時間記録、既定値、検索コマンドを接続。作業記録の事後訂正、日次メールの再送・保持期間は同設計の後続範囲へ集約する。
|
||||||
|
|
||||||
2026-10-31:ユーザ指定により[日常操作・ブラウザ・エディタ・CLI](priority-ux-20261031.md)を次期開発の最優先とする。下記の従来機能追加より優先するが、認可・データ保全の安全条件は省略しない。TODO、受け入れ条件、復元用チェックポイントを同文書に集約する。
|
2026-10-31:ユーザ指定により[日常操作・ブラウザ・エディタ・CLI](priority-ux-20261031.md)を次期開発の最優先とする。下記の従来機能追加より優先するが、認可・データ保全の安全条件は省略しない。TODO、受け入れ条件、復元用チェックポイントを同文書に集約する。
|
||||||
|
|
||||||
2026-09-27追記:`organizer.tasks 0.11.1`で[既定タスクリスト名の変更](task-dav-default-list-name.md)を実装し、12:51 JSTに[本番両インスタンスへ反映](../../operations/deployments/2026-09-27-default-task-list-name.md)。PROPPATCH 405を解消し、利用者・domain別の表示名を保存、全探索結果へ反映する。実機再試行は確認待ち。色・アイコン・通常プロジェクトのPROPPATCHは別件。
|
2026-09-27追記:`organizer.tasks 0.11.1`で[既定タスクリスト名の変更](task-dav-default-list-name.md)を実装し、12:51 JSTに[本番両インスタンスへ反映](../../operations/deployments/2026-09-27-default-task-list-name.md)。PROPPATCH 405を解消し、利用者・domain別の表示名を保存、全探索結果へ反映する。実機再試行は確認待ち。色・アイコン・通常プロジェクトのPROPPATCHは別件。
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# タスク作成と作業記録と個人アドレス帳
|
||||||
|
|
||||||
|
タスクの入口をWeb・CLI・メールで共通化する。タスク、作業記録、既定値、配信設定、連絡先はDomainと本人に属する。既存のタスクAPI・CalDAVを変更せず、個人向けAPIを追加する。管理者であることだけでは他人のデータを読めない。
|
||||||
|
|
||||||
|
## 作成API
|
||||||
|
|
||||||
|
基点は `/_/api/v1/extension/organizer.tasks/`。通常のログインセッションのBearer認証を使う。CalDAV専用資格情報はこのAPIの資格情報ではない。
|
||||||
|
|
||||||
|
| 操作 | Methodと相対URI | 契約 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| タスクを作る | POST `capture` | UUIDのrequest_id、titleが必須。notes、project_uuid、assignee_uuid、due_on、start_on、planned_on、review_on、estimate_minutes、complexityを指定可能 |
|
||||||
|
| 既定値 | GET / PUT `preferences` | PUTはGETしたversionを含める。競合は412 |
|
||||||
|
| 実行中の記録 | GET `work` | itemがnullなら停止中 |
|
||||||
|
| 開始 | POST `work` | action=start、uuid、task_uuid。開始時刻はサーバーで記録 |
|
||||||
|
| 終了 | POST `work` | action=stopとGETで得たitem。versionで条件付き更新 |
|
||||||
|
| レポート | GET `report?from=YYYY-MM-DD&to=YYYY-MM-DD` | fromを含み、toを含まない。ドメインのtimezone、最大367日 |
|
||||||
|
| 予定を作る | POST `calendar-capture` | request_id、calendar_uuid、title、from、to。本人所有・非公開・非共有・外部sourceなしのカレンダー限定 |
|
||||||
|
|
||||||
|
captureは省略した項目に本人の既定値を適用する。日付の空文字は既定値を使わず明示的に解除する。日数は作成日のドメインtimezoneにおける暦日で、0は当日、空欄は未設定。担当者UUIDは計画上の注記であり、所有権の移転や閲覧権限の付与ではない。
|
||||||
|
|
||||||
|
Webの新規作成・クイック追加・サブタスク追加でも既定値を読む。サブタスクのプロジェクト・優先度・bucketは親の所属を優先する。既存汎用items APIとCalDAVではクライアント指定を尊重し、新しいcaptureの既定値を暗黙適用しない。
|
||||||
|
|
||||||
|
同じrequest_id・同じ要求内容の再送は既存タスクを返す。最初の保存後に既定値やタスクが更新されても作り直さない。同じrequest_idで別内容を送ると412。要求のreceiptとタスクRevisionは同一トランザクションで保存する。API入力は32 KiBまで、件名300 UTF-8 bytes、メモ16 KiBまで。
|
||||||
|
|
||||||
|
calendar-captureも同じUIDを再利用し、再送で既存予定を上書きしない。時刻は `2026-11-02T09:00` のドメイン時刻、またはオフセット付きRFC 3339。終了は開始後、最大31日。予定内容を取得する前にPersonalLocal制約をロック内で検査する。外部取り込みカレンダーの内容を読まない。
|
||||||
|
|
||||||
|
## 作業時間と達成度
|
||||||
|
|
||||||
|
Webのタスク行の▶から開始し、上部の作業記録欄で終了する。CLIは `task start UUID` / `task stop`。タイマーはサーバーで継続するので、ブラウザや端末を閉じても止まらない。停止はタスク完了とは別操作。忘れずに終了すること。同一人物で同時に開始できる記録は1件。
|
||||||
|
|
||||||
|
`/v/plan/tasks/report` は完了数、ポイント、作業時間、Pomodoro集中時間を表示する。ポイントは `1 + ceil(見積分数 / 30) × 複雑度`。複雑度は1〜5、未設定の旧タスクは1。見積なしは1ポイント。完了の取消は集計から除外し、再完了するとその日の実績になる。完了済みタスクの見積変更も現在のポイントへ反映される。これは個人の振り返り指標であり、人事評価や客観的生産性の尺度ではない。
|
||||||
|
|
||||||
|
深夜をまたぐ作業はローカル日付境界で分割し、夏時間の日も24時間固定にしない。Pomodoroと手動記録は別集計で、両者を合算しない。各系列は最大10,000件で、上限到達時はpartialを返して期間の絞り込みを促す。
|
||||||
|
|
||||||
|
## 毎日のメール
|
||||||
|
|
||||||
|
`/v/plan/tasks/settings` で本人が有効化する。送信先は現在の本人のアカウントメールアドレスのみ。管理者のSMTP設定が必要。時刻はHH:mmとIANA timezoneを保存する。`task.digest.deliver` イベントが60秒周期で期限到来設定を最大20件ずつ処理する。キュー停止・負荷・SMTP遅延で配信時刻が遅れる場合がある。
|
||||||
|
|
||||||
|
当日の計画・期限到来タスクを最大100件送る。件名、期限、取り組む日、見積、タスクURLを含め、メモは送らない。送信直前にアカウント状態・同意のversion・送信先を再確認する。メールによる保存・転送の可能性があるため、既定は無効。
|
||||||
|
|
||||||
|
SMTPとSQLiteをまたぐexactly-onceは保証できない。送信前にDomain・本人・日付で予約し、配送結果はsent、uncertain、cancelled。予約後のクラッシュはsendingとして残す。結果不明の場合は自動再送せず、二重送信を避ける。翌日は通常通り処理し、過去日の取りこぼしをまとめて送らない。設定画面に直近結果を表示する。
|
||||||
|
|
||||||
|
## トップ検索コマンド
|
||||||
|
|
||||||
|
```text
|
||||||
|
add task 見積を確認 project:"開発 計画" cost:2h due:2026-11-03 review:2026-11-02 complexity:3
|
||||||
|
add task 文書を書く start:2026-11-02 planned:2026-11-02
|
||||||
|
add cal 打ち合わせ calendar:personal from:2026-11-02T09:00 to:2026-11-02T10:00
|
||||||
|
```
|
||||||
|
|
||||||
|
`project:` は名前またはUUID、候補を表示する。`calendar:` は名前・pretty_name・UUID、対象が1つだけなら省略可能。スペースを含む名前は引用符で囲む。工数は2h、30m、1.5hなど整数分に換算できる値。日付はYYYY-MM-DD。
|
||||||
|
|
||||||
|
Enterでは確認欄を表示し、「作成」で保存する。通常の検索候補への移動とは分離する。未知のオプション・重複指定・曖昧な名前は拒否。通信失敗時は同じ画面の再試行で同じrequest_idを使用する。トップ検索の入力は再読込をまたぐ永続下書きではない。
|
||||||
|
|
||||||
|
## 個人アドレス帳
|
||||||
|
|
||||||
|
画面は `/v/plan/contacts`、APIは `/_/api/v1/extension/organizer.contacts/`。拡張機能organizer.contactsを無効化すると読み書きとも停止する。Principal・プロフィール連絡先とは独立し、メール一致による自動アカウント紐付けはしない。
|
||||||
|
|
||||||
|
名前、複数メール・電話、所属、メモを編集できる。GET itemsはqとafterで最大100件ずつ検索・取得。POST itemsでUUID付き新規作成、GET items/UUIDで詳細、PUT items/UUIDでversionとIf-Matchを伴う条件付き更新。削除はdeleted=trueの同じPUTで行い、一覧から除外する。「削除済み」へ切り替えて復元できる(一覧APIのdeleted=1、更新時deleted=false)。削除したデータとvCard snapshotは保全される。
|
||||||
|
|
||||||
|
POST importは1件のUTF-8 vCard、GET items/UUID.vcfは書き出し。Webは最大2 MiB・200件のファイルを確認後に1件ずつ取り込み、失敗したカード番号を報告する。原子的な一括処理ではなく、成功分は保持する。同じUID・同じ内容は重複登録せず、同じUIDの異なる内容は412。UIDなしは入力バイト列のSHA-256から安定したUIDを補う。
|
||||||
|
|
||||||
|
vCard 3.0/4.0のUTF-8を対象とし、fold/unfold、テキストescape、複数のEMAIL/TEL、未知propertyを扱う。未対応propertyは保存・再出力し、PHOTO等の外部URLを取得しない。変更していない編集項目のparameterや繰り返しも保持する。変更した項目は画面の値で置換するため、その項目のTYPE等は外れる。vCard 2.1、ENCODING/CHARSET指定、壊れた行は欠落を起こす前に拒否する。1件64 KiBまで。
|
||||||
|
|
||||||
|
vCardの内容はDocumentStore snapshot、現在値と所有者・version・検索用projectionはSQLite、履歴はorganizer_contact_revisionsに保存する。DR snapshotのDocument参照抽出にも連絡先の現在・履歴を含める。一般のWiki/アセットURLに公開するための登録はしない。
|
||||||
|
|
||||||
|
2026-11-02に `organizer.contacts 0.2.0` として、個人CardDAV提供、変更履歴の確認・復元、全アドレス帳exportを追加した。履歴はGET `items/UUID/history` と `items/UUID/history/VERSION`、復元はPOST `items/UUID/restore` にrevision・version・If-Matchを渡し、新しい版を保存する。GET `export.vcf` は有効な連絡先のみ、最大5,000件・16 MiBを一括出力する。CardDAVのrootは `/_/api/v1/carddav/`。専用scope `contacts` を使い、既存CalDAVのallを拡張しない。[接続・同期・移行契約](../../operations/carddav-contacts.md)を参照。
|
||||||
|
|
||||||
|
## 移行と後続範囲
|
||||||
|
|
||||||
|
managed schemaにtask-productivityとcontactsを追加。task-productivityは既存organizer_items作成後に実行し、旧完了タスクを1回だけ集計projectionへ移す。既存スキーマ定義の改変ではない。切戻しでは旧版のschema checkが新コンポーネントを未知とするため、単に旧イメージを起動できるとは扱わない。データを消して戻さない。
|
||||||
|
|
||||||
|
- 連絡先の共有アドレス帳、外部CardDAV connector、重複候補mergeは別段階。個人CardDAV提供面と外部サービスの取り込みは区別する。
|
||||||
|
- 作業記録の事後修正・取消、失効Domainで取り残された記録の管理用終了手順、プロジェクト別集計、担当者への共有・通知は後続。
|
||||||
|
- 日次メールの手動再送・配信ログの保管期間、receiptの失効設計は後続。安易な削除で重複作成・配信を復活させない。
|
||||||
|
- vCard legacy変換・version間変換と履歴保持期間は後続。
|
||||||
|
|
||||||
|
利用手順は [neomuttとタスクCLI](../../operations/neomutt-tasks.md) を参照。
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# 個人アドレス帳の操作とCardDAV接続
|
||||||
|
|
||||||
|
`organizer.contacts 0.2.0` は、Webの個人アドレス帳と外部クライアントが同じ連絡先を編集するための限定CardDAV提供面を持つ。連絡先はDomainと所有者で分離し、管理者であることだけでは他人の連絡先を取得できない。共有アドレス帳や、PagesWikiから外部サービスを定期取得するconnectorは別の後続機能である。
|
||||||
|
|
||||||
|
この資料は実装済みのソース契約を示す。本番反映はリリース・展開記録で別に管理する。
|
||||||
|
|
||||||
|
## Webでの操作
|
||||||
|
|
||||||
|
入口は `/v/plan/contacts`。
|
||||||
|
|
||||||
|
- 名前、複数メールアドレス・電話番号、所属、メモを編集する。
|
||||||
|
- 「削除済み」の一覧から連絡先を復元する。削除は履歴を残す論理削除である。
|
||||||
|
- 個別の「変更履歴」で過去のvCardを確認し、選んだ版を新しい版として復元する。復元確認で未保存フォームの破棄を明示する。他の端末で変更されていた場合は412で止まり、再読み込みが必要になる。
|
||||||
|
- 「アドレス帳を書き出す」で有効な連絡先を1つの `.vcf` にまとめる。削除済みは含まない。上限は5,000件または16 MiBで、超過した場合は途中までのファイルを正常応答として返さない。
|
||||||
|
- ⇄ の「CardDAV連携」で、端末別の資格情報を発行・失効する。
|
||||||
|
|
||||||
|
vCardの未対応項目は保存・再出力するが、Webで変更した項目についてはその項目のTYPEなどのparameterを再現しない。PHOTO等の外部URLにはアクセスしない。vCard 2.1、ENCODING/CHARSET指定、1件64 KiBを超える画像入りカードなどは拒否する。詳細は[個人アドレス帳の実装契約](../design/ja/task-productivity-contacts.md)を参照。
|
||||||
|
|
||||||
|
## クライアントを接続する
|
||||||
|
|
||||||
|
1. Webに通常ログインし、連絡先画面の ⇄ を開く。
|
||||||
|
2. 端末名、読み取り専用または読み書き、有効期間を選び、パスワードを発行する。
|
||||||
|
3. 表示された認証情報IDとパスワードをクライアントに保存する。パスワードは再表示できない。
|
||||||
|
|
||||||
|
| 項目 | 値 |
|
||||||
|
| --- | --- |
|
||||||
|
| サーバーURL | `https://pages.anya.jp/_/api/v1/carddav/`。別DomainではそのDomainのHTTPS originを使う |
|
||||||
|
| ユーザー名 | 発行画面の認証情報ID。Wikiのユーザー名・メールアドレスではない |
|
||||||
|
| パスワード | 発行した連絡先専用パスワード |
|
||||||
|
| アドレス帳 | 自動検出される `PagesWiki Contacts` |
|
||||||
|
| discovery | `/.well-known/carddav` からAPI rootへ307転送 |
|
||||||
|
|
||||||
|
専用資格情報のscopeは `contacts`。既存の `tasks`、`calendar`、`all` は連絡先への権限を持たず、`all` の意味は予定とタスクのままである。連絡先の資格情報からWiki API、予定、タスクへアクセスできない。通常セッションのBearerでも本人のCardDAVを操作できるが、端末設定には用途を限定した資格情報を使う。
|
||||||
|
|
||||||
|
資格情報の管理は既存の `/_/api/v1/caldav-credentials` APIを共用する。作成時に `scope: "contacts"` を明示する。この管理API自体には通常のログインセッションが必要で、CardDAV資格情報による再発行はできない。HTTPSを必須とし、AuthorizationやvCard本文をログ・問い合わせに貼り付けない。
|
||||||
|
|
||||||
|
vdirsyncer 0.21.0では、合成データによる検出、取得、双方からの更新、新規作成、双方からの削除を検証した。設定例は以下の通り。実際の資格情報を含むファイルは所有者のみ読み取り可能にする。
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[general]
|
||||||
|
status_path = "~/.local/state/vdirsyncer"
|
||||||
|
|
||||||
|
[pair contacts]
|
||||||
|
a = "contacts_local"
|
||||||
|
b = "contacts_remote"
|
||||||
|
collections = ["contacts"]
|
||||||
|
|
||||||
|
[storage contacts_local]
|
||||||
|
type = "filesystem"
|
||||||
|
path = "~/.local/share/contacts"
|
||||||
|
fileext = ".vcf"
|
||||||
|
|
||||||
|
[storage contacts_remote]
|
||||||
|
type = "carddav"
|
||||||
|
url = "https://pages.anya.jp/_/api/v1/carddav/"
|
||||||
|
username = "発行された認証情報ID"
|
||||||
|
password = "発行されたパスワード"
|
||||||
|
```
|
||||||
|
|
||||||
|
`contacts_local` のpath配下に `contacts` ディレクトリを作り、`vdirsyncer discover`、`vdirsyncer sync` を実行する。アドレス帳名の書き換えは未対応なので、`metadata = ["displayname"]` によるmetasyncは設定しない。全件削除はクライアントの安全機構が止める場合があり、意図した削除か確認するまで強制オプションを使わない。DAVx⁵・iOSの端末実機での検証は別途必要である。
|
||||||
|
|
||||||
|
## URIと通信契約
|
||||||
|
|
||||||
|
| URI | 役割と操作 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/_/api/v1/carddav/` | OPTIONS、PROPFIND。current-user-principalとaddressbook-home-set |
|
||||||
|
| `/_/api/v1/carddav/{principal_uuid}/` | 本人のhome。OPTIONS、PROPFIND |
|
||||||
|
| `/_/api/v1/carddav/{principal_uuid}/contacts/` | 固定の個人アドレス帳。OPTIONS、PROPFIND、REPORT |
|
||||||
|
| 同上の `{resource_name}.vcf` | OPTIONS、PROPFIND、GET、HEAD、PUT、DELETE |
|
||||||
|
|
||||||
|
resource名は `.vcf` を含め5〜128 ASCII bytes、英数字・ハイフン・アンダースコア・ピリオドのみ、先頭ピリオドは禁止。Web作成分はUUID.vcf、クライアント作成分は受信した名前を固定対応表に保存する。UIDは同じ所有者・Domain内で一意かつ作成後は変更不可。名前とUIDが同じという仮定はしない。
|
||||||
|
|
||||||
|
取得時のETagはリソースのversionを表す。作成は `If-None-Match: *`、更新・削除は取得済みの `If-Match` が必要で、条件がない場合は428、競合時は412を返す。内容の正規化でPUTの入力バイト列と保存値が変わった場合は、PUT応答にETagを付けず再取得を要求する。vCardのUID欠落・変更・重複を黙って別人として保存しない。
|
||||||
|
|
||||||
|
PROPFINDはDepth 0または1。アドレス帳一覧は同じDB snapshotからtokenとメタデータを取得し、本文をロードせず最大5,000件を返す。上限超過は507で、欠落した一覧からクライアントが削除を誤推定することを避ける。
|
||||||
|
|
||||||
|
REPORTは以下の限定範囲を実装する。
|
||||||
|
|
||||||
|
- `addressbook-multiget`:同じアドレス帳の最大100 href。外部URLは取得しない。
|
||||||
|
- `addressbook-query`:最大200件のアドレス帳を対象とするbounded scan。propertyの存在・不在、text-match、anyof/allofを扱う。未知propertyも原文から検索する。parameter filterは未対応で、無視せずエラーにする。
|
||||||
|
- `sync-collection`:sync-level 1。最大200件ずつの差分、追加・更新・削除tombstoneを返す。続きがある場合はアドレス帳の507応答と次のtokenを207内に含める。クライアントはそのtokenで続行する。
|
||||||
|
|
||||||
|
不正なsync-tokenは403の `valid-sync-token`。クライアントはローカルデータを捨てず、再照合する。XMLは64 KiB、深さ12、要素1,000まででDTDを拒否する。全体の処理期限は20秒。取得・更新は `private, no-store` とする。
|
||||||
|
|
||||||
|
対応するvCardは既存のUTF-8 3.0/4.0保存profileで、通信では保存されたversionをそのまま返す。3.0↔4.0変換やaddress-dataの部分抽出はしない。別versionを明示要求された場合は拒否する。MKCOL、PROPPATCH、DAV ACL、共有・複数アドレス帳、MOVE/COPYは未対応。`DAV: 1, addressbook-access` はクライアント検出用に返すが、CardDAV全機能への準拠を意味しない。応答には `X-PagesWiki-CardDAV-Profile: private-addressbook` を付ける。
|
||||||
|
|
||||||
|
基本プロトコルは[RFC 6352](https://www.rfc-editor.org/rfc/rfc6352.html)、差分同期は[RFC 6578](https://www.rfc-editor.org/rfc/rfc6578.html)を参照する。text-matchは `i;octet` と、titlecase後の互換分解を使う `i;unicode-casemap` を扱う。[RFC 5051](https://www.rfc-editor.org/rfc/rfc5051.html)
|
||||||
|
|
||||||
|
## 保存と移行
|
||||||
|
|
||||||
|
contactsのmanaged schema v2を追加し、リリース済みv1の定義は変更しない。既存の連絡先と履歴を残したままresource名、変更sequence、DB epochを補う。変更sequenceは連絡先ごとの最新1行だけを保持し、論理削除も差分に残す。vCard snapshotと履歴の保管は従来通りであり、履歴自体の保持期間・GCは後続設計となる。
|
||||||
|
|
||||||
|
sync-tokenはDB epoch、Domain、所有者、sequenceに結び付く。DBバックアップを復元するとsequenceが過去へ戻り得るため、復元先を公開する前に停止状態で `organizer_contact_epoch` のvalueを新しい32-byte乱数のhexへ更新し、既存クライアントを再照合させる。tombstoneを物理削除する保守もtoken失効とセットで設計する。通常稼働中の自動purgeは実装しない。
|
||||||
|
|
||||||
|
切戻しには旧バイナリが新schema versionを拒否する場合がある。旧イメージへの交換だけを安全なrollbackとは扱わず、整合したDB・DocumentStoreのバックアップと復元手順を用意する。新しい連絡先秘密値は `pw_contactdav_` prefixを使い、旧版がタスク権限として誤解釈しない。
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
2026-11-02に以下を合成データで実施した。本番連絡先や外部取り込みカレンダーの内容は検証に使用していない。
|
||||||
|
|
||||||
|
- `go test ./... -count=1`、`go vet ./...`。
|
||||||
|
- 連絡先・managed schemaのrace detector付きテスト。同時PUTは一方だけ204、他方は412となる。
|
||||||
|
- v1からv2への既存行保全・繰り返し起動、変更sequence更新、資格情報削除のmarker清掃。
|
||||||
|
- 読み取り専用・失効・別scope・extension無効化、カレンダーとタスクを無効にした場合の独立稼働。
|
||||||
|
- 201件の一覧と差分ページング、上限超過の明示、XML・UID・文字コード・Unicode検索の境界条件。
|
||||||
|
- vdirsyncer 0.21.0での往復同期、Chromiumのデスクトップとスマートフォン幅での保存・履歴確認・復元・一括export・資格情報発行と失効。
|
||||||
|
|
||||||
|
実クライアント試験は `PAGESWIKI_VDIRSYNCER` に実行ファイルを指定し、`go test ./internal/server -run '^TestContactDAVVdirsyncer$' -count=1` で再実行できる。ブラウザ試験は `PAGESWIKI_BROWSER_TEST=1` で `TestProductivityChromium` の `contacts-` サブテストを実行する。通常のテストでは外部クライアントとブラウザの試験をskipする。
|
||||||
|
|
||||||
|
## 次段階
|
||||||
|
|
||||||
|
- [ ] 複数・共有アドレス帳、read/write collaboratorと共有解除、管理者の代理操作境界。
|
||||||
|
- [ ] 外部CardDAV connector。ETagと同期receipt、競合保全、URLのSSRF対策、イベントキュー・停止スイッチ。
|
||||||
|
- [ ] 200件を超えるaddressbook-queryの索引化、parameter filter、vCard version変換の情報保持試験。
|
||||||
|
- [ ] 端末実機の互換試験、連絡先mergeの確認UI、履歴保持・削除ポリシー。
|
||||||
|
|
||||||
|
後続機能は現在の個人アドレス帳を暗黙に公開・共有しない。外部connectorの追加は資格情報の保存・外向き通信を新たに伴うため、現在のCardDAV提供面とは別の設定とする。
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# PagesWiki v0.4.0 のCLI言語編集と本番反映
|
||||||
|
|
||||||
|
2026-11-01 21:48:37 JST、CLIの言語自動選択・新規言語版編集と、OIDC承認時の追加ローカルTOTP省略を本番へ反映した。
|
||||||
|
ホストの `/home/anya/.local/bin/pages` も同じリリースへ更新した。接続設定と保存済みセッションは変更していない。
|
||||||
|
|
||||||
|
## 配布物
|
||||||
|
|
||||||
|
- ソースcommit:`93f4ecb8f4be8a798e22c4816663fc6754cc1951`。
|
||||||
|
- 注釈付きGitタグ:`v0.4.0`。タグobject:`2f7a20f6deeb80f3e998426aaf7d3f2546eba7d8`。
|
||||||
|
- [ビルド run 18](https://git.anya.jp/anya/wikipages/actions/runs/18):初回で全工程成功。
|
||||||
|
- [リリース昇格 run 19](https://git.anya.jp/anya/wikipages/actions/runs/19):全工程成功。
|
||||||
|
- 公開CLIの機能追加を含むため、SemVerのMINORを更新した。公開済みタグは変更していない。
|
||||||
|
|
||||||
|
対象はapp、app2、adaptor-gateway、excalidraw-viewer。code-server、Kroki、Mermaidは再作成していない。
|
||||||
|
registry prefixは `git.anya.jp/anya/`。SHAタグとリリースタグのmanifest digest・image IDが一致し、
|
||||||
|
OCI revisionはソースcommitと一致する。リリース昇格時の再ビルドはない。
|
||||||
|
|
||||||
|
| イメージ | v0.4.0 manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:d3c4fd22e1530bf85c1ec0451b731e57ede616a8f070922d517696957f3368ef` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:08f796af86d60b851c80ad88acc1141d1240398f7b83697fe907e9b28b49bca1` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:adfdb46a4c4329366f1a66b918f3d5ba06b767723770b3f6e180566224193552` |
|
||||||
|
|
||||||
|
## 利用方法と互換性
|
||||||
|
|
||||||
|
OIDC経由のCLI承認では、ローカルTOTPが登録済みでも再入力を要求しない。
|
||||||
|
プロバイダー側の認証ポリシー、確認コード、明示承認、CSRF、PKCE、単回交換は維持する。
|
||||||
|
OIDC成功だけでMFA levelを加算せず、パスワードログイン時のローカルTOTP要件も変更しない。
|
||||||
|
|
||||||
|
新規CLIプロファイルの言語は `auto`。既存プロファイルの `und` 等は維持するため、必要に応じて変更する。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages configure --lang auto
|
||||||
|
pages edit /対象のパス
|
||||||
|
# 一時指定、または明示的な言語版の作成
|
||||||
|
pages edit /対象のパス --lang auto
|
||||||
|
pages edit /対象のパス --lang en
|
||||||
|
```
|
||||||
|
|
||||||
|
`auto` は通常表示されるRevisionの言語を確定し、その言語の現在headを編集する。
|
||||||
|
明示言語のheadがない場合は既存内容を下書きとし、空のCAS基点で最初のRevisionを作成する。
|
||||||
|
元の言語版は変更せず、無変更終了では何も作らない。同時作成や更新は409で停止し、ローカル原稿を保持する。
|
||||||
|
新規Path/Page作成・自動翻訳は含まない。[CLI設計](../../design/ja/remote-cli.md)を参照。
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
- 全Goテスト(キャッシュなし)、全Go vet、CLI関連store/serverのrace検査、Python単体22件が成功。
|
||||||
|
- 実HTTPハンドラと合成データで、auto編集、新規言語版、元言語保持、競合、失効、readonlyの書込拒否を確認。
|
||||||
|
- 模擬OIDC providerとローカルTOTP有効の合成アカウントで、追加TOTPなしの承認・交換を確認。
|
||||||
|
- Chromiumで1440px/390pxの承認画面と既存Cookieログインを確認。
|
||||||
|
- CIのテスト・3イメージのビルド・push・リリース昇格がすべて成功。
|
||||||
|
- 本番4サービスのrevision一致・再起動0回・health成功。公開HTTPSのhealth/ログインも200。
|
||||||
|
- 更新前後とも両インスタンスのmanaged schema 10コンポーネントがcurrent。今回のschema変更はない。
|
||||||
|
- イメージ内、リポジトリ、ホストPATH上のCLIが同じSHA-256。承認テンプレートに追加TOTP欄がないことも確認。
|
||||||
|
- 起動後の初期観察では、4サービスにpanic/fatal・DB lock・ジョブ失敗・errorログはなかった。
|
||||||
|
|
||||||
|
公開HTTPSでCLI開始→承認入口→未承認token交換の `authorization_pending` を確認した。
|
||||||
|
要求は1件だけ作成し、コード・verifier・device codeは表示/保存せず、セッションは発行していない。要求は5分で失効する。
|
||||||
|
実ユーザーの資格情報による最終承認・文書編集は行っていない。外部取り込みカレンダーの内容も開いていない。
|
||||||
|
|
||||||
|
## 保全と復旧
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.4.0-20261101/`、親ディレクトリは0700。
|
||||||
|
`config/` に旧Compose、`.env.release`、0600の `.env`、旧ホストCLIを保持した。
|
||||||
|
`cutover/data`・`cutover/data2` は21:48:21 JSTに最終同期を完了した停止時整合バックアップ。
|
||||||
|
21:47:30 JSTに停止を開始し、チェックサム比較による同期、DB関連ファイルのバイト一致、filesystem sync後に起動した。
|
||||||
|
対象4サービスの停止開始から再起動完了までは約67秒。
|
||||||
|
|
||||||
|
容量を抑えるため、前回バックアップの未変更ファイルだけをrsyncのlink-destで共有した。
|
||||||
|
本番データとのハードリンク共有はない。DBは別inodeであり、最終同期もin-place更新を使用していない。
|
||||||
|
バックアップ世代は不変として扱い、共有ファイルを直接編集しない。既存バックアップは削除していない。
|
||||||
|
切替後の空き容量は約14GB。世代の別媒体への退避・整理は後続の運用課題とする。
|
||||||
|
|
||||||
|
Git無視対象 `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.4.0`。
|
||||||
|
通常の `.env` とregistry overlayを併用し、`up --no-build --no-deps` で対象4サービスだけを更新した。
|
||||||
|
ローカル3イメージのlatest互換タグもv0.4.0へ揃えた。registryのlatestは更新していない。
|
||||||
|
|
||||||
|
旧v0.3.0は各ローカルrepositoryの `rollback-before-v0.4.0-20261101` で保持した。
|
||||||
|
旧イメージの読み取り専用schema checkは、両退避DBで全コンポーネントcurrentとなった。
|
||||||
|
これはmanaged schemaの互換確認であり、復旧起動全体の実地試験ではない。
|
||||||
|
復旧時は進行中の編集・CLI承認を考慮し、書込みを停止して切替後データも保全したうえで、旧タグと旧CLIを使用する。
|
||||||
|
追加TOTP要件は旧版に戻る。DBバックアップの復元は切替後の書込みを失うため、自動で行わず別途承認を必要とする。
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# PagesWiki v0.5.0 のタスク管理と個人アドレス帳の本番反映
|
||||||
|
|
||||||
|
2026-11-01 23:15:44 JST、タスク作成API、作業時間記録、達成度レポート、日次メール設定、個人アドレス帳、トップ検索の作成コマンドを本番へ反映した。ホストの `/home/anya/.local/bin/pages` も更新した。既存CLIの接続設定と保存済みセッションは変更していない。
|
||||||
|
|
||||||
|
## 配布物
|
||||||
|
|
||||||
|
- ソースcommit:`8988e5a2f8436708a5a591ef126261629d662f32`。
|
||||||
|
- 注釈付きGitタグ:`v0.5.0`。タグobject:`008b146b2f4fac75c76ad3e7606552e1ae12bc51`。
|
||||||
|
- [ビルド run 21](https://git.anya.jp/anya/wikipages/actions/runs/21):再実行のjob 23で全工程成功。
|
||||||
|
- [リリース昇格 run 22](https://git.anya.jp/anya/wikipages/actions/runs/22):全工程成功。
|
||||||
|
- 公開API・CLIの追加機能に対し、SemVerのMINORを更新した。既存のリリースタグは変更していない。
|
||||||
|
|
||||||
|
対象はapp、app2、adaptor-gateway、excalidraw-viewer。code-server、Kroki、Mermaidは再作成していない。
|
||||||
|
registry prefixは `git.anya.jp/anya/`。SHAタグとリリースタグのimage ID・manifest digestが一致し、linux/amd64のOCI revisionも上記commitと一致する。リリース昇格時の再ビルドはない。
|
||||||
|
|
||||||
|
| イメージ | v0.5.0 manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:6e326d06244878af1f5eb9a562893136a2c6b5414b53f8edd477334f07f092d6` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:097bd78daa97fd5d4de2aff1b58f93397176672421b4b1459a86408ab6f3e3f3` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:d8bbd27d3ef15a5fc41e87786b6074116fbda98375cccce341693e716325fa29` |
|
||||||
|
|
||||||
|
イメージ内、リポジトリ、ホストPATH上のCLIのSHA-256は、いずれも `d423d1a38cb931880e78e419188083592d9163cdd958ace86f58849d141c4f41`。
|
||||||
|
|
||||||
|
## 利用開始と機能範囲
|
||||||
|
|
||||||
|
| 入口 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/v/plan/tasks/settings` | プロジェクト・担当者・見積・複雑度・各日付の既定値、日次メールの時刻設定 |
|
||||||
|
| `/v/plan/tasks/report` | 日別の完了数・ポイントのヒートマップ、タスク別作業時間、Pomodoro時間 |
|
||||||
|
| `/v/plan/contacts` | 本人専用アドレス帳、複数メール・電話、検索、削除・復元、vCard入出力 |
|
||||||
|
| `pages task` | 作成・計画・完了、メールからの作成、作業開始・終了、レポート、設定 |
|
||||||
|
| `pages contacts` | 検索、neomuttの宛先補完、vCard入出力 |
|
||||||
|
| トップ検索 | `add task` と `add cal`、プロジェクト・カレンダー候補、明示確認後の作成 |
|
||||||
|
|
||||||
|
日次メールは既定で無効。本人の有効化、本人のメール登録、管理者のSMTP設定が必要。導入作業では実メールを送信していない。担当者UUIDは計画上の注記であり、所有権移転・閲覧権限付与ではない。
|
||||||
|
|
||||||
|
連絡先は個人アドレス帳として実装した。共有アドレス帳、CardDAV提供・外部双方向同期は未実装。作業記録の事後修正、配信結果不明時の手動再送、連絡先の履歴復元UI等も後続範囲とする。詳細と制約は [タスクと連絡先の設計](../../design/ja/task-productivity-contacts.md)、コマンド例は [neomuttとタスクCLI](../neomutt-tasks.md) を参照。
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
- ローカルの全Goテスト、全Go vet、CLIのPython単体26件、検索コマンド解析テスト2件が成功。
|
||||||
|
- 最終版でタスク作成・作業記録・日次配信・予定作成・CLI実HTTP・連絡先のrace検査が成功。managed schemaの反復適用・readonly・旧完了タスクの移行も検査した。
|
||||||
|
- 合成データの実HTTPでCLIの作成、開始、終了、更新、完了、集計、連絡先入出力を検証した。SMTPは模擬サーバーで日本語本文・MIMEを検証した。
|
||||||
|
- Chromiumで新規5画面のデスクトップ/スマートフォン計10ケースと、既存タスク画面4サイズを検証した。最終のサブタスク既定値修正も両画面幅で再確認した。
|
||||||
|
- 本番4サービスが同じソースrevisionで稼働し、再起動回数は0。healthcheckを持つapp・Excalidrawはhealthy、appとapp2のローカルhealthは200、公開HTTPSのhealth・ログインは200。
|
||||||
|
- 本番の新規API4種は匿名要求を401・no-storeで拒否。設定・レポート・連絡先ページはログインへ303。新規・更新JS/CSS計8ファイルは公開HTTPSの内容とリリースソースのSHA-256が一致した。
|
||||||
|
- 両インスタンスのmanaged schemaはcontactsとtask-productivityを含む12コンポーネントすべてcurrent。起動後の初期観察では、4サービスにpanic/fatal・DB lock・ジョブ失敗・errorログはなかった。
|
||||||
|
|
||||||
|
本番の実ユーザー資格情報を使った新規タスク・連絡先の作成は行っていない。外部取り込みカレンダーの内容も開いていない。バックアップは内容を解釈しないファイル保全である。
|
||||||
|
|
||||||
|
### CI再実行の経緯
|
||||||
|
|
||||||
|
初回のjob 22では、既存の `TestSaveRevisionFreezesEmbeddedAssetHeads` が `db.Open` の段階で `initialize SQLite connection: context deadline exceeded` となった(8秒)。アセット機能のassertionへ到達する前の失敗で、新機能を含むserverパッケージは成功していた。
|
||||||
|
|
||||||
|
同一テストをローカルで20回連続実行して成功。同一commit・同一テスト条件のまま全CIを再実行し、job 23では全テストとビルド・pushが成功した。テストの削除・スキップ、DB期限の緩和はしていない。
|
||||||
|
|
||||||
|
後続のCI改善では、SQLiteの初期化遅延を計測し、テスト用ストレージとパッケージ並列度、BuildKitの永続キャッシュを見直す。一時的なI/O競合は候補だが、このログだけで原因を断定しない。
|
||||||
|
|
||||||
|
## 保全と復旧
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.5.0-20261101/`、親ディレクトリは0700。
|
||||||
|
`config/` に旧Compose、旧 `.env.release`、0600の `.env`、旧ホストCLIを保持した。
|
||||||
|
|
||||||
|
23:15:14 JSTに対象4サービスの停止を開始した。停止確認後に `cutover/data` と `cutover/data2` をチェックサム比較で最終同期し、DB関連ファイルのバイト一致・別inode・filesystem syncを確認して、23:15:37 JSTにバックアップ検証を終えた。23:15:44 JSTに再起動が完了した。停止開始から再起動完了までは約30秒。
|
||||||
|
|
||||||
|
変更されていないファイルは前回の不変バックアップをrsyncのlink-destとして共有した。本番ファイルとのハードリンク共有やin-place更新は行っていない。DBは事前コピーせず、停止後に一度だけコピーして一時的な必要容量を抑えた。共有されたバックアップファイルを直接編集してはいけない。
|
||||||
|
|
||||||
|
旧v0.4.0イメージを、各ローカルrepositoryの `rollback-before-v0.5.0-20261101` タグで保持した。旧版による読み取り専用schema checkでは、保全した両DBのmanaged schema 10コンポーネントがcurrent。これはschemaの検査であり、復旧起動全体の実地試験ではない。
|
||||||
|
|
||||||
|
今回の更新ではDBに新しいコンポーネントを追加している。旧イメージへの交換だけで安全に切り戻せるとは扱わない。復旧が必要な場合は書込みを停止し、切替後データも保全してから旧版との互換性を確認する。バックアップの復元は切替後の書込みを失うため、自動で実行しない。
|
||||||
|
|
||||||
|
Git無視対象 `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.5.0`。通常の `.env` とregistry overlayを併用し、`up --no-build --no-deps` で対象4サービスだけを更新した。ローカルlatest互換タグはv0.5.0へ揃え、registryのlatestは変更していない。
|
||||||
|
|
||||||
|
切替後の空き容量は約7.3GB。既存バックアップ・旧イメージは削除していない。別媒体への保全確認と世代整理を、次の大容量操作より先に実施する。
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# neomuttとpages CLIによるタスク管理
|
||||||
|
|
||||||
|
メールからタスクを作り、作業の開始・終了を記録し、個人アドレス帳をneomuttの宛先補完に使う。先に通常の端末でpages-cliを設定してログインする。neomuttの設定やシェル履歴にトークンを書かない。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages configure --origin https://pages.anya.jp --username YOUR_USERNAME
|
||||||
|
pages login --oidc --no-browser
|
||||||
|
pages task --help
|
||||||
|
```
|
||||||
|
|
||||||
|
別接続を使うときは `pages --profile NAME task ...`。保存セッションはprivateなプロファイルファイルを使い、処理中はプロファイルロックを取得する。
|
||||||
|
|
||||||
|
## メールから作成
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages task from-mail < message.eml
|
||||||
|
pages task from-mail --project '開発 計画' --due 2026-11-03 < message.eml
|
||||||
|
# 本文を保存してよいメールに限り明示する
|
||||||
|
pages task from-mail --include-body < message.eml
|
||||||
|
```
|
||||||
|
|
||||||
|
既定では件名をタスク名、From・Date・Message-IDをメモにする。本文と添付はアップロードしない。include-bodyはplain text本文だけを追加し、HTML画像・添付・外部URLは取得しない。1通2 MiB、メモ16 KiBが上限。件名が300 UTF-8 bytesを超える場合は `--title '短い件名'` で指定する。
|
||||||
|
|
||||||
|
同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じメールを別の独立タスクにもしたい場合は `task add` を使う。
|
||||||
|
|
||||||
|
`~/.config/neomutt/neomuttrc` の例。pagesの絶対パスはインストール先に合わせる。件名等をシェルコマンド文字列に展開せず、メールを標準入力で渡す。
|
||||||
|
|
||||||
|
```muttrc
|
||||||
|
set pipe_split = yes
|
||||||
|
set pipe_decode = no
|
||||||
|
macro index,pager ,t "<pipe-message>/home/anya/.local/bin/pages task from-mail<enter>" "Create PagesWiki task"
|
||||||
|
```
|
||||||
|
|
||||||
|
`,` → `t` で選択メールを取り込む。pipe_splitは複数メールを1つのMIME入力へ連結しないため、pipe_decode=noはCLI側でMIMEを解釈するための設定。既存のpipe操作にも影響するので、自分の設定と合わせて確認する。[NeoMutt設定リファレンス](https://neomutt.org/guide/reference.html)を参照。
|
||||||
|
|
||||||
|
## 通信失敗と再送
|
||||||
|
|
||||||
|
CLIは作成要求を送信前にprivateなセッションファイルへ保持する。失敗時に表示するrequest_idで明示的に再送する。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages task retry REQUEST_UUID
|
||||||
|
```
|
||||||
|
|
||||||
|
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
|
||||||
|
|
||||||
|
サーバーで保存された直後に応答が失われても、同じrequest_idで再送すれば既存タスクが返る。保留要求を書き換えて再送すると412になる。セッションファイルにはトークンもあるため、デバッグ目的で内容を貼り付けない。
|
||||||
|
|
||||||
|
## 計画と実績
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages task project-add '開発 計画'
|
||||||
|
pages task projects
|
||||||
|
pages task preferences --project '開発 計画' --due-days 3 --review-days 1 --estimate 60 --complexity 2
|
||||||
|
pages task add '設計をレビュー' --estimate 120 --planned 2026-11-02
|
||||||
|
pages task list --view today
|
||||||
|
pages task update TASK_UUID --due 2026-11-04
|
||||||
|
pages task start TASK_UUID
|
||||||
|
pages task status
|
||||||
|
pages task stop
|
||||||
|
pages task done TASK_UUID
|
||||||
|
pages task report --from 2026-11-01 --to 2026-12-01
|
||||||
|
pages task report --from 2026-11-01 --to 2026-12-01 --json
|
||||||
|
```
|
||||||
|
|
||||||
|
stopは作業記録の終了、doneはタスクの完了。両者は独立している。見積は分単位、complexityは1〜5。期間のtoは含まない。CSV等への後処理にはJSONを使う。APIはドメインのタイムゾーンで日付を集計する。
|
||||||
|
|
||||||
|
日次メールを設定する例。SMTP設定と本人のメール登録が必要で、CLIを実行しただけでは第三者へ送信しない。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages task preferences --digest on --at 09:00 --timezone Asia/Tokyo
|
||||||
|
pages task preferences --digest off
|
||||||
|
```
|
||||||
|
|
||||||
|
## neomuttの宛先補完
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages contacts list --query 田中
|
||||||
|
pages contacts import contact.vcf
|
||||||
|
pages contacts export CONTACT_UUID > contact.vcf
|
||||||
|
pages contacts query 田中 --neomutt
|
||||||
|
```
|
||||||
|
|
||||||
|
```muttrc
|
||||||
|
set query_command = "/home/anya/.local/bin/pages contacts query --neomutt -- %s"
|
||||||
|
bind editor <Tab> complete-query
|
||||||
|
```
|
||||||
|
|
||||||
|
neomuttは%sをシェル用に引用するので、%sをさらに引用符で囲まない。出力は先頭の状態行と、メール・名前・所属のタブ区切り。`--`は検索語をCLIオプションとして解釈させないために付ける。標準のCtrl-Tによる補完を残したい場合はbind行を省略する。[外部アドレス検索](https://neomutt.org/guide/advancedusage.html#query)、[query_command](https://neomutt.org/guide/reference.html#query-command)。
|
||||||
|
|
||||||
|
連絡先は本人のDomain内だけを検索し、最大100件。メールアドレスのない連絡先は候補に出ない。ログイン切れの場合は通常の端末で再ログインする。書き出したvCardには非公開情報が含まれるため、ファイル権限と保存先を確認する。
|
||||||
|
|
||||||
|
## HTTPクライアントから使う
|
||||||
|
|
||||||
|
`POST https://pages.anya.jp/_/api/v1/extension/organizer.tasks/capture`
|
||||||
|
|
||||||
|
Content-Typeはapplication/json、AuthorizationはBearerセッション。例示UUIDは要求ごとに生成し、通信再送時だけ同じものを使う。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"request_id": "884587b2-6ae5-4aef-86d0-fd21dac39d1c",
|
||||||
|
"title": "メールで依頼された内容を確認",
|
||||||
|
"notes": "Message-ID: <example@example.invalid>",
|
||||||
|
"estimate_minutes": 30,
|
||||||
|
"complexity": 2,
|
||||||
|
"due_on": "2026-11-03"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
成功は201とitem。認証切れ401、権限不足403、要求IDの内容競合412、不正入力422。トークンをクエリ文字列に含めず、HTTPSで送る。詳細は [タスクと連絡先の設計](../design/ja/task-productivity-contacts.md) を参照。
|
||||||
@@ -508,7 +508,7 @@ func publish(stage, target string) error {
|
|||||||
func verifyReferences(ctx context.Context, database *sql.DB, seen map[string]bool) error {
|
func verifyReferences(ctx context.Context, database *sql.DB, seen map[string]bool) error {
|
||||||
// Only authoritative references, not derived projection/preview caches. Some
|
// Only authoritative references, not derived projection/preview caches. Some
|
||||||
// installations predate optional modules, hence the explicit table check.
|
// installations predate optional modules, hence the explicit table check.
|
||||||
for _, ref := range [][2]string{{"revisions", "document_hash"}, {"assets", "head_document_hash"}, {"asset_head_history", "document_hash"}, {"organizer_items", "document_hash"}, {"organizer_revisions", "document_hash"}} {
|
for _, ref := range [][2]string{{"revisions", "document_hash"}, {"assets", "head_document_hash"}, {"asset_head_history", "document_hash"}, {"organizer_items", "document_hash"}, {"organizer_revisions", "document_hash"}, {"organizer_contacts", "hash"}, {"organizer_contact_revisions", "hash"}} {
|
||||||
var exists bool
|
var exists bool
|
||||||
if err := database.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", ref[0]).Scan(&exists); err != nil {
|
if err := database.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", ref[0]).Scan(&exists); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ type Manifest struct {
|
|||||||
|
|
||||||
func Catalog() []Manifest {
|
func Catalog() []Manifest {
|
||||||
return []Manifest{
|
return []Manifest{
|
||||||
{ID: "organizer.tasks", APIVersion: 1, Version: "0.11.1", Kind: "tasks", Scope: "domain", NameKey: "tasks.title", DescriptionKey: "tasks.help", Capabilities: []string{"tasks.own.read", "tasks.own.write"}, Events: []string{"organizer.task.changed", "organizer.project.changed"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+background+index"},
|
{ID: "organizer.contacts", APIVersion: 1, Version: "0.2.0", Kind: "contacts", Scope: "domain", NameKey: "contacts.title", DescriptionKey: "contacts.help", Capabilities: []string{"contacts.own.read", "contacts.own.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
|
{ID: "organizer.tasks", APIVersion: 1, Version: "0.12.0", Kind: "tasks", Scope: "domain", NameKey: "tasks.title", DescriptionKey: "tasks.help", Capabilities: []string{"tasks.own.read", "tasks.own.write"}, Events: []string{"organizer.task.changed", "organizer.project.changed", "task.digest.deliver"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+background+index"},
|
||||||
{ID: "organizer.calendar", APIVersion: 1, Version: "0.2.0", Kind: "calendar", Scope: "domain", NameKey: "calendar.title", DescriptionKey: "calendar.help", Capabilities: []string{"calendar.read", "calendar.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
{ID: "organizer.calendar", APIVersion: 1, Version: "0.2.0", Kind: "calendar", Scope: "domain", NameKey: "calendar.title", DescriptionKey: "calendar.help", Capabilities: []string{"calendar.read", "calendar.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
{ID: "content.diary", APIVersion: 1, Version: "0.1.0", Kind: "diary", Scope: "domain", NameKey: "periodical.diary", DescriptionKey: "periodical.diary_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "diary", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
{ID: "content.diary", APIVersion: 1, Version: "0.1.0", Kind: "diary", Scope: "domain", NameKey: "periodical.diary", DescriptionKey: "periodical.diary_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "diary", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
{ID: "content.blog", APIVersion: 1, Version: "0.1.0", Kind: "blog", Scope: "domain", NameKey: "periodical.blog", DescriptionKey: "periodical.blog_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "blog", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
{ID: "content.blog", APIVersion: 1, Version: "0.1.0", Kind: "blog", Scope: "domain", NameKey: "periodical.blog", DescriptionKey: "periodical.blog_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "blog", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
|
|||||||
@@ -82,18 +82,22 @@ type davResponse struct {
|
|||||||
href string
|
href string
|
||||||
props map[xml.Name]string
|
props map[xml.Name]string
|
||||||
status int
|
status int
|
||||||
|
errorXML string
|
||||||
}
|
}
|
||||||
|
|
||||||
func davProperty(ns, key, value string) (xml.Name, string) {
|
func davProperty(ns, key, value string) (xml.Name, string) {
|
||||||
return xml.Name{Space: ns, Local: key}, value
|
return xml.Name{Space: ns, Local: key}, value
|
||||||
}
|
}
|
||||||
func writeDAV(w http.ResponseWriter, rows []davResponse, requested []davNode) {
|
func writeDAV(w http.ResponseWriter, rows []davResponse, requested []davNode, syncToken ...string) {
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?><d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">`)
|
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?><d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">`)
|
||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
b.WriteString("<d:response><d:href>" + xmlText(row.href) + "</d:href>")
|
b.WriteString("<d:response><d:href>" + xmlText(row.href) + "</d:href>")
|
||||||
if row.status != 0 {
|
if row.status != 0 {
|
||||||
fmt.Fprintf(&b, "<d:status>HTTP/1.1 %d %s</d:status>", row.status, http.StatusText(row.status))
|
fmt.Fprintf(&b, "<d:status>HTTP/1.1 %d %s</d:status>", row.status, http.StatusText(row.status))
|
||||||
|
if row.errorXML != "" {
|
||||||
|
b.WriteString("<d:error>" + row.errorXML + "</d:error>")
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
present, missing := strings.Builder{}, strings.Builder{}
|
present, missing := strings.Builder{}, strings.Builder{}
|
||||||
props := requested
|
props := requested
|
||||||
@@ -122,6 +126,9 @@ func writeDAV(w http.ResponseWriter, rows []davResponse, requested []davNode) {
|
|||||||
}
|
}
|
||||||
b.WriteString("</d:response>")
|
b.WriteString("</d:response>")
|
||||||
}
|
}
|
||||||
|
if len(syncToken) == 1 {
|
||||||
|
b.WriteString("<d:sync-token>" + xmlText(syncToken[0]) + "</d:sync-token>")
|
||||||
|
}
|
||||||
b.WriteString("</d:multistatus>")
|
b.WriteString("</d:multistatus>")
|
||||||
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
||||||
w.WriteHeader(207)
|
w.WriteHeader(207)
|
||||||
|
|||||||
@@ -0,0 +1,586 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"golang.org/x/text/unicode/norm"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
const contactDAV = "/_/api/v1/carddav/"
|
||||||
|
const cardNS = "urn:ietf:params:xml:ns:carddav"
|
||||||
|
|
||||||
|
func contactDAVRoute(p string) bool {
|
||||||
|
return p == strings.TrimSuffix(contactDAV, "/") || strings.HasPrefix(p, contactDAV) || p == "/.well-known/carddav"
|
||||||
|
}
|
||||||
|
func contactDAVError(w http.ResponseWriter, status int, ns, condition string) {
|
||||||
|
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
io.WriteString(w, `<?xml version="1.0"?><d:error xmlns:d="DAV:"><p:`+condition+` xmlns:p="`+xmlText(ns)+`"/></d:error>`)
|
||||||
|
}
|
||||||
|
func contactDAVStoreError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
w.WriteHeader(404)
|
||||||
|
case errors.Is(err, store.ErrTaskConflict):
|
||||||
|
w.WriteHeader(412)
|
||||||
|
case errors.Is(err, store.ErrContactUIDConflict):
|
||||||
|
contactDAVError(w, 403, cardNS, "no-uid-conflict")
|
||||||
|
case errors.Is(err, store.ErrContactSyncToken):
|
||||||
|
contactDAVError(w, 403, davNS, "valid-sync-token")
|
||||||
|
case errors.Is(err, store.ErrAccessDenied):
|
||||||
|
w.WriteHeader(403)
|
||||||
|
case errors.Is(err, store.ErrTaskInvalid):
|
||||||
|
contactDAVError(w, 403, cardNS, "valid-address-data")
|
||||||
|
default:
|
||||||
|
http.Error(w, "address book operation failed", 500)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func contactDAVRow(base string, item store.ContactDAVItem) davResponse {
|
||||||
|
row := davResponse{href: base + item.Name}
|
||||||
|
if item.Deleted {
|
||||||
|
row.status = 404
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
size := len(item.VCard)
|
||||||
|
if item.Size > 0 {
|
||||||
|
size = item.Size
|
||||||
|
}
|
||||||
|
row.props = map[xml.Name]string{
|
||||||
|
{Space: davNS, Local: "getetag"}: xmlText(store.ContactETag(item.Contact)),
|
||||||
|
{Space: davNS, Local: "resourcetype"}: "",
|
||||||
|
{Space: davNS, Local: "getcontenttype"}: "text/vcard; charset=utf-8",
|
||||||
|
{Space: davNS, Local: "getcontentlength"}: strconv.Itoa(size),
|
||||||
|
{Space: cardNS, Local: "address-data"}: xmlText(item.VCard),
|
||||||
|
}
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
func contactBookRow(base, token string, writable bool) davResponse {
|
||||||
|
return davResponse{href: base, props: map[xml.Name]string{
|
||||||
|
{Space: davNS, Local: "displayname"}: "PagesWiki Contacts",
|
||||||
|
{Space: davNS, Local: "resourcetype"}: "<d:collection/><a:addressbook/>",
|
||||||
|
{Space: davNS, Local: "current-user-privilege-set"}: davPrivileges(writable),
|
||||||
|
{Space: davNS, Local: "sync-token"}: xmlText(token),
|
||||||
|
{Space: "http://calendarserver.org/ns/", Local: "getctag"}: xmlText(token),
|
||||||
|
{Space: cardNS, Local: "addressbook-description"}: "Private contacts",
|
||||||
|
{Space: cardNS, Local: "max-resource-size"}: "65536",
|
||||||
|
{Space: cardNS, Local: "supported-address-data"}: `<a:address-data-type content-type="text/vcard" version="3.0"/><a:address-data-type content-type="text/vcard" version="4.0"/>`,
|
||||||
|
{Space: cardNS, Local: "supported-collation-set"}: `<a:supported-collation>i;unicode-casemap</a:supported-collation><a:supported-collation>i;octet</a:supported-collation>`,
|
||||||
|
{Space: davNS, Local: "supported-report-set"}: `<d:supported-report><d:report><a:addressbook-query/></d:report></d:supported-report><d:supported-report><d:report><a:addressbook-multiget/></d:report></d:supported-report><d:supported-report><d:report><d:sync-collection/></d:report></d:supported-report>`,
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleContactDAV(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
r = r.WithContext(ctx)
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if !s.systemExtensionEnabled(domain, "organizer.contacts") {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/.well-known/carddav" {
|
||||||
|
w.Header().Set("Location", contactDAV)
|
||||||
|
w.WriteHeader(307)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor, writable, _, credential, ok := s.davActor(w, r, "contacts", false)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// davActor authenticates the principal; storage rechecks active membership,
|
||||||
|
// ownership and the extension switch even on reads.
|
||||||
|
snapshot, err := s.store.ContactDAVSnapshot(ctx, domain, actor, "", 0)
|
||||||
|
if err != nil {
|
||||||
|
contactDAVStoreError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
principal := contactDAV + actor + "/"
|
||||||
|
book := principal + "contacts/"
|
||||||
|
p := r.URL.Path
|
||||||
|
root := p == contactDAV || p == strings.TrimSuffix(contactDAV, "/")
|
||||||
|
home := p == principal || p == strings.TrimSuffix(principal, "/")
|
||||||
|
collection := p == book || p == strings.TrimSuffix(book, "/")
|
||||||
|
name := ""
|
||||||
|
if !root && !home && !collection {
|
||||||
|
if !strings.HasPrefix(p, book) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name = strings.TrimPrefix(p, book)
|
||||||
|
if !store.ValidContactDAVName(name) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.Header().Set("DAV", "1, addressbook-access")
|
||||||
|
w.Header().Set("X-PagesWiki-CardDAV-Profile", "private-addressbook")
|
||||||
|
allow := "OPTIONS, PROPFIND"
|
||||||
|
if collection {
|
||||||
|
allow += ", REPORT"
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
allow += ", GET, HEAD"
|
||||||
|
if writable {
|
||||||
|
allow += ", PUT, DELETE"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.Header().Set("Allow", allow)
|
||||||
|
if r.Method == "OPTIONS" {
|
||||||
|
w.WriteHeader(204)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "PROPFIND" {
|
||||||
|
depth := r.Header.Get("Depth")
|
||||||
|
if depth != "0" && depth != "1" {
|
||||||
|
contactDAVError(w, 403, davNS, "propfind-finite-depth")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, e := readDAV(w, r)
|
||||||
|
if e != nil || n.XMLName.Local != "" && n.XMLName != (xml.Name{Space: davNS, Local: "propfind"}) {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var requested []davNode
|
||||||
|
if prop := n.child(davNS, "prop"); prop != nil {
|
||||||
|
requested = prop.Children
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
c, e := s.store.ContactDAVResource(ctx, domain, actor, name)
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if c.Deleted {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
row := contactDAVRow(book, store.ContactDAVItem{Contact: c, Name: name})
|
||||||
|
delete(row.props, xml.Name{Space: cardNS, Local: "address-data"})
|
||||||
|
writeDAV(w, []davResponse{row}, requested)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rows []davResponse
|
||||||
|
if collection {
|
||||||
|
rows = append(rows, contactBookRow(book, snapshot.Token, writable))
|
||||||
|
if depth == "1" {
|
||||||
|
data, e := s.store.ContactDAVInventory(ctx, domain, actor)
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if data.More {
|
||||||
|
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, c := range data.Items {
|
||||||
|
row := contactDAVRow(book, c)
|
||||||
|
delete(row.props, xml.Name{Space: cardNS, Local: "address-data"})
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
rows[0] = contactBookRow(book, data.Token, writable)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
href := principal
|
||||||
|
if root {
|
||||||
|
href = contactDAV
|
||||||
|
}
|
||||||
|
rows = append(rows, davResponse{href: href, props: map[xml.Name]string{
|
||||||
|
{Space: davNS, Local: "resourcetype"}: "<d:collection/><d:principal/>",
|
||||||
|
{Space: davNS, Local: "displayname"}: "PagesWiki Contacts",
|
||||||
|
{Space: davNS, Local: "current-user-principal"}: "<d:href>" + principal + "</d:href>",
|
||||||
|
{Space: davNS, Local: "principal-URL"}: "<d:href>" + principal + "</d:href>",
|
||||||
|
{Space: cardNS, Local: "addressbook-home-set"}: "<d:href>" + principal + "</d:href>",
|
||||||
|
{Space: davNS, Local: "current-user-privilege-set"}: davPrivileges(false),
|
||||||
|
}})
|
||||||
|
if depth == "1" {
|
||||||
|
rows = append(rows, contactBookRow(book, snapshot.Token, writable))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeDAV(w, rows, requested)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "REPORT" && collection {
|
||||||
|
s.contactDAVReport(w, r, domain, actor, book)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, err := s.store.ContactDAVResource(ctx, domain, actor, name)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
contactDAVStoreError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
exists := err == nil && !c.Deleted
|
||||||
|
if r.Method == "GET" || r.Method == "HEAD" {
|
||||||
|
if !exists {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tag := store.ContactETag(c)
|
||||||
|
w.Header().Set("ETag", tag)
|
||||||
|
if contactETagMatch(r.Header.Get("If-None-Match"), tag, true) {
|
||||||
|
w.WriteHeader(304)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/vcard; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Length", strconv.Itoa(len(c.VCard)))
|
||||||
|
if r.Method == "GET" {
|
||||||
|
io.WriteString(w, c.VCard)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != "PUT" && r.Method != "DELETE" {
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !writable {
|
||||||
|
w.WriteHeader(403)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "DELETE" && !exists {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
match, none := r.Header.Get("If-Match"), r.Header.Get("If-None-Match")
|
||||||
|
if match != "" && none != "" {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if match != "" && (!exists || !contactETagMatch(match, store.ContactETag(c), false)) || none != "" && exists && contactETagMatch(none, store.ContactETag(c), true) {
|
||||||
|
w.WriteHeader(412)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if exists && match == "" {
|
||||||
|
w.WriteHeader(428)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !exists && match == "" && none != "*" {
|
||||||
|
w.WriteHeader(428)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw := ""
|
||||||
|
if r.Method == "PUT" {
|
||||||
|
media, params, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if e != nil || media != "text/vcard" && media != "text/x-vcard" || params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8") {
|
||||||
|
contactDAVError(w, 415, cardNS, "supported-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 65536))
|
||||||
|
if e != nil {
|
||||||
|
w.WriteHeader(413)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw = string(data)
|
||||||
|
if values := store.ContactPropertyValues(store.Contact{VCard: raw}, "UID"); len(values) != 1 || values[0] == "" {
|
||||||
|
contactDAVError(w, 403, cardNS, "valid-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if v := params["version"]; v != "" {
|
||||||
|
values := store.ContactPropertyValues(store.Contact{VCard: raw}, "VERSION")
|
||||||
|
if len(values) != 1 || values[0] != v {
|
||||||
|
contactDAVError(w, 415, cardNS, "supported-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
saved, e := s.store.SaveContactDAV(ctx, domain, actor, credential, name, raw, c.Version, r.Method == "DELETE")
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "DELETE" {
|
||||||
|
w.WriteHeader(204)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// RFC 6352: a transformed PUT representation must be fetched again by client.
|
||||||
|
if saved.VCard == raw {
|
||||||
|
w.Header().Set("ETag", store.ContactETag(saved))
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
w.WriteHeader(204)
|
||||||
|
} else {
|
||||||
|
w.Header().Set("Location", book+name)
|
||||||
|
w.WriteHeader(201)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func contactETagMatch(value, tag string, weak bool) bool {
|
||||||
|
for _, v := range strings.Split(value, ",") {
|
||||||
|
v = strings.TrimSpace(v)
|
||||||
|
if weak {
|
||||||
|
v = strings.TrimPrefix(v, "W/")
|
||||||
|
}
|
||||||
|
if v == "*" || v == tag {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
func (s *Server) contactDAVReport(w http.ResponseWriter, r *http.Request, domain, actor, book string) {
|
||||||
|
if depth := r.Header.Get("Depth"); depth != "" && depth != "0" && depth != "1" {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, err := readDAV(w, r)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
prop := n.child(davNS, "prop")
|
||||||
|
if prop == nil || len(prop.Children) == 0 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, p := range prop.Children {
|
||||||
|
if p.XMLName == (xml.Name{Space: cardNS, Local: "address-data"}) && (len(p.Children) > 0 || p.attr("content-type") != "" && p.attr("content-type") != "text/vcard" || p.attr("version") != "" && p.attr("version") != "3.0" && p.attr("version") != "4.0") {
|
||||||
|
contactDAVError(w, 403, cardNS, "supported-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
requested := prop.Children
|
||||||
|
rows := []davResponse{}
|
||||||
|
if n.XMLName == (xml.Name{Space: davNS, Local: "sync-collection"}) {
|
||||||
|
level := n.child(davNS, "sync-level")
|
||||||
|
token := n.child(davNS, "sync-token")
|
||||||
|
if level == nil || level.Text != "1" || token == nil {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limit := 200
|
||||||
|
if l := n.child(davNS, "limit"); l != nil {
|
||||||
|
num := l.child(davNS, "nresults")
|
||||||
|
if num == nil {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, e := strconv.Atoi(num.Text)
|
||||||
|
if e != nil || v < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if v < limit {
|
||||||
|
limit = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data, e := s.store.ContactDAVSnapshot(r.Context(), domain, actor, token.Text, limit)
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, c := range data.Items {
|
||||||
|
rows = append(rows, contactDAVRow(book, c))
|
||||||
|
}
|
||||||
|
if data.More {
|
||||||
|
rows = append(rows, davResponse{href: book, status: 507, errorXML: "<d:number-of-matches-within-limits/>"})
|
||||||
|
}
|
||||||
|
writeContactDAV(w, rows, requested, data.Token)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n.XMLName == (xml.Name{Space: cardNS, Local: "addressbook-multiget"}) {
|
||||||
|
count := 0
|
||||||
|
for _, h := range n.Children {
|
||||||
|
if h.XMLName != (xml.Name{Space: davNS, Local: "href"}) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
if count > 100 {
|
||||||
|
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, e := url.Parse(h.Text)
|
||||||
|
if e != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Host != "" && (!strings.EqualFold(u.Host, r.Host) || u.Scheme != "https" && u.Scheme != "http") || !strings.HasPrefix(u.Path, book) || !store.ValidContactDAVName(strings.TrimPrefix(u.Path, book)) {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := strings.TrimPrefix(u.Path, book)
|
||||||
|
c, e := s.store.ContactDAVResource(r.Context(), domain, actor, name)
|
||||||
|
if errors.Is(e, sql.ErrNoRows) {
|
||||||
|
rows = append(rows, davResponse{href: book + name, status: 404})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows = append(rows, contactDAVRow(book, store.ContactDAVItem{Contact: c, Name: name}))
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeContactDAV(w, rows, requested)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n.XMLName != (xml.Name{Space: cardNS, Local: "addressbook-query"}) {
|
||||||
|
contactDAVError(w, 403, davNS, "supported-report")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filter := n.child(cardNS, "filter")
|
||||||
|
if filter != nil && !validContactFilter(*filter) {
|
||||||
|
contactDAVError(w, 403, cardNS, "supported-filter")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// A bounded full scan is explicit; never return a truncated 207 as a complete
|
||||||
|
// address book, which would make clients infer deletions. Sync is paginated.
|
||||||
|
data, e := s.store.ContactDAVSnapshot(r.Context(), domain, actor, "", 200)
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if data.More {
|
||||||
|
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limit := 200
|
||||||
|
if l := n.child(cardNS, "limit"); l != nil {
|
||||||
|
num := l.child(cardNS, "nresults")
|
||||||
|
if num == nil {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, e := strconv.Atoi(num.Text)
|
||||||
|
if e != nil || v < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if v < limit {
|
||||||
|
limit = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range data.Items {
|
||||||
|
if filter == nil || matchContactFilter(c.Contact, *filter) {
|
||||||
|
rows = append(rows, contactDAVRow(book, c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(rows) > limit {
|
||||||
|
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeContactDAV(w, rows, requested)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeContactDAV(w http.ResponseWriter, rows []davResponse, requested []davNode, token ...string) {
|
||||||
|
for _, p := range requested {
|
||||||
|
if p.XMLName == (xml.Name{Space: cardNS, Local: "address-data"}) && p.attr("version") != "" {
|
||||||
|
for _, row := range rows {
|
||||||
|
if v, ok := row.props[xml.Name{Space: cardNS, Local: "address-data"}]; ok && !strings.HasPrefix(v, xmlText("BEGIN:VCARD\r\nVERSION:"+p.attr("version")+"\r\n")) {
|
||||||
|
contactDAVError(w, 403, cardNS, "supported-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeDAV(w, rows, requested, token...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validContactFilter(n davNode) bool {
|
||||||
|
if n.attr("test") != "" && n.attr("test") != "anyof" && n.attr("test") != "allof" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, p := range n.Children {
|
||||||
|
if p.XMLName != (xml.Name{Space: cardNS, Local: "prop-filter"}) || p.attr("name") == "" || p.attr("test") != "" && p.attr("test") != "anyof" && p.attr("test") != "allof" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range p.attr("name") {
|
||||||
|
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range p.Children {
|
||||||
|
switch m.XMLName {
|
||||||
|
case xml.Name{Space: cardNS, Local: "is-not-defined"}:
|
||||||
|
if len(p.Children) != 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
case xml.Name{Space: cardNS, Local: "text-match"}:
|
||||||
|
if m.attr("collation") != "" && m.attr("collation") != "i;unicode-casemap" && m.attr("collation") != "i;octet" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if m.attr("match-type") != "" && m.attr("match-type") != "contains" && m.attr("match-type") != "equals" && m.attr("match-type") != "starts-with" && m.attr("match-type") != "ends-with" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if m.attr("negate-condition") != "" && m.attr("negate-condition") != "yes" && m.attr("negate-condition") != "no" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if len(m.Children) > 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func matchContactFilter(c store.Contact, n davNode) bool {
|
||||||
|
if len(n.Children) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
all := n.attr("test") == "allof"
|
||||||
|
result := all
|
||||||
|
for _, p := range n.Children {
|
||||||
|
values := store.ContactPropertyValues(c, p.attr("name"))
|
||||||
|
match := len(values) > 0
|
||||||
|
if len(p.Children) > 0 {
|
||||||
|
and := p.attr("test") == "allof"
|
||||||
|
match = and
|
||||||
|
for _, m := range p.Children {
|
||||||
|
hit := false
|
||||||
|
if m.XMLName.Local == "is-not-defined" {
|
||||||
|
hit = len(values) == 0
|
||||||
|
} else {
|
||||||
|
for _, v := range values {
|
||||||
|
query := m.Text
|
||||||
|
if m.attr("collation") != "i;octet" {
|
||||||
|
v = norm.NFKD.String(strings.Map(unicode.ToTitle, v))
|
||||||
|
query = norm.NFKD.String(strings.Map(unicode.ToTitle, query))
|
||||||
|
}
|
||||||
|
switch m.attr("match-type") {
|
||||||
|
case "equals":
|
||||||
|
hit = v == query
|
||||||
|
case "starts-with":
|
||||||
|
hit = strings.HasPrefix(v, query)
|
||||||
|
case "ends-with":
|
||||||
|
hit = strings.HasSuffix(v, query)
|
||||||
|
default:
|
||||||
|
hit = strings.Contains(v, query)
|
||||||
|
}
|
||||||
|
if hit {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if m.attr("negate-condition") == "yes" {
|
||||||
|
hit = !hit && len(values) > 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if and {
|
||||||
|
match = match && hit
|
||||||
|
} else {
|
||||||
|
match = match || hit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if all {
|
||||||
|
result = result && match
|
||||||
|
} else {
|
||||||
|
result = result || match
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Real client interoperability uses only disposable, synthetic contacts.
|
||||||
|
func TestContactDAVVdirsyncer(t *testing.T) {
|
||||||
|
bin := os.Getenv("PAGESWIKI_VDIRSYNCER")
|
||||||
|
if bin == "" {
|
||||||
|
t.Skip("opt-in vdirsyncer executable")
|
||||||
|
}
|
||||||
|
s, _, domain, actor := taskFixture(t)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
credential, password, err := s.store.CreateDAVCredential(ctx, domain, actor, "Fixture", true, 1, "contacts")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
native, err := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), VCard: testCard}, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(s.handler())
|
||||||
|
defer server.Close()
|
||||||
|
dir := t.TempDir()
|
||||||
|
local := filepath.Join(dir, "cards")
|
||||||
|
if err = os.MkdirAll(filepath.Join(local, "contacts"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
config := fmt.Sprintf(`[general]
|
||||||
|
status_path = %q
|
||||||
|
[pair contacts]
|
||||||
|
a = "local"
|
||||||
|
b = "remote"
|
||||||
|
collections = ["contacts"]
|
||||||
|
[storage local]
|
||||||
|
type = "filesystem"
|
||||||
|
path = %q
|
||||||
|
fileext = ".vcf"
|
||||||
|
[storage remote]
|
||||||
|
type = "carddav"
|
||||||
|
url = %q
|
||||||
|
username = %q
|
||||||
|
password = %q
|
||||||
|
`, filepath.Join(dir, "status"), local, strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+contactDAV, credential.ID, password)
|
||||||
|
configPath := filepath.Join(dir, "vdirsyncer.conf")
|
||||||
|
if err = os.WriteFile(configPath, []byte(config), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run := func(action string, extra ...string) {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.CommandContext(ctx, bin, append([]string{"-c", configPath, action}, extra...)...)
|
||||||
|
cmd.Stdin = strings.NewReader("y\ny\ny\n")
|
||||||
|
out, e := cmd.CombinedOutput()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatalf("%s: %v\n%s", action, e, strings.ReplaceAll(string(out), password, "[REDACTED]"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run("discover")
|
||||||
|
run("sync")
|
||||||
|
files, err := filepath.Glob(filepath.Join(local, "contacts", "*.vcf"))
|
||||||
|
if err != nil || len(files) != 1 {
|
||||||
|
t.Fatal(files, err)
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(files[0])
|
||||||
|
if err != nil || !strings.Contains(string(raw), "FN:田中") {
|
||||||
|
t.Fatal("download", err)
|
||||||
|
}
|
||||||
|
if err = os.WriteFile(files[0], []byte(strings.Replace(string(raw), "FN:田中", "FN:Client edited", 1)), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run("sync")
|
||||||
|
got, err := s.store.Contact(ctx, domain, actor, native.UUID)
|
||||||
|
if err != nil || got.Name != "Client edited" || !strings.Contains(got.VCard, "X-PRIVATE:keep") {
|
||||||
|
t.Fatal("client edit", got.Name, err)
|
||||||
|
}
|
||||||
|
got.Name = "Web edited"
|
||||||
|
got, err = s.store.SaveContact(ctx, domain, actor, got, false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run("sync")
|
||||||
|
raw, err = os.ReadFile(files[0])
|
||||||
|
if err != nil || !strings.Contains(string(raw), "FN:Web edited") {
|
||||||
|
t.Fatal("web edit", err)
|
||||||
|
}
|
||||||
|
newPath := filepath.Join(local, "contacts", "client-new.vcf")
|
||||||
|
newCard := strings.ReplaceAll(testCard, "urn:test:dav-contact", "urn:test:client-new")
|
||||||
|
if err = os.WriteFile(newPath, []byte(newCard), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run("sync")
|
||||||
|
items, _, err := s.store.Contacts(ctx, domain, actor, "", "")
|
||||||
|
if err != nil || len(items) != 2 {
|
||||||
|
t.Fatal("client create", len(items), err)
|
||||||
|
}
|
||||||
|
if err = os.Remove(newPath); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run("sync")
|
||||||
|
items, _, err = s.store.Contacts(ctx, domain, actor, "", "")
|
||||||
|
if err != nil || len(items) != 1 {
|
||||||
|
t.Fatal("client delete", len(items), err)
|
||||||
|
}
|
||||||
|
got.Deleted = true
|
||||||
|
if _, err = s.store.SaveContact(ctx, domain, actor, got, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Emptying a whole book requires vdirsyncer's explicit safety override.
|
||||||
|
run("sync", "--force-delete", "contacts/contacts")
|
||||||
|
files, err = filepath.Glob(filepath.Join(local, "contacts", "*.vcf"))
|
||||||
|
if err != nil || len(files) != 0 {
|
||||||
|
t.Fatal("web delete", files, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/xml"
|
||||||
|
"fmt"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testCard = "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:dav-contact\r\nFN:田中\r\nEMAIL;TYPE=work:tanaka@example.invalid\r\nX-PRIVATE:keep\r\nEND:VCARD\r\n"
|
||||||
|
|
||||||
|
func TestContactDAVConcurrentWritesAndStandaloneExtension(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
for _, id := range []string{"organizer.tasks", "organizer.calendar"} {
|
||||||
|
if e := s.setSystemExtensionEnabled(domain, id, false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cred, pass, err := s.store.CreateDAVCredential(ctx, domain, actor, "phone", true, 1, "contacts")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(cred.ID+":"+pass))
|
||||||
|
path := contactDAV + actor + "/contacts/one.vcf"
|
||||||
|
if w := cardRequest(s, auth, "PUT", path, testCard, map[string]string{"If-None-Match": "*"}); w.Code != 201 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if w := cardRequest(s, "Bearer "+token, "GET", "/_/api/v1/caldav-credentials", "", nil); w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
start := make(chan struct{})
|
||||||
|
results := make(chan int, 2)
|
||||||
|
for _, name := range []string{"First", "Second"} {
|
||||||
|
go func(name string) {
|
||||||
|
<-start
|
||||||
|
w := cardRequest(s, auth, "PUT", path, strings.Replace(testCard, "FN:田中", "FN:"+name, 1), map[string]string{"If-Match": `"1"`})
|
||||||
|
results <- w.Code
|
||||||
|
}(name)
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
a, b := <-results, <-results
|
||||||
|
if !(a == 204 && b == 412 || a == 412 && b == 204) {
|
||||||
|
t.Fatal("concurrent overwrite", a, b)
|
||||||
|
}
|
||||||
|
// Removing the contacts marker must never reinterpret this secret as tasks.
|
||||||
|
if _, err = s.store.DB.Exec(`DELETE FROM organizer_contact_credentials WHERE credential_id=?`, cred.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, _, _, err = s.store.AuthenticateDAV(ctx, domain, cred.ID, pass, ""); err != store.ErrAccessDenied {
|
||||||
|
t.Fatal("scope downgrade", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContactDAVInventoryAndLimits(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
for i := 0; i < 201; i++ {
|
||||||
|
_, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), Name: fmt.Sprintf("Person %03d", i)}, false)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data, err := s.store.ContactDAVInventory(ctx, domain, actor)
|
||||||
|
if err != nil || data.More || len(data.Items) != 201 {
|
||||||
|
t.Fatal(len(data.Items), err)
|
||||||
|
}
|
||||||
|
for _, c := range data.Items {
|
||||||
|
if c.VCard != "" || c.Size < 1 || c.Version != 1 {
|
||||||
|
t.Fatal("inventory must contain metadata only", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
book := contactDAV + actor + "/contacts/"
|
||||||
|
auth := "Bearer " + token
|
||||||
|
w := cardRequest(s, auth, "PROPFIND", book, "", nil)
|
||||||
|
if w.Code != 207 || strings.Count(w.Body.String(), "<d:response>") != 202 || strings.Contains(w.Body.String(), "BEGIN:VCARD") {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
w = cardRequest(s, auth, "REPORT", book, cardSync("", ""), nil)
|
||||||
|
if w.Code != 207 || !strings.Contains(w.Body.String(), "507") {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
next := cardRequest(s, auth, "REPORT", book, cardSync(responseSync(t, w), ""), nil)
|
||||||
|
if next.Code != 207 || strings.Count(next.Body.String(), "<d:response>") != 1 {
|
||||||
|
t.Fatal(next.Code, next.Body)
|
||||||
|
}
|
||||||
|
query := `<a:addressbook-query xmlns:a="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:"><d:prop><d:getetag/></d:prop></a:addressbook-query>`
|
||||||
|
w = cardRequest(s, auth, "REPORT", book, query, nil)
|
||||||
|
if w.Code != 507 {
|
||||||
|
t.Fatal("must not silently truncate a full query", w.Code)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
raw, media string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{strings.Replace(testCard, "UID:urn:test:dav-contact\r\n", "", 1), "text/vcard", 403},
|
||||||
|
{testCard, "text/vcard; version=3.0", 415},
|
||||||
|
{testCard, "text/vcard; charset=shift_jis", 415},
|
||||||
|
} {
|
||||||
|
w = cardRequest(s, auth, "PUT", book+"invalid.vcf", tc.raw, map[string]string{"If-None-Match": "*", "Content-Type": tc.media})
|
||||||
|
if w.Code != tc.want {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContactDAVUnicodeAndUnknownProperties(t *testing.T) {
|
||||||
|
card := store.Contact{VCard: strings.Replace(testCard, "X-PRIVATE:keep", "X-PRIVATE:CAFÉ", 1)}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
collation, query string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"i;unicode-casemap", "cafe\u0301", true},
|
||||||
|
{"i;unicode-casemap", "CAFÉ", true},
|
||||||
|
{"i;octet", "café", false},
|
||||||
|
{"i;octet", "CAFÉ", true},
|
||||||
|
} {
|
||||||
|
var filter davNode
|
||||||
|
raw := `<a:filter xmlns:a="urn:ietf:params:xml:ns:carddav"><a:prop-filter name="X-PRIVATE"><a:text-match collation="` + tc.collation + `" match-type="equals">` + tc.query + `</a:text-match></a:prop-filter></a:filter>`
|
||||||
|
if e := xml.Unmarshal([]byte(raw), &filter); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if !validContactFilter(filter) || matchContactFilter(card, filter) != tc.want {
|
||||||
|
t.Fatal(tc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cardRequest(s *Server, auth, method, path, body string, headers map[string]string) *httptest.ResponseRecorder {
|
||||||
|
if headers == nil {
|
||||||
|
headers = map[string]string{}
|
||||||
|
}
|
||||||
|
if _, ok := headers["Content-Type"]; !ok {
|
||||||
|
headers["Content-Type"] = "text/vcard"
|
||||||
|
}
|
||||||
|
return davTaskRequest(s, auth, method, path, body, headers)
|
||||||
|
}
|
||||||
|
func cardSync(token string, limit string) string {
|
||||||
|
return `<d:sync-collection xmlns:d="DAV:"><d:sync-token>` + xmlText(token) + `</d:sync-token><d:sync-level>1</d:sync-level><d:prop><d:getetag/></d:prop>` + limit + `</d:sync-collection>`
|
||||||
|
}
|
||||||
|
func responseSync(t *testing.T, w *httptest.ResponseRecorder) string {
|
||||||
|
t.Helper()
|
||||||
|
var value struct {
|
||||||
|
Token string `xml:"sync-token"`
|
||||||
|
}
|
||||||
|
if e := xml.Unmarshal(w.Body.Bytes(), &value); e != nil || value.Token == "" {
|
||||||
|
t.Fatal(e, w.Body)
|
||||||
|
}
|
||||||
|
return value.Token
|
||||||
|
}
|
||||||
|
func TestContactDAVRoundTripAndScopes(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
book := contactDAV + actor + "/contacts/"
|
||||||
|
cred, password, err := s.store.CreateDAVCredential(ctx, domain, actor, "phone", true, 90, "contacts")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(cred.ID+":"+password))
|
||||||
|
request := func(method, path, body string, h map[string]string, want int) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
w := cardRequest(s, auth, method, path, body, h)
|
||||||
|
if w.Code != want {
|
||||||
|
t.Fatalf("%s %s: %d want %d %s", method, path, w.Code, want, w.Body)
|
||||||
|
}
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
options := request("OPTIONS", contactDAV, "", nil, 204)
|
||||||
|
if options.Header().Get("DAV") != "1, addressbook-access" {
|
||||||
|
t.Fatal(options.Header())
|
||||||
|
}
|
||||||
|
home := request("PROPFIND", contactDAV, `<d:propfind xmlns:d="DAV:" xmlns:a="urn:ietf:params:xml:ns:carddav"><d:prop><d:current-user-principal/><a:addressbook-home-set/></d:prop></d:propfind>`, nil, 207)
|
||||||
|
if !strings.Contains(home.Body.String(), contactDAV+actor+"/") {
|
||||||
|
t.Fatal(home.Body)
|
||||||
|
}
|
||||||
|
discovery := request("PROPFIND", contactDAV+actor+"/", "", nil, 207)
|
||||||
|
if !strings.Contains(discovery.Body.String(), book) {
|
||||||
|
t.Fatal(discovery.Body)
|
||||||
|
}
|
||||||
|
empty := request("REPORT", book, cardSync("", ""), nil, 207)
|
||||||
|
emptyToken := responseSync(t, empty)
|
||||||
|
path := book + "client-contact.vcf"
|
||||||
|
request("PUT", path, testCard, map[string]string{"If-None-Match": "*"}, 201)
|
||||||
|
get := request("GET", path, "", nil, 200)
|
||||||
|
tag := get.Header().Get("ETag")
|
||||||
|
request("GET", path, "", map[string]string{"If-None-Match": tag}, 304)
|
||||||
|
request("PUT", path, testCard, map[string]string{"If-None-Match": "*"}, 412)
|
||||||
|
request("PUT", path, testCard, nil, 428)
|
||||||
|
request("PUT", path, testCard, map[string]string{"If-Match": `"999"`}, 412)
|
||||||
|
request("PUT", book+"duplicate.vcf", testCard, map[string]string{"If-None-Match": "*"}, 403)
|
||||||
|
c, err := s.store.ContactDAVResource(ctx, domain, actor, "client-contact.vcf")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c.Name = "Webで変更"
|
||||||
|
c, err = s.store.SaveContact(ctx, domain, actor, c, false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
delta := request("REPORT", book, cardSync(emptyToken, ""), nil, 207)
|
||||||
|
if !strings.Contains(delta.Body.String(), path) || strings.Contains(delta.Body.String(), "Webで変更") {
|
||||||
|
t.Fatal(delta.Body)
|
||||||
|
}
|
||||||
|
synced := responseSync(t, delta)
|
||||||
|
multi := `<a:addressbook-multiget xmlns:a="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:"><d:prop><d:getetag/><a:address-data/></d:prop><d:href>` + path + `</d:href><d:href>` + book + `missing.vcf</d:href></a:addressbook-multiget>`
|
||||||
|
got := request("REPORT", book, multi, nil, 207)
|
||||||
|
if !strings.Contains(got.Body.String(), "Webで変更") || !strings.Contains(got.Body.String(), "X-PRIVATE:keep") || !strings.Contains(got.Body.String(), "404 Not Found") {
|
||||||
|
t.Fatal(got.Body)
|
||||||
|
}
|
||||||
|
request("DELETE", path, "", map[string]string{"If-Match": store.ContactETag(c)}, 204)
|
||||||
|
request("GET", path, "", nil, 404)
|
||||||
|
delta = request("REPORT", book, cardSync(synced, ""), nil, 207)
|
||||||
|
if !strings.Contains(delta.Body.String(), path) || !strings.Contains(delta.Body.String(), "404 Not Found") {
|
||||||
|
t.Fatal(delta.Body)
|
||||||
|
}
|
||||||
|
request("REPORT", book, cardSync("urn:foreign:123", ""), nil, 403)
|
||||||
|
request("PUT", path, testCard, map[string]string{"If-None-Match": "*"}, 201)
|
||||||
|
c, err = s.store.ContactDAVResource(ctx, domain, actor, "client-contact.vcf")
|
||||||
|
if err != nil || c.Deleted {
|
||||||
|
t.Fatal(c, err)
|
||||||
|
}
|
||||||
|
if w := cardRequest(s, auth, "GET", contactsAPI+"items", "", nil); w.Code != 401 {
|
||||||
|
t.Fatal("DAV credential leaked to API", w.Code)
|
||||||
|
}
|
||||||
|
if w := cardRequest(s, auth, "PROPFIND", taskDAVRoot, "", nil); w.Code != 401 {
|
||||||
|
t.Fatal("contact credential grants tasks", w.Code)
|
||||||
|
}
|
||||||
|
// The legacy 'all' scope remains calendar+tasks, not newly added contacts.
|
||||||
|
all, pass, e := s.store.CreateDAVCredential(ctx, domain, actor, "old", true, 1, "all")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
otherAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(all.ID+":"+pass))
|
||||||
|
if w := cardRequest(s, otherAuth, "PROPFIND", contactDAV, "", nil); w.Code != 401 {
|
||||||
|
t.Fatal("old authority expanded", w.Code)
|
||||||
|
}
|
||||||
|
request("PROPFIND", contactDAV+uuid.NewString()+"/contacts/", "", nil, 404)
|
||||||
|
if e = s.store.RevokeTaskDAVCredential(ctx, domain, actor, cred.ID); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
request("GET", path, "", nil, 401)
|
||||||
|
if _, e = s.store.SaveContactDAV(ctx, domain, actor, cred.ID, "client-contact.vcf", testCard, c.Version, false); e != store.ErrAccessDenied {
|
||||||
|
t.Fatal("revoked writer", e)
|
||||||
|
}
|
||||||
|
// A normal session can still edit its own address book.
|
||||||
|
if w := cardRequest(s, "Bearer "+token, "GET", path, "", nil); w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContactDAVPaginationHistoryAndBoundaries(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
auth := "Bearer " + token
|
||||||
|
book := contactDAV + actor + "/contacts/"
|
||||||
|
var ids []string
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
id := uuid.NewString()
|
||||||
|
ids = append(ids, id)
|
||||||
|
_, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: id, Name: "Person"}, false)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
first := cardRequest(s, auth, "REPORT", book, cardSync("", `<d:limit><d:nresults>1</d:nresults></d:limit>`), nil)
|
||||||
|
if first.Code != 207 || !strings.Contains(first.Body.String(), "507 Insufficient Storage") {
|
||||||
|
t.Fatal(first.Code, first.Body)
|
||||||
|
}
|
||||||
|
second := cardRequest(s, auth, "REPORT", book, cardSync(responseSync(t, first), ""), nil)
|
||||||
|
if second.Code != 207 || strings.Contains(second.Body.String(), "507 Insufficient Storage") {
|
||||||
|
t.Fatal(second.Code, second.Body)
|
||||||
|
}
|
||||||
|
var r struct {
|
||||||
|
Responses []struct {
|
||||||
|
Href string `xml:"href"`
|
||||||
|
} `xml:"response"`
|
||||||
|
}
|
||||||
|
if e := xml.Unmarshal(second.Body.Bytes(), &r); e != nil || len(r.Responses) != 2 {
|
||||||
|
t.Fatal(e, second.Body)
|
||||||
|
}
|
||||||
|
c, e := s.store.Contact(ctx, domain, actor, ids[0])
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
c.Name = "Changed"
|
||||||
|
c, e = s.store.SaveContact(ctx, domain, actor, c, false)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
h, e := s.store.ContactHistory(ctx, domain, actor, c.UUID, 0)
|
||||||
|
if e != nil || len(h) != 2 {
|
||||||
|
t.Fatal(h, e)
|
||||||
|
}
|
||||||
|
restored, e := s.store.RestoreContactRevision(ctx, domain, actor, c.UUID, 1, c.Version)
|
||||||
|
if e != nil || restored.Name != "Person" || restored.Version != 3 {
|
||||||
|
t.Fatal(restored, e)
|
||||||
|
}
|
||||||
|
if _, e = s.store.RestoreContactRevision(ctx, domain, actor, c.UUID, 1, c.Version); e != store.ErrTaskConflict {
|
||||||
|
t.Fatal("stale restore", e)
|
||||||
|
}
|
||||||
|
raw, e := s.store.ExportContacts(ctx, domain, actor)
|
||||||
|
if e != nil || strings.Count(raw, "BEGIN:VCARD") != 3 {
|
||||||
|
t.Fatal(e, raw)
|
||||||
|
}
|
||||||
|
history := cardRequest(s, auth, "GET", contactsAPI+"items/"+c.UUID+"/history", "", nil)
|
||||||
|
if history.Code != 200 {
|
||||||
|
t.Fatal(history.Code, history.Body)
|
||||||
|
}
|
||||||
|
preview := cardRequest(s, auth, "GET", contactsAPI+"items/"+c.UUID+"/history/1", "", nil)
|
||||||
|
if preview.Code != 200 || !strings.Contains(preview.Body.String(), "Person") {
|
||||||
|
t.Fatal(preview.Code, preview.Body)
|
||||||
|
}
|
||||||
|
restoreBody, _ := json.Marshal(map[string]int64{"version": restored.Version, "revision": 1})
|
||||||
|
restore := cardRequest(s, auth, "POST", contactsAPI+"items/"+c.UUID+"/restore", string(restoreBody), map[string]string{"If-Match": store.ContactETag(restored)})
|
||||||
|
if restore.Code != 200 {
|
||||||
|
t.Fatal(restore.Code, restore.Body)
|
||||||
|
}
|
||||||
|
query := `<a:addressbook-query xmlns:a="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:"><d:prop><d:getetag/></d:prop><a:filter><a:prop-filter name="FN"><a:text-match match-type="equals">Person</a:text-match></a:prop-filter></a:filter></a:addressbook-query>`
|
||||||
|
found := cardRequest(s, auth, "REPORT", book, query, nil)
|
||||||
|
if found.Code != 207 {
|
||||||
|
t.Fatal(found.Code, found.Body)
|
||||||
|
}
|
||||||
|
for _, body := range []string{strings.Replace(query, `name="FN"`, `name="BAD NAME"`, 1), strings.Replace(query, `match-type="equals"`, `collation="unsupported"`, 1)} {
|
||||||
|
w := cardRequest(s, auth, "REPORT", book, body, nil)
|
||||||
|
if w.Code != 403 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xmlBomb := `<!DOCTYPE x [<!ENTITY x "bomb">]><d:propfind xmlns:d="DAV:"/>`
|
||||||
|
if w := cardRequest(s, auth, "PROPFIND", book, xmlBomb, nil); w.Code != 400 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
foreign := `<a:addressbook-multiget xmlns:a="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:"><d:prop><d:getetag/></d:prop><d:href>https://evil.invalid` + book + `a.vcf</d:href></a:addressbook-multiget>`
|
||||||
|
if w := cardRequest(s, auth, "REPORT", book, foreign, nil); w.Code != 400 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
read, pass, e := s.store.CreateDAVCredential(ctx, domain, actor, "readonly", false, 1, "contacts")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
readonly := "Basic " + base64.StdEncoding.EncodeToString([]byte(read.ID+":"+pass))
|
||||||
|
if w := cardRequest(s, readonly, "PUT", book+"new.vcf", testCard, map[string]string{"If-None-Match": "*"}); w.Code != 403 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if e = s.setSystemExtensionEnabled(domain, "organizer.contacts", false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if w := cardRequest(s, auth, "PROPFIND", book, "", nil); w.Code != 404 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package server
|
|||||||
func init() {
|
func init() {
|
||||||
for lang, entries := range map[string]map[string]string{
|
for lang, entries := range map[string]map[string]string{
|
||||||
"en": {
|
"en": {
|
||||||
|
"contacts.title": "Private address book", "contacts.help": "Private contacts, vCard import/export and email address lookup.",
|
||||||
"contact.title": "Contact details", "contact.phone": "Phone number",
|
"contact.title": "Contact details", "contact.phone": "Phone number",
|
||||||
"contact.help": "Private by default, independently of your profile. A tap opens the phone app. Leave blank to remove. Use 3–15 digits with an optional leading +, spaces, hyphens or parentheses; extensions and service codes are not supported.",
|
"contact.help": "Private by default, independently of your profile. A tap opens the phone app. Leave blank to remove. Use 3–15 digits with an optional leading +, spaces, hyphens or parentheses; extensions and service codes are not supported.",
|
||||||
"contact.visibility_help": "The profile audience remains the upper limit. Anonymous access also requires the domain to permit public profiles. Administrators do not automatically see private numbers.",
|
"contact.visibility_help": "The profile audience remains the upper limit. Anonymous access also requires the domain to permit public profiles. Administrators do not automatically see private numbers.",
|
||||||
@@ -10,6 +11,7 @@ func init() {
|
|||||||
"contact.invalid_phone": "Enter a phone number with 3–15 digits and optional leading +; only spaces, hyphens and parentheses may separate digits.",
|
"contact.invalid_phone": "Enter a phone number with 3–15 digits and optional leading +; only spaces, hyphens and parentheses may separate digits.",
|
||||||
},
|
},
|
||||||
"ja": {
|
"ja": {
|
||||||
|
"contacts.title": "個人アドレス帳", "contacts.help": "非公開の連絡先、vCard入出力、メールアドレス検索。",
|
||||||
"contact.title": "連絡先", "contact.phone": "電話番号",
|
"contact.title": "連絡先", "contact.phone": "電話番号",
|
||||||
"contact.help": "プロフィールとは別に、既定で非公開です。タップすると電話アプリを開きます。空欄で削除。3〜15桁の数字と先頭の+、空白・ハイフン・括弧を使用できます。内線やサービスコードは未対応です。",
|
"contact.help": "プロフィールとは別に、既定で非公開です。タップすると電話アプリを開きます。空欄で削除。3〜15桁の数字と先頭の+、空白・ハイフン・括弧を使用できます。内線やサービスコードは未対応です。",
|
||||||
"contact.visibility_help": "プロフィールの公開範囲を上限とします。匿名公開にはドメイン側の許可も必要です。管理者でも非公開の番号は表示されません。",
|
"contact.visibility_help": "プロフィールの公開範囲を上限とします。匿名公開にはドメイン側の許可も必要です。管理者でも非公開の番号は表示されません。",
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const contactsAPI = "/_/api/v1/extension/organizer.contacts/"
|
||||||
|
|
||||||
|
func contactRoute(p string) bool {
|
||||||
|
return contactDAVRoute(p) || p == "/v/plan/contacts" || strings.HasPrefix(p, contactsAPI)
|
||||||
|
}
|
||||||
|
func (s *Server) handleContacts(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if !s.systemExtensionEnabled(domain, "organizer.contacts") {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor, active := s.calendarActor(r)
|
||||||
|
if actor == "" {
|
||||||
|
s.authRequired(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != "GET" && r.Method != "HEAD" && !active {
|
||||||
|
taskError(w, store.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/v/plan/contacts" {
|
||||||
|
if r.Method != "GET" && r.Method != "HEAD" {
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, _, e := s.store.Contacts(r.Context(), domain, actor, "", ""); e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.renderWithContext(w, r, "contacts.gohtml", map[string]any{"Title": "Contacts", "ContactWritable": active, "Path": r.URL.Path})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := strings.TrimPrefix(r.URL.Path, contactsAPI)
|
||||||
|
if key == "export.vcf" && (r.Method == "GET" || r.Method == "HEAD") {
|
||||||
|
raw, e := s.store.ExportContacts(r.Context(), domain, actor)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/vcard; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="contacts.vcf"`)
|
||||||
|
w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
|
||||||
|
if r.Method == "GET" {
|
||||||
|
io.WriteString(w, raw)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
parts := strings.Split(key, "/")
|
||||||
|
if len(parts) >= 3 && parts[0] == "items" && (parts[2] == "history" || parts[2] == "restore") {
|
||||||
|
id, e := uuid.Parse(parts[1])
|
||||||
|
if e != nil || id.String() != parts[1] {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if parts[2] == "history" && r.Method == "GET" {
|
||||||
|
if len(parts) == 4 {
|
||||||
|
revision, e := strconv.ParseInt(parts[3], 10, 64)
|
||||||
|
if e != nil || revision < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, e := s.store.ContactAtRevision(r.Context(), domain, actor, parts[1], revision)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(parts) != 3 {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
before := int64(0)
|
||||||
|
if v := r.URL.Query().Get("before"); v != "" {
|
||||||
|
before, e = strconv.ParseInt(v, 10, 64)
|
||||||
|
if e != nil || before < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items, e := s.store.ContactHistory(r.Context(), domain, actor, parts[1], before)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next := int64(0)
|
||||||
|
if len(items) == 100 {
|
||||||
|
next = items[99].Version
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"items": items, "next": next})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if parts[2] == "restore" && len(parts) == 3 && r.Method == "POST" {
|
||||||
|
var input struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Revision int64 `json:"revision"`
|
||||||
|
}
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if input.Version < 1 || input.Revision < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("If-Match") == "" {
|
||||||
|
w.WriteHeader(428)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("If-Match") != `"`+strconv.FormatInt(input.Version, 10)+`"` {
|
||||||
|
w.WriteHeader(412)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, e := s.store.RestoreContactRevision(r.Context(), domain, actor, parts[1], input.Revision, input.Version)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("ETag", store.ContactETag(c))
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if key == "items" && r.Method == "GET" {
|
||||||
|
items, next, e := s.store.ListContacts(r.Context(), domain, actor, r.URL.Query().Get("q"), r.URL.Query().Get("after"), r.URL.Query().Get("deleted") == "1")
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"items": items, "next": next})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if key == "import" && r.Method == "POST" {
|
||||||
|
raw, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 65536))
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, e := s.store.SaveContact(r.Context(), domain, actor, store.Contact{UUID: uuid.NewString(), VCard: string(raw)}, true)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 201, map[string]any{"item": c})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := strings.TrimPrefix(key, "items/")
|
||||||
|
export := strings.HasSuffix(id, ".vcf")
|
||||||
|
if export {
|
||||||
|
id = strings.TrimSuffix(id, ".vcf")
|
||||||
|
}
|
||||||
|
if key != "items" {
|
||||||
|
if u, e := uuid.Parse(id); e != nil || u.String() != id {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if key != "items" && (r.Method == "GET" || r.Method == "HEAD") {
|
||||||
|
c, e := s.store.Contact(r.Context(), domain, actor, id)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("ETag", `"`+strconv.FormatInt(c.Version, 10)+`"`)
|
||||||
|
if export {
|
||||||
|
w.Header().Set("Content-Type", "text/vcard; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="contact.vcf"`)
|
||||||
|
w.Write([]byte(c.VCard))
|
||||||
|
} else {
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !export && (key == "items" && r.Method == "POST" || key != "items" && r.Method == "PUT") {
|
||||||
|
var c store.Contact
|
||||||
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 128<<10))
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if decoder.Decode(&c) != nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if key == "items" {
|
||||||
|
if c.Version != 0 {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if c.UUID != id {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("If-Match") == "" {
|
||||||
|
w.WriteHeader(428)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("If-Match") != `"`+strconv.FormatInt(c.Version, 10)+`"` {
|
||||||
|
taskError(w, store.ErrTaskConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, e := s.store.SaveContact(r.Context(), domain, actor, c, false)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("ETag", `"`+strconv.FormatInt(c.Version, 10)+`"`)
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Allow", "GET, HEAD, POST, PUT")
|
||||||
|
w.WriteHeader(405)
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"net/http/httptest"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestContactsPreserveImportAndIsolation(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
raw := "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:person\r\nFN:田中\r\nEMAIL;TYPE=work:tanaka@example.invalid\r\nTEL;TYPE=cell:1234\r\nX-PRIVATE:keep\\,this\r\nPHOTO:https://example.invalid/do-not-fetch\r\nEND:VCARD\r\n"
|
||||||
|
c, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), VCard: raw}, true)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
repeat, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), VCard: raw}, true)
|
||||||
|
if e != nil || repeat.UUID != c.UUID {
|
||||||
|
t.Fatal("not idempotent", e)
|
||||||
|
}
|
||||||
|
c.Name = "変更"
|
||||||
|
c, e = s.store.SaveContact(ctx, domain, actor, c, false)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for _, preserved := range []string{"EMAIL;TYPE=work:", "TEL;TYPE=cell:", "X-PRIVATE:keep\\,this", "PHOTO:https:"} {
|
||||||
|
if !strings.Contains(c.VCard, preserved) {
|
||||||
|
t.Fatal("lost", preserved)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
old := c
|
||||||
|
old.Version--
|
||||||
|
if _, e = s.store.SaveContact(ctx, domain, actor, old, false); e != store.ErrTaskConflict {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e = s.store.Contact(ctx, domain, uuid.NewString(), c.UUID); e == nil {
|
||||||
|
t.Fatal("other user read")
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest("GET", "http://localhost"+contactsAPI+"items?q=tanaka", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.handleContacts(w, req)
|
||||||
|
if w.Code != 200 || !strings.Contains(w.Body.String(), "変更") {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
c.Deleted = true
|
||||||
|
if _, e = s.store.SaveContact(ctx, domain, actor, c, false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
items, _, e := s.store.Contacts(ctx, domain, actor, "", "")
|
||||||
|
if e != nil || len(items) != 0 {
|
||||||
|
t.Fatal(items, e)
|
||||||
|
}
|
||||||
|
if e = s.setSystemExtensionEnabled(domain, "organizer.contacts", false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e = s.store.Contact(ctx, domain, actor, c.UUID); e != store.ErrAccessDenied {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestContactFormatValidation(t *testing.T) {
|
||||||
|
for _, raw := range []string{"BEGIN:VCARD\nVERSION:2.1\nFN:x\nEND:VCARD\n", "BEGIN:VCARD\nVERSION:4.0\nFN;ENCODING=QUOTED-PRINTABLE:x\nEND:VCARD\n", "BEGIN:VCARD\nVERSION:4.0\nFN:x\nmalformed\nEND:VCARD\n"} {
|
||||||
|
if _, e := store.ParseContact(raw); e == nil {
|
||||||
|
t.Fatal("accepted malformed/legacy")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw := "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:" + strings.Repeat("名", 90) + "\r\nNOTE:one\\ntwo\r\nEND:VCARD\r\n"
|
||||||
|
c, e := store.ParseContact(raw)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
again, e := store.ParseContact(c.VCard)
|
||||||
|
if e != nil || again.Name != c.Name || again.Notes != "one\ntwo" {
|
||||||
|
t.Fatal(again, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,6 +40,9 @@ func (s *Server) davActor(w http.ResponseWriter, r *http.Request, requested stri
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
w.Header().Set("WWW-Authenticate", `Basic realm="PagesWiki CalDAV", charset="UTF-8"`)
|
w.Header().Set("WWW-Authenticate", `Basic realm="PagesWiki CalDAV", charset="UTF-8"`)
|
||||||
|
if requested == "contacts" {
|
||||||
|
w.Header().Set("WWW-Authenticate", `Basic realm="PagesWiki CardDAV", charset="UTF-8"`)
|
||||||
|
}
|
||||||
w.WriteHeader(401)
|
w.WriteHeader(401)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -87,11 +90,11 @@ func (s *Server) handleDAVHome(w http.ResponseWriter, r *http.Request) {
|
|||||||
{Space: calNS, Local: "calendar-home-set"}: "<d:href>" + calendarDAV + "</d:href>",
|
{Space: calNS, Local: "calendar-home-set"}: "<d:href>" + calendarDAV + "</d:href>",
|
||||||
}}}
|
}}}
|
||||||
rows[0].props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] = davPrivileges(false)
|
rows[0].props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] = davPrivileges(false)
|
||||||
if writable && tasks && scope != "calendar" {
|
if writable && tasks && (scope == "tasks" || scope == "all") {
|
||||||
rows[0].props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] += "<d:privilege><d:bind/></d:privilege>"
|
rows[0].props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] += "<d:privilege><d:bind/></d:privilege>"
|
||||||
}
|
}
|
||||||
if r.Header.Get("Depth") == "1" {
|
if r.Header.Get("Depth") == "1" {
|
||||||
if calendars && scope != "tasks" {
|
if calendars && (scope == "calendar" || scope == "all") {
|
||||||
repo, err := s.calendars()
|
repo, err := s.calendars()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
calendarError(w, err)
|
calendarError(w, err)
|
||||||
@@ -108,7 +111,7 @@ func (s *Server) handleDAVHome(w http.ResponseWriter, r *http.Request) {
|
|||||||
rows = append(rows, row)
|
rows = append(rows, row)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if tasks && scope != "calendar" {
|
if tasks && (scope == "tasks" || scope == "all") {
|
||||||
row := taskDAVCollectionRow()
|
row := taskDAVCollectionRow()
|
||||||
title, err := s.store.TaskDAVDefaultTitle(r.Context(), domain, actor)
|
title, err := s.store.TaskDAVDefaultTitle(r.Context(), domain, actor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -137,7 +140,7 @@ func davPrivileges(write bool) string {
|
|||||||
func (s *Server) handleDAVCredentials(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleDAVCredentials(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Cache-Control", "private, no-store")
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
domain := s.domainUUIDForRequest(r)
|
domain := s.domainUUIDForRequest(r)
|
||||||
if !s.systemExtensionEnabled(domain, "organizer.tasks") && !s.systemExtensionEnabled(domain, "organizer.calendar") {
|
if !s.systemExtensionEnabled(domain, "organizer.tasks") && !s.systemExtensionEnabled(domain, "organizer.calendar") && !s.systemExtensionEnabled(domain, "organizer.contacts") {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ func (s *Server) withStandbyReadOnly(next http.Handler) http.Handler {
|
|||||||
// V1 standby does not serve organizer or DAV endpoints: their current
|
// V1 standby does not serve organizer or DAV endpoints: their current
|
||||||
// read paths repair file-backed indexes and update credential metadata.
|
// read paths repair file-backed indexes and update credential metadata.
|
||||||
// They become available after promotion; no false successful sync responses.
|
// They become available after promotion; no false successful sync responses.
|
||||||
for _, prefix := range []string{"/v/plan", "/v/calendar", "/v/event", "/v/tasks", "/_/api/v1/calendar", "/_/api/v1/caldav", "/_/api/v1/task", "/_/api/v1/extension/", "/.well-known/caldav"} {
|
for _, prefix := range []string{"/v/plan", "/v/calendar", "/v/event", "/v/tasks", "/_/api/v1/calendar", "/_/api/v1/caldav", "/_/api/v1/carddav", "/_/api/v1/task", "/_/api/v1/extension/", "/.well-known/caldav", "/.well-known/carddav"} {
|
||||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||||
fail("organizer/DAV read service requires DR promotion in this version")
|
fail("organizer/DAV read service requires DR promotion in this version")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ func (s *Server) registeredEventHandlers() *dregarnuhr.Registry {
|
|||||||
s.eventHandlersOnce.Do(func() {
|
s.eventHandlersOnce.Do(func() {
|
||||||
registry := &dregarnuhr.Registry{}
|
registry := &dregarnuhr.Registry{}
|
||||||
handlers := map[string]dregarnuhr.Handler{
|
handlers := map[string]dregarnuhr.Handler{
|
||||||
|
store.TaskDigestEventType: s.deliverTaskDigests,
|
||||||
store.NotificationPushEventType: func(ctx context.Context, job *store.EventJob) error {
|
store.NotificationPushEventType: func(ctx context.Context, job *store.EventJob) error {
|
||||||
return s.deliverNotificationPushContext(ctx, job)
|
return s.deliverNotificationPushContext(ctx, job)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -73,6 +73,9 @@ func (s *Server) startEventScheduler() {
|
|||||||
if err := s.store.EnsureTaskFocusEvent(); err != nil {
|
if err := s.store.EnsureTaskFocusEvent(); err != nil {
|
||||||
log.Printf("focus timer initialization failed: %v", err)
|
log.Printf("focus timer initialization failed: %v", err)
|
||||||
}
|
}
|
||||||
|
if err := s.store.EnsureTaskDigestEvent(); err != nil {
|
||||||
|
log.Printf("task digest initialization failed: %v", err)
|
||||||
|
}
|
||||||
if err := s.store.EnsureNotificationPushEvent(); err != nil {
|
if err := s.store.EnsureNotificationPushEvent(); err != nil {
|
||||||
log.Printf("notification push initialization failed: %v", err)
|
log.Printf("notification push initialization failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,12 @@ func SetDAVAuthOutcome(r *http.Request, outcome string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func davLogTarget(path string) string {
|
func davLogTarget(path string) string {
|
||||||
|
if path == "/.well-known/carddav" {
|
||||||
|
return "carddav_discovery"
|
||||||
|
}
|
||||||
|
if path == "/_/api/v1/carddav" || strings.HasPrefix(path, "/_/api/v1/carddav/") {
|
||||||
|
return "carddav"
|
||||||
|
}
|
||||||
const root = "/_/api/v1/caldav"
|
const root = "/_/api/v1/caldav"
|
||||||
p := strings.TrimSuffix(path, "/")
|
p := strings.TrimSuffix(path, "/")
|
||||||
switch p {
|
switch p {
|
||||||
|
|||||||
@@ -80,6 +80,8 @@ func TestDAVLogTarget(t *testing.T) {
|
|||||||
"/_/api/v1/caldav/tasks/default/private.ics": "task_resource",
|
"/_/api/v1/caldav/tasks/default/private.ics": "task_resource",
|
||||||
"/_/api/v1/caldav/private/": "calendar_collection",
|
"/_/api/v1/caldav/private/": "calendar_collection",
|
||||||
"/.well-known/caldav": "well_known",
|
"/.well-known/caldav": "well_known",
|
||||||
|
"/.well-known/carddav": "carddav_discovery",
|
||||||
|
"/_/api/v1/carddav/private-owner/private.vcf": "carddav",
|
||||||
"/_/api/v1/caldav-credentials": "", "/health": "",
|
"/_/api/v1/caldav-credentials": "", "/health": "",
|
||||||
} {
|
} {
|
||||||
if got := davLogTarget(path); got != want {
|
if got := davLogTarget(path); got != want {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ func NormalizePath(
|
|||||||
// Hosted adapter assets use directory-relative module and worker URLs.
|
// Hosted adapter assets use directory-relative module and worker URLs.
|
||||||
// DAV collections also require the slash: removing it conflicts with
|
// DAV collections also require the slash: removing it conflicts with
|
||||||
// ServeMux's collection redirect and causes an infinite redirect loop.
|
// ServeMux's collection redirect and causes an infinite redirect loop.
|
||||||
if strings.HasPrefix(p, "/_/adaptor/") || strings.HasPrefix(p, "/_/api/v1/caldav/") {
|
if strings.HasPrefix(p, "/_/adaptor/") || strings.HasPrefix(p, "/_/api/v1/caldav/") || strings.HasPrefix(p, "/_/api/v1/carddav/") {
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestNormalizePathDAVCollections(t *testing.T) {
|
func TestNormalizePathDAVCollections(t *testing.T) {
|
||||||
for _, path := range []string{"/_/api/v1/caldav/", "/_/api/v1/caldav/tasks/", "/_/api/v1/caldav/tasks/default/", "/_/api/v1/caldav/calendar-id/"} {
|
for _, path := range []string{"/_/api/v1/caldav/", "/_/api/v1/caldav/tasks/", "/_/api/v1/caldav/tasks/default/", "/_/api/v1/caldav/calendar-id/", "/_/api/v1/carddav/", "/_/api/v1/carddav/actor/contacts/"} {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(401) })
|
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(401) })
|
||||||
for _, method := range []string{"GET", "OPTIONS", "PROPFIND", "REPORT"} {
|
for _, method := range []string{"GET", "OPTIONS", "PROPFIND", "REPORT"} {
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProductivityChromium(t *testing.T) {
|
||||||
|
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||||
|
t.Skip("opt-in Chromium")
|
||||||
|
}
|
||||||
|
for _, view := range []string{"contacts", "settings", "report", "tasks", "home"} {
|
||||||
|
for _, size := range []string{"desktop", "mobile"} {
|
||||||
|
t.Run(view+"-"+size, func(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { s.renderSearchHome(w, r, "search") })
|
||||||
|
item := newTaskRecord("task", "Browser work task")
|
||||||
|
item.Status = "done"
|
||||||
|
item.Estimate = 60
|
||||||
|
item.Complexity = 3
|
||||||
|
if _, e := s.store.SaveTask(context.Background(), domain, actor, item, 0); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
repo, e := s.calendars()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e = repo.Create(context.Background(), domain, actor, "Command calendar", "local"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
script, e := os.ReadFile("internal/server/testdata/productivity-browser.js")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
path := map[string]string{"contacts": "/v/plan/contacts", "settings": "/v/plan/tasks/settings", "report": "/v/plan/tasks/report", "tasks": "/v/plan/tasks", "home": "/"}[view]
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if r.Method == "GET" && r.URL.Path == path {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||||
|
for k, v := range rec.Header() {
|
||||||
|
w.Header()[k] = v
|
||||||
|
}
|
||||||
|
w.WriteHeader(rec.Code)
|
||||||
|
// The home template uses nonce CSP. Reuse its already generated nonce
|
||||||
|
// only in this synthetic fixture; production HTML is never rewritten.
|
||||||
|
nonce := ""
|
||||||
|
if csp := rec.Header().Get("Content-Security-Policy"); strings.Contains(csp, "'nonce-") {
|
||||||
|
nonce = strings.SplitN(strings.SplitN(csp, "'nonce-", 2)[1], "'", 2)[0]
|
||||||
|
}
|
||||||
|
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", "<script nonce=\""+nonce+"\">"+string(script)+"</script></body>", 1)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
width, height := "1440", "1000"
|
||||||
|
if size == "mobile" {
|
||||||
|
width, height = "390", "844"
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
shot := ""
|
||||||
|
if prefix := os.Getenv("PAGESWIKI_PRODUCTIVITY_SCREENSHOT"); prefix != "" {
|
||||||
|
shot = prefix + "-" + view + "-" + size + ".png"
|
||||||
|
}
|
||||||
|
out, e := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+path, t.TempDir(), shot, width, height).CombinedOutput()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatalf("%v: %s", e, out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -84,6 +84,10 @@ func sendMagicLinkSMTPWithTLS(ctx context.Context, config store.AuthProviderConf
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
return deliverSMTPMessage(ctx, config, host, sender, addressee, message, tlsOverride)
|
||||||
|
}
|
||||||
|
|
||||||
|
func deliverSMTPMessage(ctx context.Context, config store.AuthProviderConfig, host, sender, addressee string, message []byte, tlsOverride *tls.Config) error {
|
||||||
ctx, cancel := context.WithTimeout(ctx, smtpDeliveryTimeout)
|
ctx, cancel := context.WithTimeout(ctx, smtpDeliveryTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
connection, err := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, "tcp", config.SMTPAddress)
|
connection, err := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, "tcp", config.SMTPAddress)
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskCalendarCapture(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
repo, e := s.calendars()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
c, e := repo.Create(context.Background(), domain, actor, "Command calendar", "local")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
input := map[string]any{"request_id": uuid.NewString(), "calendar_uuid": c.ID, "title": "会議", "from": "2026-11-02T09:00", "to": "2026-11-02T10:00"}
|
||||||
|
for range 2 {
|
||||||
|
w := taskRequest(s, token, "POST", "calendar-capture", input, "")
|
||||||
|
if w.Code != 201 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os/exec"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskCLIHTTPIntegration(t *testing.T) {
|
||||||
|
if _, e := exec.LookPath("python3"); e != nil {
|
||||||
|
t.Skip("python3 not installed")
|
||||||
|
}
|
||||||
|
s, token, _, _ := taskFixture(t)
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.Host = "localhost"
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
cmd := exec.CommandContext(ctx, "python3", "pages-cli/test_task_integration.py")
|
||||||
|
b, _ := json.Marshal(map[string]string{"origin": server.URL, "token": token, "root": t.TempDir()})
|
||||||
|
cmd.Stdin = bytes.NewReader(b)
|
||||||
|
if out, e := cmd.CombinedOutput(); e != nil {
|
||||||
|
t.Fatalf("CLI task integration %v: %s", e, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -64,6 +64,9 @@ func (s *Server) handleTaskDAVCredentials(w http.ResponseWriter, r *http.Request
|
|||||||
if body.Scope != "tasks" {
|
if body.Scope != "tasks" {
|
||||||
endpoint = calendarDAV
|
endpoint = calendarDAV
|
||||||
}
|
}
|
||||||
|
if body.Scope == "contacts" {
|
||||||
|
endpoint = contactDAV
|
||||||
|
}
|
||||||
response := map[string]any{"credential": credential, "username": credential.ID, "password": password, "url": endpoint}
|
response := map[string]any{"credential": credential, "username": credential.ID, "password": password, "url": endpoint}
|
||||||
if body.Scope == "tasks" {
|
if body.Scope == "tasks" {
|
||||||
response["collection"] = taskDAVCollection
|
response["collection"] = taskDAVCollection
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func sendTaskDigestSMTP(ctx context.Context, config store.AuthProviderConfig, recipient, day, body string) error {
|
||||||
|
// Reuse envelope validation and bounded TLS-aware SMTP transport, without
|
||||||
|
// exposing SMTP credentials, recipient or task content to job logs.
|
||||||
|
host, from, to, _, err := smtpMessage(config, recipient, "https://pages.invalid/")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sender, _ := smtpMailbox(config.SMTPFrom)
|
||||||
|
addressee, _ := smtpMailbox(recipient)
|
||||||
|
if len(body) > 128<<10 || len(day) != 10 || strings.ContainsAny(day, "\r\n\x00") {
|
||||||
|
return store.ErrTaskInvalid
|
||||||
|
}
|
||||||
|
encoded := base64.StdEncoding.EncodeToString([]byte(body))
|
||||||
|
var lines strings.Builder
|
||||||
|
for len(encoded) > 76 {
|
||||||
|
lines.WriteString(encoded[:76] + "\r\n")
|
||||||
|
encoded = encoded[76:]
|
||||||
|
}
|
||||||
|
lines.WriteString(encoded + "\r\n")
|
||||||
|
message := []byte(fmt.Sprintf("To: %s\r\nFrom: %s\r\nSubject: PagesWiki tasks %s\r\nDate: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n%s", addressee.String(), sender.String(), day, time.Now().Format(time.RFC1123Z), lines.String()))
|
||||||
|
return deliverSMTPMessage(ctx, config, host, from, to, message, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) deliverTaskDigests(ctx context.Context, job *store.EventJob) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
due, err := s.store.DueTaskDigests(ctx, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sent, uncertain := 0, 0
|
||||||
|
for _, candidate := range due {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
claim, e := s.store.ClaimTaskDigest(ctx, candidate, time.Now())
|
||||||
|
if errors.Is(e, sql.ErrNoRows) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
state := "cancelled"
|
||||||
|
if s.systemExtensionEnabled(claim.Domain, "organizer.tasks") {
|
||||||
|
config, e := s.store.AuthProviderConfig(claim.Domain, "smtp")
|
||||||
|
if e == nil && config.Enabled {
|
||||||
|
items, next, e := s.store.ListTasks(ctx, claim.Domain, claim.Owner, store.TaskQuery{Kind: "task", View: "today", Today: claim.Day, Limit: 100})
|
||||||
|
if e == nil {
|
||||||
|
var body strings.Builder
|
||||||
|
host, _ := s.store.GetDomainEffectiveHost(claim.Domain)
|
||||||
|
base := ""
|
||||||
|
if host != "" && !strings.ContainsAny(host, "/\\\r\n\t @") {
|
||||||
|
base = "https://" + host
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&body, "Tasks / やることリスト — %s (%s)\n\n", claim.Day, claim.Timezone)
|
||||||
|
if len(items) == 0 {
|
||||||
|
body.WriteString("No tasks due or planned today. / 今日の対象タスクはありません。\n")
|
||||||
|
}
|
||||||
|
for _, item := range items {
|
||||||
|
fmt.Fprintf(&body, "- %s\n due/期限: %s | planned/予定: %s | estimate/見積: %d min\n %s/v/plan/task/%s\n", item.Title, item.DueOn, item.PlannedOn, item.Estimate, base, item.UUID)
|
||||||
|
}
|
||||||
|
if next != "" {
|
||||||
|
body.WriteString("\nFirst 100 items only. / 最初の100件です。続きはタスク画面で確認してください。\n")
|
||||||
|
}
|
||||||
|
// Check consent and current account email immediately before send.
|
||||||
|
if recipient, e := s.store.TaskDigestRecipient(ctx, claim); e == nil {
|
||||||
|
state = "uncertain"
|
||||||
|
if e = sendTaskDigestSMTP(ctx, config, recipient, claim.Day, body.String()); e == nil {
|
||||||
|
state = "sent"
|
||||||
|
sent++
|
||||||
|
} else {
|
||||||
|
uncertain++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Persist delivery outcome even if the scheduler context was cancelled.
|
||||||
|
finish, stop := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
e = s.store.FinishTaskDigest(finish, claim, state)
|
||||||
|
stop()
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(due) > 0 {
|
||||||
|
s.addEventProgressLog(ctx, job, fmt.Sprintf("task digest checked=%d sent=%d uncertain=%d", len(due), sent, uncertain))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
cal "pageswiki/internal/calendar"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func taskJSON(w http.ResponseWriter, r *http.Request, output any) bool {
|
||||||
|
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32768))
|
||||||
|
d.DisallowUnknownFields()
|
||||||
|
if d.Decode(output) != nil || d.Decode(&struct{}{}) != io.EOF {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultTask(p store.TaskPreferences, now time.Time) store.TaskRecord {
|
||||||
|
item := store.TaskRecord{Kind: "task", Status: "todo", Bucket: "inbox", Priority: 1, ProjectUUID: p.ProjectUUID, AssigneeUUID: p.AssigneeUUID, Estimate: p.Estimate, Complexity: p.Complexity}
|
||||||
|
for _, date := range []struct {
|
||||||
|
offset *int
|
||||||
|
target *string
|
||||||
|
}{{p.DueDays, &item.DueOn}, {p.StartDays, &item.StartOn}, {p.PlannedDays, &item.PlannedOn}, {p.ReviewDays, &item.ReviewOn}} {
|
||||||
|
if date.offset != nil {
|
||||||
|
*date.target = now.AddDate(0, 0, *date.offset).Format("2006-01-02")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return item
|
||||||
|
}
|
||||||
|
|
||||||
|
type taskCaptureInput struct {
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
ProjectUUID *string `json:"project_uuid"`
|
||||||
|
AssigneeUUID *string `json:"assignee_uuid"`
|
||||||
|
DueOn *string `json:"due_on"`
|
||||||
|
StartOn *string `json:"start_on"`
|
||||||
|
PlannedOn *string `json:"planned_on"`
|
||||||
|
ReviewOn *string `json:"review_on"`
|
||||||
|
Estimate *int `json:"estimate_minutes"`
|
||||||
|
Complexity *int `json:"complexity"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if r.Method != "GET" && !active {
|
||||||
|
taskError(w, store.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch kind {
|
||||||
|
case "calendar-capture":
|
||||||
|
if r.Method == "POST" {
|
||||||
|
if !s.systemExtensionEnabled(domain, "organizer.calendar") {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var input struct {
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
CalendarUUID string `json:"calendar_uuid"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Start string `json:"from"`
|
||||||
|
End string `json:"to"`
|
||||||
|
}
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if id, e := uuid.Parse(input.RequestID); e != nil || id.String() != input.RequestID || strings.TrimSpace(input.Title) == "" || len(input.Title) > 300 {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, _, e := s.store.ListTasks(r.Context(), domain, actor, store.TaskQuery{Kind: "task", View: "all", Today: time.Now().In(s.getLocation(domain)).Format("2006-01-02"), Limit: 1}); e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
parse := func(value string) (time.Time, error) {
|
||||||
|
if strings.HasSuffix(value, "Z") || len(value) > 19 {
|
||||||
|
return time.Parse(time.RFC3339, value)
|
||||||
|
}
|
||||||
|
v, e := time.ParseInLocation("2006-01-02T15:04", value, s.getLocation(domain))
|
||||||
|
if e == nil && v.Format("2006-01-02T15:04") != value {
|
||||||
|
e = store.ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return v, e
|
||||||
|
}
|
||||||
|
start, e1 := parse(input.Start)
|
||||||
|
end, e2 := parse(input.End)
|
||||||
|
if e1 != nil || e2 != nil || !end.After(start) || end.Sub(start) > 31*24*time.Hour {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
repo, e := s.calendars()
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
event, e := cal.Build("", cal.Event{UID: input.RequestID, Summary: input.Title, Start: start, End: end})
|
||||||
|
if e != nil {
|
||||||
|
calendarError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, event, e := repo.TaskBlock(r.Context(), domain, input.CalendarUUID, actor, input.RequestID, &event)
|
||||||
|
if e != nil {
|
||||||
|
calendarError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 201, map[string]any{"uid": event.UID, "calendar": c.PrettyName})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "preferences":
|
||||||
|
if r.Method == "GET" {
|
||||||
|
p, err := s.store.TaskPreferences(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.Version == 0 {
|
||||||
|
p.Timezone = s.getTimezoneName(domain)
|
||||||
|
}
|
||||||
|
last, err := s.store.LastTaskDigest(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"preferences": p, "defaults": defaultTask(p, time.Now().In(s.getLocation(domain))), "timezone": s.getTimezoneName(domain), "last_digest": last})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "PUT" {
|
||||||
|
var p store.TaskPreferences
|
||||||
|
if !taskJSON(w, r, &p) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.DigestEnabled {
|
||||||
|
principal, err := s.store.PrincipalForSession(domain, s.authTokenFromRequest(r))
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, store.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = smtpMailbox(principal.Email); err != nil {
|
||||||
|
writeEventJSON(w, 422, map[string]string{"error": "email_required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
config, err := s.store.AuthProviderConfig(domain, "smtp")
|
||||||
|
if err != nil || !config.Enabled {
|
||||||
|
writeEventJSON(w, 422, map[string]string{"error": "smtp_unavailable"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p, err := s.store.SaveTaskPreferences(r.Context(), domain, actor, p, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"preferences": p})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "capture":
|
||||||
|
if r.Method == "POST" {
|
||||||
|
var input taskCaptureInput
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if id, err := uuid.Parse(input.RequestID); err != nil || id.String() != input.RequestID {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p, err := s.store.TaskPreferences(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item := defaultTask(p, time.Now().In(s.getLocation(domain)))
|
||||||
|
item.Title = input.Title
|
||||||
|
item.Notes = input.Notes
|
||||||
|
for _, v := range []struct {
|
||||||
|
from *string
|
||||||
|
to *string
|
||||||
|
}{{input.ProjectUUID, &item.ProjectUUID}, {input.AssigneeUUID, &item.AssigneeUUID}, {input.DueOn, &item.DueOn}, {input.StartOn, &item.StartOn}, {input.PlannedOn, &item.PlannedOn}, {input.ReviewOn, &item.ReviewOn}} {
|
||||||
|
if v.from != nil {
|
||||||
|
*v.to = *v.from
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if input.Estimate != nil {
|
||||||
|
item.Estimate = *input.Estimate
|
||||||
|
}
|
||||||
|
if input.Complexity != nil {
|
||||||
|
item.Complexity = *input.Complexity
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(input)
|
||||||
|
hash := sha256.Sum256(raw)
|
||||||
|
item, err = s.store.CaptureTask(r.Context(), domain, actor, input.RequestID, hex.EncodeToString(hash[:]), item)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.taskResponse(w, r, item, 201)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "work":
|
||||||
|
if r.Method == "GET" {
|
||||||
|
v, err := s.store.ActiveTaskWork(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": v, "server_now_ms": time.Now().UnixMilli()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "POST" {
|
||||||
|
var input struct {
|
||||||
|
store.TaskWork
|
||||||
|
Action string `json:"action"`
|
||||||
|
}
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, err := s.store.ChangeTaskWork(r.Context(), domain, actor, input.Action, input.TaskWork, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": v, "server_now_ms": time.Now().UnixMilli()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "report":
|
||||||
|
if r.Method == "GET" {
|
||||||
|
now := time.Now().In(s.getLocation(domain))
|
||||||
|
end := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location())
|
||||||
|
start := end.AddDate(-1, 0, 0)
|
||||||
|
for _, v := range []struct {
|
||||||
|
key string
|
||||||
|
target *time.Time
|
||||||
|
}{{"from", &start}, {"to", &end}} {
|
||||||
|
if value := r.URL.Query().Get(v.key); value != "" {
|
||||||
|
parsed, err := time.ParseInLocation("2006-01-02", value, now.Location())
|
||||||
|
if err != nil || parsed.Format("2006-01-02") != value {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
*v.target = parsed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report, err := s.store.TaskReport(r.Context(), domain, actor, start, end, now)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, report)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.Header().Set("Allow", map[string]string{"calendar-capture": "POST", "capture": "POST", "work": "GET, POST", "report": "GET", "preferences": "GET, PUT"}[kind])
|
||||||
|
w.WriteHeader(405)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleTaskProductivityPage(w http.ResponseWriter, r *http.Request, active bool) {
|
||||||
|
view := strings.TrimPrefix(r.URL.Path, "/v/plan/tasks/")
|
||||||
|
s.renderWithContext(w, r, "task_productivity.gohtml", map[string]any{"Title": "Tasks", "ProductivityView": view, "TaskWritable": active, "Path": r.URL.Path})
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskDigestSMTPContent(t *testing.T) {
|
||||||
|
address, _, done := fakeSMTP(t, "", false)
|
||||||
|
body := "やること\n- 私用タスク\n"
|
||||||
|
if e := sendTaskDigestSMTP(context.Background(), store.AuthProviderConfig{SMTPAddress: address, SMTPFrom: "wiki@example.test"}, "reader@example.test", "2026-11-01", body); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
result := <-done
|
||||||
|
parts := strings.SplitN(strings.ReplaceAll(result.message, "\r\n", "\n"), "\n\n", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
t.Fatal("missing MIME body")
|
||||||
|
}
|
||||||
|
decoded, e := base64.StdEncoding.DecodeString(strings.Join(strings.Fields(parts[1]), ""))
|
||||||
|
if e != nil || string(decoded) != body {
|
||||||
|
t.Fatal("body encoding", e)
|
||||||
|
}
|
||||||
|
if !strings.Contains(parts[0], "Subject: PagesWiki tasks 2026-11-01") || strings.Contains(parts[0], "私用") {
|
||||||
|
t.Fatal("wrong headers")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskCaptureDefaultsReplayAndPermissions(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
days := 2
|
||||||
|
p := store.TaskPreferences{AssigneeUUID: actor, DueDays: &days, Complexity: 3, Estimate: 60, Timezone: "Asia/Tokyo", DigestTime: "09:00"}
|
||||||
|
p, err := s.store.SaveTaskPreferences(ctx, domain, actor, p, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
id := uuid.NewString()
|
||||||
|
input := map[string]any{"request_id": id, "title": "Mail task", "notes": "Subject only"}
|
||||||
|
w := taskRequest(s, token, "POST", "capture", input, "")
|
||||||
|
if w.Code != 201 {
|
||||||
|
t.Fatalf("capture %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
var response struct {
|
||||||
|
Item store.TaskRecord `json:"item"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if response.Item.Complexity != 3 || response.Item.Estimate != 60 || response.Item.AssigneeUUID != actor || response.Item.DueOn == "" {
|
||||||
|
t.Fatalf("defaults missing %+v", response.Item)
|
||||||
|
}
|
||||||
|
p.Estimate = 120
|
||||||
|
if _, err = s.store.SaveTaskPreferences(ctx, domain, actor, p, time.Now()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||||
|
t.Fatalf("retry %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
loaded, err := s.store.GetTask(ctx, domain, actor, id)
|
||||||
|
if err != nil || loaded.Estimate != 60 || loaded.Version != 1 {
|
||||||
|
t.Fatal(loaded, err)
|
||||||
|
}
|
||||||
|
input["title"] = "Different"
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 412 {
|
||||||
|
t.Fatalf("conflicting replay %d", w.Code)
|
||||||
|
}
|
||||||
|
input["request_id"] = uuid.NewString()
|
||||||
|
input["due_on"] = ""
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil || response.Item.DueOn != "" {
|
||||||
|
t.Fatal("explicit clear lost", err)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, "", "POST", "capture", input, ""); w.Code == 201 {
|
||||||
|
t.Fatal("anonymous capture")
|
||||||
|
}
|
||||||
|
if err = s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, err = s.store.CreateAuthSession(domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 403 {
|
||||||
|
t.Fatal("readonly capture", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskWorkReportSplitsMidnightAndCompletion(t *testing.T) {
|
||||||
|
s, _, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
item := newTaskRecord("task", "Tracked task")
|
||||||
|
item.Estimate = 60
|
||||||
|
item.Complexity = 3
|
||||||
|
item, err := s.store.SaveTask(ctx, domain, actor, item, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
loc, _ := time.LoadLocation("Asia/Tokyo")
|
||||||
|
start := time.Date(2026, 11, 1, 23, 30, 0, 0, loc)
|
||||||
|
end := start.Add(90 * time.Minute)
|
||||||
|
v, err := s.store.ChangeTaskWork(ctx, domain, actor, "start", store.TaskWork{UUID: uuid.NewString(), TaskUUID: item.UUID}, start)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.ChangeTaskWork(ctx, domain, actor, "start", store.TaskWork{UUID: uuid.NewString(), TaskUUID: item.UUID}, start); err != store.ErrTaskConflict {
|
||||||
|
t.Fatal("second active timer", err)
|
||||||
|
}
|
||||||
|
v, err = s.store.ChangeTaskWork(ctx, domain, actor, "stop", v, end)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if again, e := s.store.ChangeTaskWork(ctx, domain, actor, "stop", v, end.Add(time.Hour)); e != nil || again.EndMS != v.EndMS {
|
||||||
|
t.Fatal("stop replay changed duration", e)
|
||||||
|
}
|
||||||
|
a := time.Date(2026, 11, 1, 0, 0, 0, 0, loc)
|
||||||
|
report, err := s.store.TaskReport(ctx, domain, actor, a, a.AddDate(0, 0, 2), end)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(report.Tasks) != 1 || report.Tasks[0].WorkMS != 90*60000 || report.Days[0].WorkMS != 30*60000 || report.Days[1].WorkMS != 60*60000 {
|
||||||
|
t.Fatalf("wrong split %+v", report)
|
||||||
|
}
|
||||||
|
item.Status = "done"
|
||||||
|
item, err = s.store.SaveTask(ctx, domain, actor, item, item.Version)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
now := time.Now().In(loc)
|
||||||
|
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
|
||||||
|
report, err = s.store.TaskReport(ctx, domain, actor, day, day.AddDate(0, 0, 1), now)
|
||||||
|
if err != nil || report.Days[0].Points != 7 || report.Days[0].Completed != 1 {
|
||||||
|
t.Fatal("points", report, err)
|
||||||
|
}
|
||||||
|
item.Status = "todo"
|
||||||
|
if _, err = s.store.SaveTask(ctx, domain, actor, item, item.Version); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
report, err = s.store.TaskReport(ctx, domain, actor, day, day.AddDate(0, 0, 1), now)
|
||||||
|
if err != nil || report.Days[0].Points != 0 {
|
||||||
|
t.Fatal("reopen did not retract", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskDigestClaimOnceAndOptOut(t *testing.T) {
|
||||||
|
s, _, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
now := time.Date(2026, 11, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
p := store.TaskPreferences{Complexity: 1, DigestEnabled: true, DigestTime: "09:00", Timezone: "UTC"}
|
||||||
|
p, err := s.store.SaveTaskPreferences(ctx, domain, actor, p, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if rows, e := s.store.DueTaskDigests(ctx, now); e != nil || len(rows) != 0 {
|
||||||
|
t.Fatal(rows, e)
|
||||||
|
}
|
||||||
|
now = now.Add(2 * time.Hour)
|
||||||
|
due, err := s.store.DueTaskDigests(ctx, now)
|
||||||
|
if err != nil || len(due) != 1 {
|
||||||
|
t.Fatal(due, err)
|
||||||
|
}
|
||||||
|
claim, err := s.store.ClaimTaskDigest(ctx, due[0], now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, e := s.store.ClaimTaskDigest(ctx, due[0], now); e == nil {
|
||||||
|
t.Fatal("double claim")
|
||||||
|
}
|
||||||
|
if err = s.store.FinishTaskDigest(ctx, claim, "sent"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p.DigestEnabled = false
|
||||||
|
if _, err = s.store.SaveTaskPreferences(ctx, domain, actor, p, now); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.TaskDigestRecipient(ctx, claim); err == nil {
|
||||||
|
t.Fatal("opt-out not enforced")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,10 +20,18 @@ import (
|
|||||||
const tasksAPI = "/_/api/v1/extension/organizer.tasks/"
|
const tasksAPI = "/_/api/v1/extension/organizer.tasks/"
|
||||||
|
|
||||||
func taskRoute(p string) bool {
|
func taskRoute(p string) bool {
|
||||||
|
if contactRoute(p) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
return strings.HasPrefix(p, tasksAPI) || p == strings.TrimSuffix(taskDAVRoot, "/") || strings.HasPrefix(p, taskDAVRoot) || p == "/v/plan/today" || p == "/v/plan/tasks" || strings.HasPrefix(p, "/v/plan/tasks/") || p == "/v/plan/projects" || strings.HasPrefix(p, "/v/plan/project/") || strings.HasPrefix(p, "/v/plan/task/")
|
return strings.HasPrefix(p, tasksAPI) || p == strings.TrimSuffix(taskDAVRoot, "/") || strings.HasPrefix(p, taskDAVRoot) || p == "/v/plan/today" || p == "/v/plan/tasks" || strings.HasPrefix(p, "/v/plan/tasks/") || p == "/v/plan/projects" || strings.HasPrefix(p, "/v/plan/project/") || strings.HasPrefix(p, "/v/plan/task/")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) registerTaskRoutes() {
|
func (s *Server) registerTaskRoutes() {
|
||||||
|
s.mux.HandleFunc(contactDAV, s.handleContactDAV)
|
||||||
|
s.mux.HandleFunc(strings.TrimSuffix(contactDAV, "/"), s.handleContactDAV)
|
||||||
|
s.mux.HandleFunc("/.well-known/carddav", s.handleContactDAV)
|
||||||
|
s.mux.HandleFunc(contactsAPI, s.handleContacts)
|
||||||
|
s.mux.HandleFunc("/v/plan/contacts", s.handleContacts)
|
||||||
for _, p := range []string{"/v/plan/today", "/v/plan/tasks", "/v/plan/tasks/", "/v/plan/projects", "/v/plan/project/", "/v/plan/task/"} {
|
for _, p := range []string{"/v/plan/today", "/v/plan/tasks", "/v/plan/tasks/", "/v/plan/projects", "/v/plan/project/", "/v/plan/task/"} {
|
||||||
s.mux.HandleFunc(p, s.handleTaskPage)
|
s.mux.HandleFunc(p, s.handleTaskPage)
|
||||||
}
|
}
|
||||||
@@ -86,6 +94,10 @@ func (s *Server) handleTaskPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
domain := s.domainUUIDForRequest(r)
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if r.URL.Path == "/v/plan/tasks/report" || r.URL.Path == "/v/plan/tasks/settings" {
|
||||||
|
s.handleTaskProductivityPage(w, r, active)
|
||||||
|
return
|
||||||
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/v/plan/tasks/schedule") {
|
if strings.HasPrefix(r.URL.Path, "/v/plan/tasks/schedule") {
|
||||||
s.handleTaskSchedulePage(w, r, actor)
|
s.handleTaskSchedulePage(w, r, actor)
|
||||||
return
|
return
|
||||||
@@ -196,6 +208,10 @@ func (s *Server) handleTasksAPI(w http.ResponseWriter, r *http.Request) {
|
|||||||
r = r.WithContext(ctx)
|
r = r.WithContext(ctx)
|
||||||
domain := s.domainUUIDForRequest(r)
|
domain := s.domainUUIDForRequest(r)
|
||||||
parts := strings.Split(strings.TrimPrefix(r.URL.Path, tasksAPI), "/")
|
parts := strings.Split(strings.TrimPrefix(r.URL.Path, tasksAPI), "/")
|
||||||
|
if len(parts) == 1 && (parts[0] == "calendar-capture" || parts[0] == "capture" || parts[0] == "preferences" || parts[0] == "work" || parts[0] == "report") {
|
||||||
|
s.handleTaskProductivity(w, r, actor, active, parts[0])
|
||||||
|
return
|
||||||
|
}
|
||||||
if len(parts) == 1 && parts[0] == "schedule" {
|
if len(parts) == 1 && parts[0] == "schedule" {
|
||||||
s.handleTaskScheduleAPI(w, r, actor)
|
s.handleTaskScheduleAPI(w, r, actor)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<120;i++){if(fn())return;await new Promise(r=>setTimeout(r,100));}throw Error('Timed out: '+fn.toString());};const fill=(n,value)=>{n.value=value;n.dispatchEvent(new Event('input',{bubbles:true}));};try{
|
||||||
|
const path=location.pathname;
|
||||||
|
if(path==='/v/plan/contacts'){
|
||||||
|
await wait(()=>document.querySelector('#contacts-controls button'));document.querySelector('#contacts-controls button').click();fill(document.querySelector('[name=name]'),'ブラウザ連絡先');fill(document.querySelector('[name=emails]'),'browser@example.invalid');fill(document.querySelector('[name=notes]'),'Non-public notes');document.querySelector('#contact-editor form').requestSubmit();await wait(()=>document.querySelector('#contacts-list button')?.textContent.includes('ブラウザ'));const r=await fetch('/_/api/v1/extension/organizer.contacts/items?q=browser').then(r=>r.json());if(r.items.length!==1)throw Error('Contact save missing');
|
||||||
|
fill(document.querySelector('[name=name]'),'変更後');document.querySelector('#contact-editor form').requestSubmit();await wait(()=>document.querySelector('#contacts-list button')?.textContent.includes('変更後'));
|
||||||
|
await wait(()=>document.querySelector('.contact-history'));document.querySelector('.contact-history').open=true;await wait(()=>document.querySelectorAll('.contact-history-row').length===2);document.querySelectorAll('.contact-history-row')[1].querySelector('button').click();await wait(()=>document.querySelector('.contact-history pre').textContent.includes('ブラウザ連絡先'));
|
||||||
|
window.confirm=()=>true;document.querySelectorAll('.contact-history-row')[1].querySelectorAll('button')[1].click();await wait(()=>document.querySelector('#contacts-list button')?.textContent.includes('ブラウザ'));
|
||||||
|
const exported=await fetch('/_/api/v1/extension/organizer.contacts/export.vcf').then(r=>r.text());if(!exported.includes('ブラウザ連絡先'))throw Error('Export missing');
|
||||||
|
document.querySelector('#tasks-dav-open').click();await wait(()=>document.querySelector('#tasks-dav-dialog').open);const dav=document.querySelector('#tasks-dav-dialog');if(getComputedStyle(dav.querySelector('.dav-compat-toggle')).display!=='none')throw Error('CalDAV-only compatibility visible');fill(dav.querySelector('form>input'),'Browser contact client');dav.querySelector('form').requestSubmit();await wait(()=>!dav.querySelector('section').hidden);const credentials=await fetch('/_/api/v1/caldav-credentials').then(r=>r.json());if(credentials.items.length!==1||credentials.items[0].scope!=='contacts')throw Error('Wrong credential scope');dav.querySelector('tbody button').click();await wait(()=>!dav.querySelector('tbody button'));dav.querySelector('header button').click();
|
||||||
|
}else if(path.endsWith('/settings')){
|
||||||
|
await wait(()=>document.querySelector('[name=due_days]'));fill(document.querySelector('[name=due_days]'),'2');document.querySelector('.productivity-settings').requestSubmit();await wait(()=>document.querySelector('#productivity-status').textContent.includes('保存'));const d=await fetch('/_/api/v1/extension/organizer.tasks/preferences').then(r=>r.json());if(d.preferences.due_days!==2)throw Error('Preferences missing');
|
||||||
|
}else if(path.endsWith('/report')){
|
||||||
|
await wait(()=>document.querySelectorAll('.productivity-day').length>300);if(!document.querySelector('.productivity-day[data-level="2"]'))throw Error('Seven-point completion missing');
|
||||||
|
}else if(path==='/v/plan/tasks'){
|
||||||
|
const prefs=await fetch('/_/api/v1/extension/organizer.tasks/preferences').then(r=>r.json());await fetch('/_/api/v1/extension/organizer.tasks/preferences',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...prefs.preferences,due_days:2,estimate_minutes:60})});
|
||||||
|
await wait(()=>document.querySelector('#tasks-quick-title'));fill(document.querySelector('#tasks-quick-title'),'Recording task');document.querySelector('#tasks-capture').requestSubmit();await wait(()=>document.querySelector('[data-action=work]'));document.querySelector('[data-action=work]').click();await wait(()=>document.querySelector('.task-work-bar a').textContent.includes('Recording task'));document.querySelector('.task-work-bar button').click();await wait(()=>document.querySelector('.task-work-bar').hidden);
|
||||||
|
document.querySelector('[data-action=add-child]').click();const child=document.querySelector('.task-child-capture');fill(child.querySelector('input'),'Defaulted child');child.requestSubmit();await wait(()=>document.querySelectorAll('.task-inline-row').length===2);const children=await fetch('/_/api/v1/extension/organizer.tasks/items?q=Defaulted').then(r=>r.json());if(children.items[0].estimate_minutes!==60||!children.items[0].due_on)throw Error('Subtask defaults missing');
|
||||||
|
}else{
|
||||||
|
const input=document.querySelector('[data-home-type-search]');fill(input,'add task 検証 cost:2h complexity:3');input.closest('form').requestSubmit();await wait(()=>document.querySelector('.home-command-panel button'));document.querySelector('.home-command-panel button').click();await wait(()=>document.querySelector('.home-command-panel a'));const d=await fetch('/_/api/v1/extension/organizer.tasks/items?q='+encodeURIComponent('検証')).then(r=>r.json());if(d.items[0].estimate_minutes!==120)throw Error('Command cost missing');fill(input,'add cal 会議 from:2026-11-02T09:00 to:2026-11-02T10:00');input.closest('form').requestSubmit();await wait(()=>document.querySelector('.home-command-panel button'));document.querySelector('.home-command-panel button').click();await wait(()=>document.querySelector('.home-command-panel a')?.href.includes('/event/'));
|
||||||
|
}
|
||||||
|
if(document.documentElement.scrollWidth>innerWidth+2)throw Error('Page horizontal overflow');document.body.dataset.vimReady='true';
|
||||||
|
}catch(e){const n=document.createElement('pre');n.id='error';n.textContent=(e.stack||String(e))+'\n'+(document.querySelector('.home-command-panel')?.textContent||'');document.body.append(n);}});
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrContactUIDConflict = errors.New("contact UID conflict")
|
||||||
|
var ErrContactSyncToken = errors.New("invalid contact sync token")
|
||||||
|
|
||||||
|
func ContactPropertyValues(c Contact, key string) []string {
|
||||||
|
lines, err := cardLines(c.VCard)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
values := []string{}
|
||||||
|
for _, line := range lines[1 : len(lines)-1] {
|
||||||
|
k, v, e := cardKey(line)
|
||||||
|
if e == nil && k == strings.ToUpper(key) {
|
||||||
|
values = append(values, cardText(v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidContactDAVName(name string) bool {
|
||||||
|
if len(name) < 5 || len(name) > 128 || !strings.HasSuffix(name, ".vcf") || strings.HasPrefix(name, ".") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range name {
|
||||||
|
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("-_.", c)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func ContactETag(c Contact) string { return fmt.Sprintf(`"%d"`, c.Version) }
|
||||||
|
|
||||||
|
type ContactDAVItem struct {
|
||||||
|
Contact
|
||||||
|
Name string
|
||||||
|
Sequence int64
|
||||||
|
Size int
|
||||||
|
}
|
||||||
|
type ContactDAVSnapshot struct {
|
||||||
|
Items []ContactDAVItem
|
||||||
|
Token string
|
||||||
|
More bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scope and epoch bind opaque tokens to this database, domain and owner. Each
|
||||||
|
// resource retains only its latest sequence; soft-deleted rows are tombstones.
|
||||||
|
func (s *Store) ContactDAVSnapshot(ctx context.Context, domain, actor, token string, limit int) (ContactDAVSnapshot, error) {
|
||||||
|
if limit < 0 || limit > 200 {
|
||||||
|
return ContactDAVSnapshot{}, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return s.contactDAVSnapshot(ctx, domain, actor, token, limit, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PROPFIND inventories contain metadata only, never thousands of vCard bodies.
|
||||||
|
// The same read transaction supplies both the inventory and its change token.
|
||||||
|
func (s *Store) ContactDAVInventory(ctx context.Context, domain, actor string) (ContactDAVSnapshot, error) {
|
||||||
|
return s.contactDAVSnapshot(ctx, domain, actor, "", 5000, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) contactDAVSnapshot(ctx context.Context, domain, actor, token string, limit int, metadata bool) (ContactDAVSnapshot, error) {
|
||||||
|
out := ContactDAVSnapshot{Items: []ContactDAVItem{}}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err = taskActor(ctx, tx, domain, actor, false); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err = contactEnabled(ctx, tx, domain); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
var epoch string
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT value FROM organizer_contact_epoch WHERE id=1`).Scan(&epoch); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
hash := sha256.Sum256([]byte(epoch + "\x00" + domain + "\x00" + actor))
|
||||||
|
prefix := "urn:pageswiki:contacts:" + hex.EncodeToString(hash[:]) + ":"
|
||||||
|
var high int64
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(sequence),0) FROM organizer_contact_changes WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&high); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
since := int64(0)
|
||||||
|
if token != "" {
|
||||||
|
if !strings.HasPrefix(token, prefix) {
|
||||||
|
return out, ErrContactSyncToken
|
||||||
|
}
|
||||||
|
since, err = strconv.ParseInt(strings.TrimPrefix(token, prefix), 10, 64)
|
||||||
|
if err != nil || since < 0 || since > high || prefix+strconv.FormatInt(since, 10) != token {
|
||||||
|
return out, ErrContactSyncToken
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.Token = prefix + strconv.FormatInt(high, 10)
|
||||||
|
if limit == 0 {
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
fields := `c.data,n.name,x.sequence,0`
|
||||||
|
if metadata {
|
||||||
|
fields = `json_object('uuid',c.uuid,'version',c.version),n.name,x.sequence,length(CAST(json_extract(c.data,'$.vcard') AS BLOB))`
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT `+fields+` FROM organizer_contact_changes x JOIN organizer_contacts c USING(domain_uuid,owner_uuid,uuid) JOIN organizer_contact_names n USING(domain_uuid,owner_uuid,uuid) WHERE x.domain_uuid=? AND x.owner_uuid=? AND x.sequence>? AND (?<>'' OR c.deleted=0) ORDER BY x.sequence LIMIT ?`, domain, actor, since, token, limit+1)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
if len(out.Items) == limit {
|
||||||
|
out.More = true
|
||||||
|
out.Token = prefix + strconv.FormatInt(out.Items[len(out.Items)-1].Sequence, 10)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
var item ContactDAVItem
|
||||||
|
var raw string
|
||||||
|
if err = rows.Scan(&raw, &item.Name, &item.Sequence, &item.Size); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal([]byte(raw), &item.Contact); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Items = append(out.Items, item)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ContactDAVResource(ctx context.Context, domain, actor, name string) (Contact, error) {
|
||||||
|
if !ValidContactDAVName(name) {
|
||||||
|
return Contact{}, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
var id string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT uuid FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND name=?`, domain, actor, name).Scan(&id)
|
||||||
|
if err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
return s.Contact(ctx, domain, actor, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The version is compared under the same write lock as credential revocation,
|
||||||
|
// membership and extension state. No read-modify-write bypass for DAV clients.
|
||||||
|
func (s *Store) SaveContactDAV(ctx context.Context, domain, actor, credential, name, raw string, version int64, remove bool) (Contact, error) {
|
||||||
|
if !ValidContactDAVName(name) {
|
||||||
|
return Contact{}, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
old, err := s.ContactDAVResource(ctx, domain, actor, name)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
if old.Version != version {
|
||||||
|
return old, ErrTaskConflict
|
||||||
|
}
|
||||||
|
if remove {
|
||||||
|
if old.Version == 0 || old.Deleted {
|
||||||
|
return old, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
old.Deleted = true
|
||||||
|
return s.saveContact(ctx, domain, actor, old, "fields", credential, name)
|
||||||
|
}
|
||||||
|
id := old.UUID
|
||||||
|
if id == "" {
|
||||||
|
id = strings.TrimSuffix(name, ".vcf")
|
||||||
|
if u, e := uuid.Parse(id); e != nil || u.String() != id {
|
||||||
|
id = uuid.NewSHA1(uuid.NameSpaceURL, []byte(domain+"\x00"+actor+"\x00"+name)).String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s.saveContact(ctx, domain, actor, Contact{UUID: id, Version: version, VCard: raw}, "dav", credential, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ContactRevision struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
CreatedMS int64 `json:"created_ms"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ContactHistory(ctx context.Context, domain, actor, id string, before int64) ([]ContactRevision, error) {
|
||||||
|
if _, err := s.Contact(ctx, domain, actor, id); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT version,deleted,created_ms FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND (?=0 OR version<?) ORDER BY version DESC LIMIT 100`, domain, actor, id, before, before)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []ContactRevision{}
|
||||||
|
for rows.Next() {
|
||||||
|
var r ContactRevision
|
||||||
|
if err = rows.Scan(&r.Version, &r.Deleted, &r.CreatedMS); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
func (s *Store) RestoreContactRevision(ctx context.Context, domain, actor, id string, revision, version int64) (Contact, error) {
|
||||||
|
old, err := s.Contact(ctx, domain, actor, id)
|
||||||
|
if err != nil {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
if old.Version != version {
|
||||||
|
return old, ErrTaskConflict
|
||||||
|
}
|
||||||
|
var hash string
|
||||||
|
if err = s.DB.QueryRowContext(ctx, `SELECT hash FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND version=?`, domain, actor, id, revision).Scan(&hash); err != nil {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
raw, err := s.readDocument(hash)
|
||||||
|
if err != nil {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
return s.saveContact(ctx, domain, actor, Contact{UUID: id, Version: version, VCard: raw}, "dav", "", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ContactAtRevision(ctx context.Context, domain, actor, id string, version int64) (Contact, error) {
|
||||||
|
if _, err := s.Contact(ctx, domain, actor, id); err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
var hash string
|
||||||
|
var deleted bool
|
||||||
|
if err := s.DB.QueryRowContext(ctx, `SELECT hash,deleted FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND version=?`, domain, actor, id, version).Scan(&hash, &deleted); err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
raw, err := s.readDocument(hash)
|
||||||
|
if err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
c, err := ParseContact(raw)
|
||||||
|
c.UUID = id
|
||||||
|
c.Version = version
|
||||||
|
c.Deleted = deleted
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// One SQLite read snapshot, bounded before headers are sent. An export must
|
||||||
|
// never look successful when contacts have been silently truncated.
|
||||||
|
func (s *Store) ExportContacts(ctx context.Context, domain, actor string) (string, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND deleted=0 ORDER BY uuid LIMIT 5001`, domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out strings.Builder
|
||||||
|
count := 0
|
||||||
|
for rows.Next() {
|
||||||
|
var raw string
|
||||||
|
var c Contact
|
||||||
|
if err = rows.Scan(&raw); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal([]byte(raw), &c); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
if count > 5000 || out.Len()+len(c.VCard) > 16<<20 {
|
||||||
|
return "", ErrTaskDAVLimit
|
||||||
|
}
|
||||||
|
out.WriteString(c.VCard)
|
||||||
|
}
|
||||||
|
return out.String(), rows.Err()
|
||||||
|
}
|
||||||
@@ -0,0 +1,497 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/mail"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
var contactMigrations = []db.SQLMigration{{Version: 1, Name: "private_address_book", Statements: []string{
|
||||||
|
`CREATE TABLE organizer_contacts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,uid TEXT NOT NULL,version INTEGER NOT NULL,name TEXT NOT NULL,search TEXT NOT NULL,data TEXT NOT NULL,hash TEXT NOT NULL,deleted INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(domain_uuid,owner_uuid,uuid),UNIQUE(domain_uuid,owner_uuid,uid))`,
|
||||||
|
`CREATE INDEX organizer_contacts_owner ON organizer_contacts(domain_uuid,owner_uuid,deleted,uuid)`,
|
||||||
|
`CREATE TABLE organizer_contact_revisions(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,version INTEGER NOT NULL,hash TEXT NOT NULL,deleted INTEGER NOT NULL,created_ms INTEGER NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,uuid,version))`,
|
||||||
|
}, Assertions: []string{schemaColumns("organizer_contacts", "domain_uuid,owner_uuid,uuid,uid,version,name,search,data,hash,deleted"), schemaUnique("organizer_contacts", "domain_uuid,owner_uuid,uid")}}, {Version: 2, Name: "contact_dav_sync", Statements: []string{
|
||||||
|
`CREATE TABLE organizer_contact_credentials(credential_id TEXT PRIMARY KEY)`,
|
||||||
|
`CREATE TRIGGER organizer_contact_credential_delete AFTER DELETE ON organizer_dav_credentials BEGIN DELETE FROM organizer_contact_credentials WHERE credential_id=old.id; END`,
|
||||||
|
`CREATE TABLE organizer_contact_names(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,name TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,uuid),UNIQUE(domain_uuid,owner_uuid,name))`,
|
||||||
|
`INSERT INTO organizer_contact_names SELECT domain_uuid,owner_uuid,uuid,uuid||'.vcf' FROM organizer_contacts`,
|
||||||
|
`CREATE TABLE organizer_contact_epoch(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL)`,
|
||||||
|
`INSERT INTO organizer_contact_epoch VALUES(1,lower(hex(randomblob(32))))`,
|
||||||
|
`CREATE TABLE organizer_contact_changes(sequence INTEGER PRIMARY KEY AUTOINCREMENT,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,UNIQUE(domain_uuid,owner_uuid,uuid))`,
|
||||||
|
`CREATE INDEX organizer_contact_changes_owner ON organizer_contact_changes(domain_uuid,owner_uuid,sequence,uuid)`,
|
||||||
|
`INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) SELECT domain_uuid,owner_uuid,uuid FROM organizer_contacts ORDER BY domain_uuid,owner_uuid,uuid`,
|
||||||
|
`CREATE TRIGGER organizer_contact_insert AFTER INSERT ON organizer_contacts BEGIN INSERT INTO organizer_contact_names SELECT new.domain_uuid,new.owner_uuid,new.uuid,new.uuid||'.vcf' WHERE NOT EXISTS(SELECT 1 FROM organizer_contact_names WHERE domain_uuid=new.domain_uuid AND owner_uuid=new.owner_uuid AND uuid=new.uuid); INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) VALUES(new.domain_uuid,new.owner_uuid,new.uuid); END`,
|
||||||
|
`CREATE TRIGGER organizer_contact_update AFTER UPDATE ON organizer_contacts BEGIN DELETE FROM organizer_contact_changes WHERE domain_uuid=new.domain_uuid AND owner_uuid=new.owner_uuid AND uuid=new.uuid; INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) VALUES(new.domain_uuid,new.owner_uuid,new.uuid); END`,
|
||||||
|
}, Assertions: []string{
|
||||||
|
schemaColumns("organizer_contact_changes", "sequence,domain_uuid,owner_uuid,uuid"),
|
||||||
|
schemaColumns("organizer_contact_credentials", "credential_id"),
|
||||||
|
schemaColumns("organizer_contact_epoch", "id,value"),
|
||||||
|
schemaColumns("organizer_contact_names", "domain_uuid,owner_uuid,uuid,name"),
|
||||||
|
schemaUnique("organizer_contact_names", "domain_uuid,owner_uuid,name"),
|
||||||
|
schemaUnique("organizer_contact_changes", "domain_uuid,owner_uuid,uuid"),
|
||||||
|
schemaIndex("organizer_contact_changes", "organizer_contact_changes_owner", "domain_uuid,owner_uuid,sequence,uuid"),
|
||||||
|
`SELECT 1 WHERE (SELECT count(*) FROM organizer_contact_epoch WHERE id=1 AND length(value)=64)<>1`,
|
||||||
|
`SELECT 1 WHERE (SELECT count(*) FROM sqlite_master WHERE type='trigger' AND name IN ('organizer_contact_insert','organizer_contact_update','organizer_contact_credential_delete'))<>3`,
|
||||||
|
}}}
|
||||||
|
|
||||||
|
type Contact struct {
|
||||||
|
UUID string `json:"uuid"`
|
||||||
|
UID string `json:"uid"`
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Emails []string `json:"emails"`
|
||||||
|
Phones []string `json:"phones"`
|
||||||
|
Organization string `json:"organization"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
VCard string `json:"vcard,omitempty"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preserve every unfolded property, including unsupported fields/parameters.
|
||||||
|
// Encoded legacy v2.1/QP and malformed data are rejected, never silently lost.
|
||||||
|
func cardLines(raw string) ([]string, error) {
|
||||||
|
if len(raw) > 65536 || !utf8.ValidString(raw) || strings.ContainsRune(raw, 0) {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
for _, c := range raw {
|
||||||
|
if c < 32 && c != '\r' && c != '\n' && c != '\t' || c == 127 {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw = strings.ReplaceAll(raw, "\r\n", "\n")
|
||||||
|
if strings.ContainsRune(raw, '\r') {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
var lines []string
|
||||||
|
for _, line := range strings.Split(strings.TrimSuffix(raw, "\n"), "\n") {
|
||||||
|
if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
|
||||||
|
if len(lines) == 0 {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
lines[len(lines)-1] += line[1:]
|
||||||
|
} else {
|
||||||
|
lines = append(lines, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(lines) < 4 || lines[0] != "BEGIN:VCARD" || lines[len(lines)-1] != "END:VCARD" {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return lines, nil
|
||||||
|
}
|
||||||
|
func cardKey(line string) (string, string, error) {
|
||||||
|
quoted := false
|
||||||
|
colon := -1
|
||||||
|
for i, c := range line {
|
||||||
|
if c == '"' {
|
||||||
|
quoted = !quoted
|
||||||
|
}
|
||||||
|
if c == ':' && !quoted {
|
||||||
|
colon = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if colon < 1 {
|
||||||
|
return "", "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
head := line[:colon]
|
||||||
|
key := strings.SplitN(head, ";", 2)[0]
|
||||||
|
if i := strings.LastIndex(key, "."); i >= 0 {
|
||||||
|
key = key[i+1:]
|
||||||
|
}
|
||||||
|
for _, c := range key {
|
||||||
|
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
|
||||||
|
return "", "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
upper := strings.ToUpper(head)
|
||||||
|
if strings.Contains(upper, "ENCODING=") || strings.Contains(upper, "CHARSET=") {
|
||||||
|
return "", "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return strings.ToUpper(key), line[colon+1:], nil
|
||||||
|
}
|
||||||
|
func cardText(s string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if s[i] == '\\' && i+1 < len(s) {
|
||||||
|
i++
|
||||||
|
if s[i] == 'n' || s[i] == 'N' {
|
||||||
|
b.WriteByte('\n')
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteByte(s[i])
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
func escapeCard(s string) string {
|
||||||
|
return strings.NewReplacer("\\", "\\\\", "\r\n", "\\n", "\n", "\\n", ";", "\\;", ",", "\\,").Replace(s)
|
||||||
|
}
|
||||||
|
func foldCard(lines []string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, line := range lines {
|
||||||
|
first := true
|
||||||
|
for len(line) > 0 {
|
||||||
|
n := 75
|
||||||
|
if !first {
|
||||||
|
b.WriteByte(' ')
|
||||||
|
n = 74
|
||||||
|
}
|
||||||
|
if len(line) < n {
|
||||||
|
n = len(line)
|
||||||
|
}
|
||||||
|
for n > 0 && n < len(line) && !utf8.RuneStart(line[n]) {
|
||||||
|
n--
|
||||||
|
}
|
||||||
|
b.WriteString(line[:n])
|
||||||
|
b.WriteString("\r\n")
|
||||||
|
line = line[n:]
|
||||||
|
first = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
func ParseContact(raw string) (Contact, error) {
|
||||||
|
c := Contact{Emails: []string{}, Phones: []string{}}
|
||||||
|
lines, err := cardLines(raw)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
versions, names, uids := 0, 0, 0
|
||||||
|
for _, line := range lines[1 : len(lines)-1] {
|
||||||
|
key, value, e := cardKey(line)
|
||||||
|
if e != nil {
|
||||||
|
return c, e
|
||||||
|
}
|
||||||
|
value = cardText(value)
|
||||||
|
switch key {
|
||||||
|
case "VERSION":
|
||||||
|
versions++
|
||||||
|
if value != "4.0" && value != "3.0" {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
case "BEGIN", "END":
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
case "UID":
|
||||||
|
uids++
|
||||||
|
c.UID = value
|
||||||
|
case "FN":
|
||||||
|
names++
|
||||||
|
if c.Name == "" {
|
||||||
|
c.Name = value
|
||||||
|
}
|
||||||
|
case "EMAIL":
|
||||||
|
c.Emails = append(c.Emails, value)
|
||||||
|
case "TEL":
|
||||||
|
c.Phones = append(c.Phones, strings.TrimPrefix(value, "tel:"))
|
||||||
|
case "ORG":
|
||||||
|
if c.Organization == "" {
|
||||||
|
c.Organization = value
|
||||||
|
}
|
||||||
|
case "NOTE":
|
||||||
|
if c.Notes == "" {
|
||||||
|
c.Notes = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if versions != 1 || names < 1 || uids > 1 || len(c.Name) > 300 || len(c.UID) > 1024 || strings.TrimSpace(c.Name) == "" || len(c.Emails) > 30 || len(c.Phones) > 30 {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if lines[1] != "VERSION:4.0" && lines[1] != "VERSION:3.0" {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
for _, value := range append([]string{c.Name, c.UID}, c.Emails...) {
|
||||||
|
if strings.ContainsAny(value, "\r\n\x00") {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range c.Emails {
|
||||||
|
a, e := mail.ParseAddress(value)
|
||||||
|
if e != nil || a.Address != value {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.UID == "" {
|
||||||
|
sum := sha256.Sum256([]byte(raw))
|
||||||
|
c.UID = "urn:pageswiki:import:" + hex.EncodeToString(sum[:])
|
||||||
|
lines = append(lines[:len(lines)-1], "UID:"+c.UID, "END:VCARD")
|
||||||
|
}
|
||||||
|
c.VCard = foldCard(lines)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Editing the visible fields retains other fields verbatim. Even repeated FN,
|
||||||
|
// ORG/NOTE and typed email/phone fields survive when that field is unchanged.
|
||||||
|
func buildContact(old Contact, c Contact) (Contact, error) {
|
||||||
|
if len(c.Name) > 300 || strings.TrimSpace(c.Name) == "" || len(c.Notes) > 16384 || len(c.Organization) > 1000 || len(c.Emails) > 30 || len(c.Phones) > 30 {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
for _, value := range append(append([]string{c.Name, c.Organization}, c.Emails...), c.Phones...) {
|
||||||
|
if strings.ContainsAny(value, "\r\n\x00") {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range c.Emails {
|
||||||
|
a, e := mail.ParseAddress(value)
|
||||||
|
if e != nil || a.Address != value {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines := []string{"BEGIN:VCARD", "VERSION:4.0", "UID:urn:uuid:" + c.UUID, "END:VCARD"}
|
||||||
|
if old.VCard != "" {
|
||||||
|
var e error
|
||||||
|
lines, e = cardLines(old.VCard)
|
||||||
|
if e != nil {
|
||||||
|
return c, e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
changes := map[string][]string{}
|
||||||
|
if old.VCard == "" || c.Name != old.Name {
|
||||||
|
changes["FN"] = []string{c.Name}
|
||||||
|
}
|
||||||
|
if c.Organization != old.Organization {
|
||||||
|
changes["ORG"] = []string{c.Organization}
|
||||||
|
}
|
||||||
|
if c.Notes != old.Notes {
|
||||||
|
changes["NOTE"] = []string{c.Notes}
|
||||||
|
}
|
||||||
|
if strings.Join(c.Emails, "\x00") != strings.Join(old.Emails, "\x00") {
|
||||||
|
changes["EMAIL"] = c.Emails
|
||||||
|
}
|
||||||
|
if strings.Join(c.Phones, "\x00") != strings.Join(old.Phones, "\x00") {
|
||||||
|
changes["TEL"] = c.Phones
|
||||||
|
}
|
||||||
|
out := []string{}
|
||||||
|
for _, line := range lines[:len(lines)-1] {
|
||||||
|
k, _, _ := cardKey(line)
|
||||||
|
if _, replace := changes[k]; !replace {
|
||||||
|
out = append(out, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, key := range []string{"FN", "ORG", "NOTE", "EMAIL", "TEL"} {
|
||||||
|
for _, value := range changes[key] {
|
||||||
|
if value != "" {
|
||||||
|
out = append(out, key+":"+escapeCard(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, "END:VCARD")
|
||||||
|
parsed, e := ParseContact(foldCard(out))
|
||||||
|
parsed.UUID = c.UUID
|
||||||
|
parsed.Version = c.Version
|
||||||
|
parsed.Deleted = c.Deleted
|
||||||
|
return parsed, e
|
||||||
|
}
|
||||||
|
func contactEnabled(ctx context.Context, q interface {
|
||||||
|
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||||
|
}, domain string) error {
|
||||||
|
var raw string
|
||||||
|
err := q.QueryRowContext(ctx, `SELECT value FROM config WHERE domain_uuid=? AND key='system_extension_states'`, domain).Scan(&raw)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) || err == nil && raw == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
states := map[string]bool{}
|
||||||
|
if json.Unmarshal([]byte(raw), &states) != nil {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
if on, ok := states["organizer.contacts"]; ok && !on {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (s *Store) Contacts(ctx context.Context, domain, actor, query, after string) ([]Contact, string, error) {
|
||||||
|
return s.ListContacts(ctx, domain, actor, query, after, false)
|
||||||
|
}
|
||||||
|
func (s *Store) ListContacts(ctx context.Context, domain, actor, query, after string, deleted bool) ([]Contact, string, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
if len(query) > 200 {
|
||||||
|
return nil, "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND deleted=? AND uuid>? AND instr(search,?)>0 ORDER BY uuid LIMIT 101`, domain, actor, deleted, after, strings.ToLower(query))
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []Contact{}
|
||||||
|
next := ""
|
||||||
|
for rows.Next() {
|
||||||
|
var raw string
|
||||||
|
if err = rows.Scan(&raw); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
var c Contact
|
||||||
|
if err = json.Unmarshal([]byte(raw), &c); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
if len(out) == 100 {
|
||||||
|
next = out[99].UUID
|
||||||
|
break
|
||||||
|
}
|
||||||
|
c.VCard = ""
|
||||||
|
out = append(out, c)
|
||||||
|
}
|
||||||
|
return out, next, rows.Err()
|
||||||
|
}
|
||||||
|
func (s *Store) Contact(ctx context.Context, domain, actor, id string) (Contact, error) {
|
||||||
|
var c Contact
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, id).Scan(&raw)
|
||||||
|
if err == nil {
|
||||||
|
err = json.Unmarshal([]byte(raw), &c)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact, rawImport bool) (Contact, error) {
|
||||||
|
mode := "fields"
|
||||||
|
if rawImport {
|
||||||
|
mode = "import"
|
||||||
|
}
|
||||||
|
return s.saveContact(ctx, domain, actor, c, mode, "", "")
|
||||||
|
}
|
||||||
|
func (s *Store) saveContact(ctx context.Context, domain, actor string, c Contact, mode, credential, name string) (Contact, error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return c, ErrReadOnly
|
||||||
|
}
|
||||||
|
if id, e := uuid.Parse(c.UUID); e != nil || id.String() != c.UUID || c.Version < 0 {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, err = tx.ExecContext(ctx, `UPDATE domain_memberships SET state=state WHERE domain_uuid=? AND principal_uuid=?`, domain, actor); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if err = taskActor(ctx, tx, domain, actor, true); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if err = contactEnabled(ctx, tx, domain); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if credential != "" {
|
||||||
|
if err = davCredentialAllowed(ctx, tx, domain, actor, credential, true, "contacts"); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var old Contact
|
||||||
|
var data string
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, c.UUID).Scan(&data)
|
||||||
|
if err == nil {
|
||||||
|
if err = json.Unmarshal([]byte(data), &old); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
} else if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if c.Version != old.Version {
|
||||||
|
return c, ErrTaskConflict
|
||||||
|
}
|
||||||
|
if mode == "import" || mode == "dav" {
|
||||||
|
if mode == "import" && c.Version != 0 {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
parsed, e := ParseContact(c.VCard)
|
||||||
|
if e != nil {
|
||||||
|
return c, e
|
||||||
|
}
|
||||||
|
parsed.UUID = c.UUID
|
||||||
|
parsed.Version = c.Version
|
||||||
|
c = parsed
|
||||||
|
if old.Version != 0 && old.UID != c.UID {
|
||||||
|
return c, ErrContactUIDConflict
|
||||||
|
}
|
||||||
|
var existing string
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uid=?`, domain, actor, c.UID).Scan(&existing)
|
||||||
|
if err == nil {
|
||||||
|
var previous Contact
|
||||||
|
if json.Unmarshal([]byte(existing), &previous) != nil {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if mode == "import" {
|
||||||
|
if previous.VCard != c.VCard || previous.Deleted {
|
||||||
|
return c, ErrTaskConflict
|
||||||
|
}
|
||||||
|
return previous, nil
|
||||||
|
}
|
||||||
|
if previous.UUID != c.UUID {
|
||||||
|
return c, ErrContactUIDConflict
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
c, err = buildContact(old, c)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
if !ValidContactDAVName(name) {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
var existing string
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT name FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, c.UUID).Scan(&existing)
|
||||||
|
if err == nil && existing != name {
|
||||||
|
return c, ErrTaskConflict
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_contact_names VALUES(?,?,?,?)`, domain, actor, c.UUID, name); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
var mapped string
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT uuid FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND name=?`, domain, actor, name).Scan(&mapped); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if mapped != c.UUID {
|
||||||
|
return c, ErrTaskConflict
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.Version++
|
||||||
|
b, err := json.Marshal(c)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
hash := sha256.Sum256([]byte(c.VCard))
|
||||||
|
digest := hex.EncodeToString(hash[:])
|
||||||
|
if err = s.persistDocument(digest, c.VCard); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
search := strings.ToLower(c.Name + "\n" + c.Organization + "\n" + strings.Join(c.Emails, "\n") + "\n" + strings.Join(c.Phones, "\n"))
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contacts(domain_uuid,owner_uuid,uuid,uid,version,name,search,data,hash,deleted) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(domain_uuid,owner_uuid,uuid) DO UPDATE SET version=excluded.version,name=excluded.name,search=excluded.search,data=excluded.data,hash=excluded.hash,deleted=excluded.deleted`, domain, actor, c.UUID, c.UID, c.Version, c.Name, search, string(b), digest, c.Deleted)
|
||||||
|
if err != nil {
|
||||||
|
return c, fmt.Errorf("save contact: %w", err)
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contact_revisions VALUES(?,?,?,?,?,?,?)`, domain, actor, c.UUID, c.Version, digest, c.Deleted, time.Now().UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
return c, tx.Commit()
|
||||||
|
}
|
||||||
@@ -12,6 +12,8 @@ import (
|
|||||||
// Once released, add a new version; never edit an applied definition.
|
// Once released, add a new version; never edit an applied definition.
|
||||||
// Auth, City, tasks and calendars remain in their existing migration paths.
|
// Auth, City, tasks and calendars remain in their existing migration paths.
|
||||||
var managedStoreSchemas = map[string][]db.SQLMigration{
|
var managedStoreSchemas = map[string][]db.SQLMigration{
|
||||||
|
"contacts": contactMigrations,
|
||||||
|
"task-productivity": taskProductivityMigrations,
|
||||||
"cli-auth": cliAuthMigrations,
|
"cli-auth": cliAuthMigrations,
|
||||||
"profile-contacts": profileContactMigrations,
|
"profile-contacts": profileContactMigrations,
|
||||||
"event-jobs": eventJobMigrations,
|
"event-jobs": eventJobMigrations,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -8,6 +9,48 @@ import (
|
|||||||
"pageswiki/internal/db"
|
"pageswiki/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestContactDAVUpgradePreservesRowsAndTracksChanges(t *testing.T) {
|
||||||
|
st := newSchemaTestStore(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
if e := db.ApplySQLiteMigrations(ctx, st.DB, "contacts", contactMigrations[:1]); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := st.DB.Exec(`INSERT INTO organizer_contacts VALUES('d','u','c','uid',1,'Name','name','{"name":"Name"}','hash',0)`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if e := st.ensureSchemaComponent("contacts"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var name, data string
|
||||||
|
var before, after int64
|
||||||
|
var count int
|
||||||
|
if e := st.DB.QueryRow(`SELECT name FROM organizer_contact_names WHERE uuid='c'`).Scan(&name); e != nil || name != "c.vcf" {
|
||||||
|
t.Fatal(name, e)
|
||||||
|
}
|
||||||
|
if e := st.DB.QueryRow(`SELECT data FROM organizer_contacts WHERE uuid='c'`).Scan(&data); e != nil || data != `{"name":"Name"}` {
|
||||||
|
t.Fatal(data, e)
|
||||||
|
}
|
||||||
|
if e := st.DB.QueryRow(`SELECT sequence FROM organizer_contact_changes WHERE uuid='c'`).Scan(&before); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for range 3 {
|
||||||
|
if _, e := st.DB.Exec(`UPDATE organizer_contacts SET deleted=1 WHERE uuid='c'`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e := st.DB.QueryRow(`SELECT count(*),max(sequence) FROM organizer_contact_changes WHERE uuid='c'`).Scan(&count, &after); e != nil || count != 1 || after <= before {
|
||||||
|
t.Fatal(count, before, after, e)
|
||||||
|
}
|
||||||
|
if _, e := st.DB.Exec(`INSERT INTO organizer_dav_credentials VALUES('credential'); INSERT INTO organizer_contact_credentials VALUES('credential'); DELETE FROM organizer_dav_credentials WHERE id='credential'`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := st.DB.QueryRow(`SELECT count(*) FROM organizer_contact_credentials`).Scan(&count); e != nil || count != 0 {
|
||||||
|
t.Fatal(count, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func newSchemaTestStore(t *testing.T) *Store {
|
func newSchemaTestStore(t *testing.T) *Store {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
database, err := db.Open(filepath.Join(t.TempDir(), "schema.db"))
|
database, err := db.Open(filepath.Join(t.TempDir(), "schema.db"))
|
||||||
@@ -15,9 +58,34 @@ func newSchemaTestStore(t *testing.T) *Store {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
t.Cleanup(func() { database.Close() })
|
t.Cleanup(func() { database.Close() })
|
||||||
|
// task-productivity follows the legacy task schema at application startup.
|
||||||
|
// Provide its source projection, not the component under test itself.
|
||||||
|
if _, err = database.Exec(`CREATE TABLE organizer_items(domain_uuid TEXT,owner_uuid TEXT,uuid TEXT,kind TEXT,data TEXT)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = database.Exec(`CREATE TABLE organizer_dav_credentials(id TEXT PRIMARY KEY)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
return &Store{DB: database}
|
return &Store{DB: database}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTaskProductivityMigrationBackfillsOnce(t *testing.T) {
|
||||||
|
st := newSchemaTestStore(t)
|
||||||
|
if _, e := st.DB.Exec(`INSERT INTO organizer_items VALUES('d','u','t','task','{"completed_at_ms":123,"estimate_minutes":60}')`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if e := st.ensureSchemaComponent("task-productivity"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var count, complexity int
|
||||||
|
var completed int64
|
||||||
|
if e := st.DB.QueryRow(`SELECT count(*),completed_ms,complexity FROM organizer_task_metrics`).Scan(&count, &completed, &complexity); e != nil || count != 1 || completed != 123 || complexity != 1 {
|
||||||
|
t.Fatal(count, completed, complexity, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestManagedSchemasFreshRepeatAndReadOnly(t *testing.T) {
|
func TestManagedSchemasFreshRepeatAndReadOnly(t *testing.T) {
|
||||||
for component := range managedStoreSchemas {
|
for component := range managedStoreSchemas {
|
||||||
t.Run(component, func(t *testing.T) {
|
t.Run(component, func(t *testing.T) {
|
||||||
|
|||||||
@@ -108,6 +108,9 @@ func NewWithDocumentRoot(
|
|||||||
if err := st.EnsureTasksSchema(); err != nil {
|
if err := st.EnsureTasksSchema(); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
if err := st.ensureSchemaComponent("contacts"); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
if err := st.EnsureBrowserNavigationSchema(); err != nil {
|
if err := st.EnsureBrowserNavigationSchema(); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,10 @@ func (s *Store) CreateTaskDAVCredential(ctx context.Context, domain, actor, labe
|
|||||||
|
|
||||||
func (s *Store) CreateDAVCredential(ctx context.Context, domain, actor, label string, write bool, days int, scope string, compatibility ...bool) (TaskDAVCredential, string, error) {
|
func (s *Store) CreateDAVCredential(ctx context.Context, domain, actor, label string, write bool, days int, scope string, compatibility ...bool) (TaskDAVCredential, string, error) {
|
||||||
compat := len(compatibility) == 1 && compatibility[0]
|
compat := len(compatibility) == 1 && compatibility[0]
|
||||||
if scope != "tasks" && scope != "calendar" && scope != "all" {
|
if scope == "contacts" && compat {
|
||||||
|
return TaskDAVCredential{}, "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if scope != "tasks" && scope != "calendar" && scope != "all" && scope != "contacts" {
|
||||||
return TaskDAVCredential{}, "", ErrTaskInvalid
|
return TaskDAVCredential{}, "", ErrTaskInvalid
|
||||||
}
|
}
|
||||||
label = strings.TrimSpace(label)
|
label = strings.TrimSpace(label)
|
||||||
@@ -71,13 +74,20 @@ func (s *Store) CreateDAVCredential(ctx context.Context, domain, actor, label st
|
|||||||
// of accidentally interpreting them as task-only authority.
|
// of accidentally interpreting them as task-only authority.
|
||||||
secret = "pw_dav_" + base64.RawURLEncoding.EncodeToString(raw)
|
secret = "pw_dav_" + base64.RawURLEncoding.EncodeToString(raw)
|
||||||
}
|
}
|
||||||
|
if scope == "contacts" {
|
||||||
|
secret = "pw_contactdav_" + base64.RawURLEncoding.EncodeToString(raw)
|
||||||
|
}
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
c := TaskDAVCredential{ID: uuid.NewString(), Label: label, Write: write, CreatedMS: now.UnixMilli(), ExpiresMS: now.Add(time.Duration(days) * 24 * time.Hour).UnixMilli(), Scope: scope}
|
c := TaskDAVCredential{ID: uuid.NewString(), Label: label, Write: write, CreatedMS: now.UnixMilli(), ExpiresMS: now.Add(time.Duration(days) * 24 * time.Hour).UnixMilli(), Scope: scope}
|
||||||
c.CalendarAccessCompat = compat
|
c.CalendarAccessCompat = compat
|
||||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_credentials(id,domain_uuid,owner_uuid,label,secret_hash,write_access,created_ms,expires_ms) VALUES(?,?,?,?,?,?,?,?)`, c.ID, domain, actor, c.Label, taskDAVSecretHash(secret), write, c.CreatedMS, c.ExpiresMS)
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_credentials(id,domain_uuid,owner_uuid,label,secret_hash,write_access,created_ms,expires_ms) VALUES(?,?,?,?,?,?,?,?)`, c.ID, domain, actor, c.Label, taskDAVSecretHash(secret), write, c.CreatedMS, c.ExpiresMS)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
if scope == "contacts" {
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contact_credentials VALUES(?)`, c.ID)
|
||||||
|
} else {
|
||||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_scopes(credential_id,scope) VALUES(?,?)`, c.ID, scope)
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_scopes(credential_id,scope) VALUES(?,?)`, c.ID, scope)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if err == nil && compat {
|
if err == nil && compat {
|
||||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_compat(credential_id) VALUES(?)`, c.ID)
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_compat(credential_id) VALUES(?)`, c.ID)
|
||||||
}
|
}
|
||||||
@@ -90,7 +100,7 @@ func (s *Store) ListTaskDAVCredentials(ctx context.Context, domain, actor string
|
|||||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
rows, err := s.DB.QueryContext(ctx, `SELECT id,label,write_access,created_ms,expires_ms,COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks'),EXISTS(SELECT 1 FROM organizer_dav_compat WHERE credential_id=id) FROM organizer_dav_credentials WHERE domain_uuid=? AND owner_uuid=? ORDER BY created_ms DESC LIMIT 100`, domain, actor)
|
rows, err := s.DB.QueryContext(ctx, `SELECT id,label,write_access,created_ms,expires_ms,CASE WHEN EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id) THEN 'contacts' ELSE COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') END,EXISTS(SELECT 1 FROM organizer_dav_compat WHERE credential_id=id) FROM organizer_dav_credentials WHERE domain_uuid=? AND owner_uuid=? ORDER BY created_ms DESC LIMIT 100`, domain, actor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -130,7 +140,7 @@ func davCredentialAllowed(ctx context.Context, q interface {
|
|||||||
QueryRowContext(context.Context, string, ...any) *sql.Row
|
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||||
}, domain, actor, id string, write bool, scope string) error {
|
}, domain, actor, id string, write bool, scope string) error {
|
||||||
var yes bool
|
var yes bool
|
||||||
if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_dav_credentials WHERE id=? AND domain_uuid=? AND owner_uuid=? AND expires_ms>? AND (?=0 OR write_access=1) AND COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') IN (?, 'all'))`, id, domain, actor, time.Now().UnixMilli(), write, scope).Scan(&yes); err != nil {
|
if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_dav_credentials WHERE id=? AND domain_uuid=? AND owner_uuid=? AND expires_ms>? AND (?=0 OR write_access=1) AND ((?='contacts' AND EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id)) OR (? IN ('tasks','calendar') AND NOT EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id) AND COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') IN (?, 'all'))))`, id, domain, actor, time.Now().UnixMilli(), write, scope, scope, scope).Scan(&yes); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !yes {
|
if !yes {
|
||||||
@@ -151,16 +161,19 @@ func (s *Store) CheckDAVCredential(ctx context.Context, domain, actor, id string
|
|||||||
|
|
||||||
// An empty requested scope is discovery only; callers must filter collections.
|
// An empty requested scope is discovery only; callers must filter collections.
|
||||||
func (s *Store) AuthenticateDAV(ctx context.Context, domain, id, secret, requested string) (string, bool, string, error) {
|
func (s *Store) AuthenticateDAV(ctx context.Context, domain, id, secret, requested string) (string, bool, string, error) {
|
||||||
if len(secret) > 128 || !(strings.HasPrefix(secret, "pw_taskdav_") || strings.HasPrefix(secret, "pw_dav_")) {
|
if len(secret) > 128 || !(strings.HasPrefix(secret, "pw_taskdav_") || strings.HasPrefix(secret, "pw_dav_") || strings.HasPrefix(secret, "pw_contactdav_")) {
|
||||||
return "", false, "", ErrAccessDenied
|
return "", false, "", ErrAccessDenied
|
||||||
}
|
}
|
||||||
var actor, hash, state, scope string
|
var actor, hash, state, scope string
|
||||||
var write bool
|
var write bool
|
||||||
err := s.DB.QueryRowContext(ctx, `SELECT c.owner_uuid,c.secret_hash,c.write_access,p.state,COALESCE(s.scope,'tasks') FROM organizer_dav_credentials c JOIN principals p ON p.uuid=c.owner_uuid LEFT JOIN organizer_dav_scopes s ON s.credential_id=c.id WHERE c.id=? AND c.domain_uuid=? AND c.expires_ms>?`, id, domain, time.Now().UnixMilli()).Scan(&actor, &hash, &write, &state, &scope)
|
err := s.DB.QueryRowContext(ctx, `SELECT c.owner_uuid,c.secret_hash,c.write_access,p.state,CASE WHEN EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=c.id) THEN 'contacts' ELSE COALESCE(s.scope,'tasks') END FROM organizer_dav_credentials c JOIN principals p ON p.uuid=c.owner_uuid LEFT JOIN organizer_dav_scopes s ON s.credential_id=c.id WHERE c.id=? AND c.domain_uuid=? AND c.expires_ms>?`, id, domain, time.Now().UnixMilli()).Scan(&actor, &hash, &write, &state, &scope)
|
||||||
if err != nil || subtle.ConstantTimeCompare([]byte(hash), []byte(taskDAVSecretHash(secret))) != 1 {
|
if err != nil || subtle.ConstantTimeCompare([]byte(hash), []byte(taskDAVSecretHash(secret))) != 1 {
|
||||||
return "", false, "", ErrAccessDenied
|
return "", false, "", ErrAccessDenied
|
||||||
}
|
}
|
||||||
if requested != "" && scope != "all" && scope != requested {
|
if strings.HasPrefix(secret, "pw_contactdav_") && scope != "contacts" {
|
||||||
|
return "", false, "", ErrAccessDenied
|
||||||
|
}
|
||||||
|
if requested != "" && scope != requested && !(scope == "all" && (requested == "tasks" || requested == "calendar")) {
|
||||||
return "", false, "", ErrAccessDenied
|
return "", false, "", ErrAccessDenied
|
||||||
}
|
}
|
||||||
if err = taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
if err = taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const TaskDigestEventType = "task.digest.deliver"
|
||||||
|
|
||||||
|
type TaskDigestDue struct {
|
||||||
|
Domain string
|
||||||
|
Owner string
|
||||||
|
}
|
||||||
|
type TaskDigestClaim struct {
|
||||||
|
TaskDigestDue
|
||||||
|
Day string
|
||||||
|
Version int64
|
||||||
|
Timezone string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) EnsureTaskDigestEvent() error {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
_, err := s.DB.Exec(`INSERT OR IGNORE INTO event_definitions(uuid,name,event_type,event_key,payload,schedule_kind,interval_seconds,next_run_at_ms,enabled,priority,max_attempts,created_at_ms,updated_at_ms) VALUES('builtin.task.digest','Daily task email',?,'local','{}','interval',60,?,1,-2,1,?,?)`, TaskDigestEventType, now, now, now)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) DueTaskDigests(ctx context.Context, now time.Time) ([]TaskDigestDue, error) {
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT domain_uuid,owner_uuid FROM organizer_task_preferences WHERE next_digest_ms>0 AND next_digest_ms<=? ORDER BY next_digest_ms,domain_uuid,owner_uuid LIMIT 20`, now.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []TaskDigestDue{}
|
||||||
|
for rows.Next() {
|
||||||
|
var v TaskDigestDue
|
||||||
|
if err = rows.Scan(&v.Domain, &v.Owner); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Claim before SMTP: an ambiguous delivery is never automatically sent twice.
|
||||||
|
// An interrupted claim stays visible as "sending" for operator review.
|
||||||
|
func (s *Store) ClaimTaskDigest(ctx context.Context, due TaskDigestDue, now time.Time) (TaskDigestClaim, error) {
|
||||||
|
out := TaskDigestClaim{TaskDigestDue: due}
|
||||||
|
if s.ReadOnly {
|
||||||
|
return out, ErrReadOnly
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
res, err := tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=next_digest_ms WHERE domain_uuid=? AND owner_uuid=? AND next_digest_ms>0 AND next_digest_ms<=?`, due.Domain, due.Owner, now.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n != 1 {
|
||||||
|
return out, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, due.Domain, due.Owner).Scan(&raw); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
var p TaskPreferences
|
||||||
|
if err = json.Unmarshal([]byte(raw), &p); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
loc, err := time.LoadLocation(p.Timezone)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Day = now.In(loc).Format("2006-01-02")
|
||||||
|
out.Timezone = p.Timezone
|
||||||
|
out.Version = p.Version
|
||||||
|
allowed := taskActor(ctx, tx, due.Domain, due.Owner, true)
|
||||||
|
on, e := taskReminderExtensionEnabled(ctx, tx, due.Domain)
|
||||||
|
if e != nil {
|
||||||
|
return out, e
|
||||||
|
}
|
||||||
|
if allowed != nil && !errors.Is(allowed, ErrAccessDenied) {
|
||||||
|
return out, allowed
|
||||||
|
}
|
||||||
|
if allowed != nil || !on || !p.DigestEnabled {
|
||||||
|
// An opted-in schedule resumes after a domain or extension is restored.
|
||||||
|
next, e := nextTaskDigest(now, p)
|
||||||
|
if e != nil {
|
||||||
|
return out, e
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=? WHERE domain_uuid=? AND owner_uuid=?`, next, due.Domain, due.Owner)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
return out, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
// Missed days are not replayed. Run once for today's due time; if the
|
||||||
|
// configured hour has not arrived, move the cursor there without sending.
|
||||||
|
clock, _ := time.Parse("15:04", p.DigestTime)
|
||||||
|
local := now.In(loc)
|
||||||
|
today := time.Date(local.Year(), local.Month(), local.Day(), clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||||
|
next, err := nextTaskDigest(now, p)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=? WHERE domain_uuid=? AND owner_uuid=?`, next, due.Domain, due.Owner)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if today.After(now) {
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
return out, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
res, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_digest_deliveries VALUES(?,?,?,'sending',?)`, due.Domain, due.Owner, out.Day, now.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n, _ = res.RowsAffected()
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
return out, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) TaskDigestRecipient(ctx context.Context, c TaskDigestClaim) (string, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, c.Domain, c.Owner, true); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var raw, email string
|
||||||
|
var version int64
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT f.data,f.version,p.email FROM organizer_task_preferences f JOIN principals p ON p.uuid=f.owner_uuid WHERE f.domain_uuid=? AND f.owner_uuid=?`, c.Domain, c.Owner).Scan(&raw, &version, &email)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var p TaskPreferences
|
||||||
|
if json.Unmarshal([]byte(raw), &p) != nil || !p.DigestEnabled || version != c.Version {
|
||||||
|
return "", ErrAccessDenied
|
||||||
|
}
|
||||||
|
return email, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) FinishTaskDigest(ctx context.Context, c TaskDigestClaim, state string) error {
|
||||||
|
if state != "sent" && state != "uncertain" && state != "cancelled" {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
_, err := s.DB.ExecContext(ctx, `UPDATE organizer_digest_deliveries SET state=?,updated_ms=? WHERE domain_uuid=? AND owner_uuid=? AND day=? AND state='sending'`, state, time.Now().UnixMilli(), c.Domain, c.Owner, c.Day)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) LastTaskDigest(ctx context.Context, domain, actor string) (map[string]any, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var day, state string
|
||||||
|
var ms int64
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT day,state,updated_ms FROM organizer_digest_deliveries WHERE domain_uuid=? AND owner_uuid=? ORDER BY day DESC LIMIT 1`, domain, actor).Scan(&day, &state, &ms)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"day": day, "state": state, "updated_at_ms": ms}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,458 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
var taskProductivityMigrations = []db.SQLMigration{{Version: 1, Name: "task_capture_work_and_reporting", Statements: []string{
|
||||||
|
`CREATE TABLE organizer_task_preferences(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,version INTEGER NOT NULL,data TEXT NOT NULL,next_digest_ms INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(domain_uuid,owner_uuid))`,
|
||||||
|
`CREATE INDEX organizer_digest_due ON organizer_task_preferences(next_digest_ms) WHERE next_digest_ms>0`,
|
||||||
|
`CREATE TABLE organizer_capture_receipts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,request_uuid TEXT NOT NULL,request_hash TEXT NOT NULL,item_uuid TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,request_uuid))`,
|
||||||
|
`CREATE TABLE organizer_work_sessions(uuid TEXT PRIMARY KEY,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,task_uuid TEXT NOT NULL,start_ms INTEGER NOT NULL,end_ms INTEGER NOT NULL DEFAULT 0,version INTEGER NOT NULL DEFAULT 1)`,
|
||||||
|
`CREATE UNIQUE INDEX organizer_work_active ON organizer_work_sessions(owner_uuid) WHERE end_ms=0`,
|
||||||
|
`CREATE INDEX organizer_work_period ON organizer_work_sessions(domain_uuid,owner_uuid,start_ms,uuid)`,
|
||||||
|
`CREATE TABLE organizer_task_metrics(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,task_uuid TEXT NOT NULL,completed_ms INTEGER NOT NULL,estimate INTEGER NOT NULL,complexity INTEGER NOT NULL,PRIMARY KEY(domain_uuid,task_uuid))`,
|
||||||
|
`CREATE INDEX organizer_task_completed ON organizer_task_metrics(domain_uuid,owner_uuid,completed_ms)`,
|
||||||
|
`INSERT INTO organizer_task_metrics SELECT domain_uuid,owner_uuid,uuid,COALESCE(json_extract(data,'$.completed_at_ms'),0),COALESCE(json_extract(data,'$.estimate_minutes'),0),max(1,COALESCE(json_extract(data,'$.complexity'),1)) FROM organizer_items WHERE kind='task'`,
|
||||||
|
`CREATE TABLE organizer_digest_deliveries(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,day TEXT NOT NULL,state TEXT NOT NULL,updated_ms INTEGER NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,day))`,
|
||||||
|
}, Assertions: []string{
|
||||||
|
schemaColumns("organizer_task_preferences", "domain_uuid,owner_uuid,version,data,next_digest_ms"),
|
||||||
|
schemaUnique("organizer_capture_receipts", "domain_uuid,owner_uuid,request_uuid"),
|
||||||
|
schemaIndex("organizer_work_sessions", "organizer_work_period", "domain_uuid,owner_uuid,start_ms,uuid"),
|
||||||
|
}}}
|
||||||
|
|
||||||
|
type TaskPreferences struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
ProjectUUID string `json:"project_uuid"`
|
||||||
|
AssigneeUUID string `json:"assignee_uuid"`
|
||||||
|
DueDays *int `json:"due_days"`
|
||||||
|
StartDays *int `json:"start_days"`
|
||||||
|
PlannedDays *int `json:"planned_days"`
|
||||||
|
ReviewDays *int `json:"review_days"`
|
||||||
|
Estimate int `json:"estimate_minutes"`
|
||||||
|
Complexity int `json:"complexity"`
|
||||||
|
DigestEnabled bool `json:"digest_enabled"`
|
||||||
|
DigestTime string `json:"digest_time"`
|
||||||
|
Timezone string `json:"timezone"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) TaskPreferences(ctx context.Context, domain, actor string) (TaskPreferences, error) {
|
||||||
|
p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, DigestTime: "09:00", Timezone: "UTC"}
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT data FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&raw)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
err = json.Unmarshal([]byte(raw), &p)
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextTaskDigest(now time.Time, p TaskPreferences) (int64, error) {
|
||||||
|
loc, err := time.LoadLocation(p.Timezone)
|
||||||
|
if err != nil {
|
||||||
|
return 0, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
clock, err := time.Parse("15:04", p.DigestTime)
|
||||||
|
if err != nil || clock.Format("15:04") != p.DigestTime {
|
||||||
|
return 0, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if !p.DigestEnabled {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
t := now.In(loc)
|
||||||
|
candidate := time.Date(t.Year(), t.Month(), t.Day(), clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||||
|
if !candidate.After(now) {
|
||||||
|
candidate = time.Date(t.Year(), t.Month(), t.Day()+1, clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||||
|
}
|
||||||
|
return candidate.UnixMilli(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) SaveTaskPreferences(ctx context.Context, domain, actor string, p TaskPreferences, now time.Time) (TaskPreferences, error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return p, ErrReadOnly
|
||||||
|
}
|
||||||
|
for _, n := range []*int{p.DueDays, p.StartDays, p.PlannedDays, p.ReviewDays} {
|
||||||
|
if n != nil && (*n < 0 || *n > 3650) {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.Estimate < 0 || p.Estimate > 10080 || p.Complexity < 1 || p.Complexity > 5 || p.Version < 0 {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
next, err := nextTaskDigest(now, p)
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err = taskProductivityWriter(ctx, tx, domain, actor); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if err = validateTaskAssignee(ctx, tx, domain, p.AssigneeUUID); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if p.ProjectUUID != "" {
|
||||||
|
var yes bool
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND kind='project' AND archived=0)`, domain, actor, p.ProjectUUID).Scan(&yes); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if !yes {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var current int64
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT version FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(¤t)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if current != p.Version {
|
||||||
|
return p, ErrTaskConflict
|
||||||
|
}
|
||||||
|
p.Version++
|
||||||
|
raw, _ := json.Marshal(p)
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_task_preferences VALUES(?,?,?,?,?) ON CONFLICT(domain_uuid,owner_uuid) DO UPDATE SET version=excluded.version,data=excluded.data,next_digest_ms=excluded.next_digest_ms`, domain, actor, p.Version, string(raw), next)
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
return p, tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func taskProductivityWriter(ctx context.Context, tx *sql.Tx, domain, actor string) error {
|
||||||
|
if _, err := tx.ExecContext(ctx, `UPDATE domain_memberships SET state=state WHERE domain_uuid=? AND principal_uuid=?`, domain, actor); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := taskActor(ctx, tx, domain, actor, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
on, err := taskReminderExtensionEnabled(ctx, tx, domain)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !on {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assignment is a private planning annotation, NOT a grant to read this task.
|
||||||
|
func validateTaskAssignee(ctx context.Context, tx *sql.Tx, domain, assignee string) error {
|
||||||
|
if assignee == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, err := uuid.Parse(assignee); err != nil {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if err := taskActor(ctx, tx, domain, assignee, false); err != nil {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CapturedTask(ctx context.Context, domain, actor, request, hash string) (TaskRecord, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return TaskRecord{}, err
|
||||||
|
}
|
||||||
|
var stored, id string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT request_hash,item_uuid FROM organizer_capture_receipts WHERE domain_uuid=? AND owner_uuid=? AND request_uuid=?`, domain, actor, request).Scan(&stored, &id)
|
||||||
|
if err != nil {
|
||||||
|
return TaskRecord{}, err
|
||||||
|
}
|
||||||
|
if stored != hash {
|
||||||
|
return TaskRecord{}, ErrTaskConflict
|
||||||
|
}
|
||||||
|
return s.GetTask(ctx, domain, actor, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CaptureTask(ctx context.Context, domain, actor, request, hash string, item TaskRecord) (TaskRecord, error) {
|
||||||
|
if _, err := uuid.Parse(request); err != nil {
|
||||||
|
return TaskRecord{}, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
old, err := s.CapturedTask(ctx, domain, actor, request, hash)
|
||||||
|
if err == nil {
|
||||||
|
return old, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
item.UUID = request
|
||||||
|
out, err := s.saveTask(ctx, domain, actor, item, 0, func(tx *sql.Tx, _ *TaskRecord, _ TaskRecord) error {
|
||||||
|
_, e := tx.ExecContext(ctx, `INSERT INTO organizer_capture_receipts VALUES(?,?,?,?,?)`, domain, actor, request, hash, item.UUID)
|
||||||
|
return e
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if old, e := s.CapturedTask(ctx, domain, actor, request, hash); e == nil {
|
||||||
|
return old, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskWork struct {
|
||||||
|
UUID string `json:"uuid"`
|
||||||
|
TaskUUID string `json:"task_uuid"`
|
||||||
|
StartMS int64 `json:"start_ms"`
|
||||||
|
EndMS int64 `json:"end_ms"`
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanTaskWork(row interface{ Scan(...any) error }) (TaskWork, error) {
|
||||||
|
var v TaskWork
|
||||||
|
err := row.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version)
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const taskWorkColumns = `uuid,task_uuid,start_ms,end_ms,version`
|
||||||
|
|
||||||
|
func (s *Store) ActiveTaskWork(ctx context.Context, domain, actor string) (*TaskWork, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
v, err := scanTaskWork(s.DB.QueryRowContext(ctx, `SELECT `+taskWorkColumns+` FROM organizer_work_sessions WHERE domain_uuid=? AND owner_uuid=? AND end_ms=0`, domain, actor))
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return &v, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string, v TaskWork, now time.Time) (TaskWork, error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return v, ErrReadOnly
|
||||||
|
}
|
||||||
|
if _, err := uuid.Parse(v.UUID); err != nil {
|
||||||
|
return v, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err = taskProductivityWriter(ctx, tx, domain, actor); err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
old, err := scanTaskWork(tx.QueryRowContext(ctx, `SELECT `+taskWorkColumns+` FROM organizer_work_sessions WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, v.UUID, domain, actor))
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
switch action {
|
||||||
|
case "start":
|
||||||
|
if v.Version != 0 {
|
||||||
|
return v, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
if old.TaskUUID != v.TaskUUID {
|
||||||
|
return v, ErrTaskConflict
|
||||||
|
}
|
||||||
|
return old, tx.Commit()
|
||||||
|
}
|
||||||
|
var yes bool
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND kind='task' AND archived=0 AND status NOT IN ('done','cancelled'))`, domain, actor, v.TaskUUID).Scan(&yes); err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
if !yes {
|
||||||
|
return v, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
v.StartMS = now.UnixMilli()
|
||||||
|
v.EndMS = 0
|
||||||
|
v.Version = 1
|
||||||
|
res, e := tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_work_sessions(uuid,domain_uuid,owner_uuid,task_uuid,start_ms) VALUES(?,?,?,?,?)`, v.UUID, domain, actor, v.TaskUUID, v.StartMS)
|
||||||
|
if e != nil {
|
||||||
|
return v, e
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n != 1 {
|
||||||
|
return v, ErrTaskConflict
|
||||||
|
}
|
||||||
|
case "stop":
|
||||||
|
if err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
if old.EndMS > 0 {
|
||||||
|
if v.Version == old.Version || v.Version == old.Version-1 {
|
||||||
|
return old, tx.Commit()
|
||||||
|
}
|
||||||
|
return v, ErrTaskConflict
|
||||||
|
}
|
||||||
|
if old.Version != v.Version {
|
||||||
|
return v, ErrTaskConflict
|
||||||
|
}
|
||||||
|
v = old
|
||||||
|
v.EndMS = max(v.StartMS, now.UnixMilli())
|
||||||
|
v.Version++
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE organizer_work_sessions SET end_ms=?,version=? WHERE uuid=?`, v.EndMS, v.Version, v.UUID)
|
||||||
|
if err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return v, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return v, tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskReportDay struct {
|
||||||
|
Date string `json:"date"`
|
||||||
|
Completed int `json:"completed"`
|
||||||
|
Points int `json:"points"`
|
||||||
|
Estimate int `json:"estimate_minutes"`
|
||||||
|
WorkMS int64 `json:"work_ms"`
|
||||||
|
FocusMS int64 `json:"focus_ms"`
|
||||||
|
}
|
||||||
|
type TaskReportItem struct {
|
||||||
|
UUID string `json:"uuid"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
ProjectUUID string `json:"project_uuid"`
|
||||||
|
WorkMS int64 `json:"work_ms"`
|
||||||
|
Points int `json:"points"`
|
||||||
|
Completed bool `json:"completed"`
|
||||||
|
}
|
||||||
|
type TaskReport struct {
|
||||||
|
Days []TaskReportDay `json:"days"`
|
||||||
|
Tasks []TaskReportItem `json:"tasks"`
|
||||||
|
Sessions []TaskWork `json:"sessions"`
|
||||||
|
Partial bool `json:"partial"`
|
||||||
|
Timezone string `json:"timezone"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end, now time.Time) (TaskReport, error) {
|
||||||
|
out := TaskReport{Days: []TaskReportDay{}, Tasks: []TaskReportItem{}, Sessions: []TaskWork{}, Timezone: start.Location().String()}
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if !end.After(start) || end.Sub(start) > 367*24*time.Hour {
|
||||||
|
return out, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
days := map[string]int{}
|
||||||
|
for day := start; day.Before(end); day = day.AddDate(0, 0, 1) {
|
||||||
|
days[day.Format("2006-01-02")] = len(out.Days)
|
||||||
|
out.Days = append(out.Days, TaskReportDay{Date: day.Format("2006-01-02")})
|
||||||
|
}
|
||||||
|
byTask := map[string]int{}
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT m.completed_ms,m.estimate,m.complexity,m.task_uuid,COALESCE(i.title,''),COALESCE(i.project_uuid,'') FROM organizer_task_metrics m LEFT JOIN organizer_items i ON i.domain_uuid=m.domain_uuid AND i.owner_uuid=m.owner_uuid AND i.uuid=m.task_uuid WHERE m.domain_uuid=? AND m.owner_uuid=? AND m.completed_ms>=? AND m.completed_ms<? ORDER BY m.completed_ms,m.task_uuid LIMIT 10001`, domain, actor, start.UnixMilli(), end.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n := 0
|
||||||
|
for rows.Next() {
|
||||||
|
var ms int64
|
||||||
|
var estimate, complexity int
|
||||||
|
var id, title, project string
|
||||||
|
if err = rows.Scan(&ms, &estimate, &complexity, &id, &title, &project); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
if n > 10000 {
|
||||||
|
out.Partial = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if index, ok := days[time.UnixMilli(ms).In(start.Location()).Format("2006-01-02")]; ok {
|
||||||
|
d := &out.Days[index]
|
||||||
|
d.Completed++
|
||||||
|
d.Estimate += estimate
|
||||||
|
d.Points += 1 + ((estimate+29)/30)*max(1, complexity)
|
||||||
|
byTask[id] = len(out.Tasks)
|
||||||
|
out.Tasks = append(out.Tasks, TaskReportItem{UUID: id, Title: title, ProjectUUID: project, Completed: true, Points: 1 + ((estimate+29)/30)*max(1, complexity)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
// Split intervals at local midnight; never assume a day is exactly 24h.
|
||||||
|
addSpan := func(a, b int64, focus bool) int64 {
|
||||||
|
a = max(a, start.UnixMilli())
|
||||||
|
b = min(b, end.UnixMilli(), now.UnixMilli())
|
||||||
|
if b <= a {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
total := b - a
|
||||||
|
for a < b {
|
||||||
|
t := time.UnixMilli(a).In(start.Location())
|
||||||
|
next := time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()).UnixMilli()
|
||||||
|
stop := min(next, b)
|
||||||
|
if index, ok := days[t.Format("2006-01-02")]; ok {
|
||||||
|
if focus {
|
||||||
|
out.Days[index].FocusMS += stop - a
|
||||||
|
} else {
|
||||||
|
out.Days[index].WorkMS += stop - a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a = stop
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
rows, err = s.DB.QueryContext(ctx, `SELECT w.uuid,w.task_uuid,w.start_ms,w.end_ms,w.version,COALESCE(i.title,''),COALESCE(i.project_uuid,'') FROM organizer_work_sessions w LEFT JOIN organizer_items i ON i.domain_uuid=w.domain_uuid AND i.owner_uuid=w.owner_uuid AND i.uuid=w.task_uuid WHERE w.domain_uuid=? AND w.owner_uuid=? AND w.start_ms<? AND (w.end_ms=0 OR w.end_ms>?) ORDER BY w.start_ms DESC,w.uuid LIMIT 10001`, domain, actor, end.UnixMilli(), start.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n = 0
|
||||||
|
for rows.Next() {
|
||||||
|
var v TaskWork
|
||||||
|
var title, project string
|
||||||
|
if err = rows.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version, &title, &project); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
if n > 10000 {
|
||||||
|
out.Partial = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
finish := v.EndMS
|
||||||
|
if finish == 0 {
|
||||||
|
finish = now.UnixMilli()
|
||||||
|
}
|
||||||
|
elapsed := addSpan(v.StartMS, finish, false)
|
||||||
|
if elapsed == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out.Sessions = append(out.Sessions, v)
|
||||||
|
index, ok := byTask[v.TaskUUID]
|
||||||
|
if !ok {
|
||||||
|
index = len(out.Tasks)
|
||||||
|
byTask[v.TaskUUID] = index
|
||||||
|
out.Tasks = append(out.Tasks, TaskReportItem{UUID: v.TaskUUID, Title: title, ProjectUUID: project})
|
||||||
|
}
|
||||||
|
out.Tasks[index].WorkMS += elapsed
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
rows, err = s.DB.QueryContext(ctx, `SELECT start_ms,end_ms FROM organizer_focus_spans WHERE domain_uuid=? AND owner_uuid=? AND start_ms>=? AND start_ms<? AND end_ms>? AND phase='focus' ORDER BY start_ms,session_uuid,version LIMIT 10001`, domain, actor, start.Add(-180*time.Minute).UnixMilli(), end.UnixMilli(), start.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
n = 0
|
||||||
|
for rows.Next() {
|
||||||
|
var a, b int64
|
||||||
|
if err = rows.Scan(&a, &b); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
if n > 10000 {
|
||||||
|
out.Partial = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
addSpan(a, b, true)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
+22
-1
@@ -36,6 +36,8 @@ type TaskRecord struct {
|
|||||||
DueOn string `json:"due_on"`
|
DueOn string `json:"due_on"`
|
||||||
PlannedOn string `json:"planned_on"`
|
PlannedOn string `json:"planned_on"`
|
||||||
ReviewOn string `json:"review_on"`
|
ReviewOn string `json:"review_on"`
|
||||||
|
AssigneeUUID string `json:"assignee_uuid,omitempty"`
|
||||||
|
Complexity int `json:"complexity,omitempty"`
|
||||||
PageUUID string `json:"page_uuid"`
|
PageUUID string `json:"page_uuid"`
|
||||||
Archived bool `json:"archived"`
|
Archived bool `json:"archived"`
|
||||||
Version int64 `json:"version"`
|
Version int64 `json:"version"`
|
||||||
@@ -96,7 +98,10 @@ func (s *Store) EnsureTasksSchema() error {
|
|||||||
if err := s.ensureTaskBlocksSchema(); err != nil {
|
if err := s.ensureTaskBlocksSchema(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return s.ensureTaskFocusSchema()
|
if err := s.ensureTaskFocusSchema(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.ensureSchemaComponent("task-productivity")
|
||||||
}
|
}
|
||||||
|
|
||||||
func validTaskDate(v string) bool {
|
func validTaskDate(v string) bool {
|
||||||
@@ -108,6 +113,9 @@ func validTaskDate(v string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func validateTask(item *TaskRecord) error {
|
func validateTask(item *TaskRecord) error {
|
||||||
|
if item.Complexity < 0 || item.Complexity > 5 {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
if !validTaskNotesSubpath(item.NotesSubpath) || (item.Kind != "project" && item.NotesSubpath != "") {
|
if !validTaskNotesSubpath(item.NotesSubpath) || (item.Kind != "project" && item.NotesSubpath != "") {
|
||||||
return ErrTaskInvalid
|
return ErrTaskInvalid
|
||||||
}
|
}
|
||||||
@@ -188,6 +196,9 @@ func (s *Store) SaveTask(ctx context.Context, domain, actor string, item TaskRec
|
|||||||
|
|
||||||
// prepare participates in the same writer transaction as the task head.
|
// prepare participates in the same writer transaction as the task head.
|
||||||
func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRecord, expected int64, prepare func(*sql.Tx, *TaskRecord, TaskRecord) error) (TaskRecord, error) {
|
func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRecord, expected int64, prepare func(*sql.Tx, *TaskRecord, TaskRecord) error) (TaskRecord, error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return TaskRecord{}, ErrReadOnly
|
||||||
|
}
|
||||||
if err := validateTask(&item); err != nil {
|
if err := validateTask(&item); err != nil {
|
||||||
return TaskRecord{}, err
|
return TaskRecord{}, err
|
||||||
}
|
}
|
||||||
@@ -266,6 +277,11 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
|
|||||||
if err = s.validateTaskParentTx(ctx, tx, domain, actor, item, old); err != nil {
|
if err = s.validateTaskParentTx(ctx, tx, domain, actor, item, old); err != nil {
|
||||||
return TaskRecord{}, err
|
return TaskRecord{}, err
|
||||||
}
|
}
|
||||||
|
if item.AssigneeUUID != old.AssigneeUUID {
|
||||||
|
if err = validateTaskAssignee(ctx, tx, domain, item.AssigneeUUID); err != nil {
|
||||||
|
return TaskRecord{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
// DAV identity and round-trip metadata are writable only through the DAV
|
// DAV identity and round-trip metadata are writable only through the DAV
|
||||||
// transaction callback, never through a generic JSON/UI update.
|
// transaction callback, never through a generic JSON/UI update.
|
||||||
item.CalDAV = old.CalDAV
|
item.CalDAV = old.CalDAV
|
||||||
@@ -330,6 +346,11 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
|
|||||||
if err = s.syncTaskRemindersTx(ctx, tx, domain, actor, item); err != nil {
|
if err = s.syncTaskRemindersTx(ctx, tx, domain, actor, item); err != nil {
|
||||||
return TaskRecord{}, err
|
return TaskRecord{}, err
|
||||||
}
|
}
|
||||||
|
if item.Kind == "task" {
|
||||||
|
if _, err = tx.ExecContext(ctx, `INSERT INTO organizer_task_metrics VALUES(?,?,?,?,?,?) ON CONFLICT(domain_uuid,task_uuid) DO UPDATE SET completed_ms=excluded.completed_ms,estimate=excluded.estimate,complexity=excluded.complexity`, domain, actor, item.UUID, item.CompletedMS, item.Estimate, max(1, item.Complexity)); err != nil {
|
||||||
|
return TaskRecord{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
if err = tx.Commit(); err != nil {
|
if err = tx.Commit(); err != nil {
|
||||||
return TaskRecord{}, err
|
return TaskRecord{}, err
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-1
@@ -51,7 +51,7 @@ CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログイ
|
|||||||
OIDCで認証した場合は、追加のローカルTOTPを要求しません。承認後はCLIが専用セッションを受け取ります。
|
OIDCで認証した場合は、追加のローカルTOTPを要求しません。承認後はCLIが専用セッションを受け取ります。
|
||||||
OIDCプロバイダーのパスワードやトークンをターミナルに入力する必要はありません。
|
OIDCプロバイダーのパスワードやトークンをターミナルに入力する必要はありません。
|
||||||
プロバイダー側のMFAポリシーはそのまま適用されます。パスワードログイン時のローカルTOTPも変更しません。
|
プロバイダー側のMFAポリシーはそのまま適用されます。パスワードログイン時のローカルTOTPも変更しません。
|
||||||
この追加TOTP省略はv0.3.0より後の変更です。v0.3.0のサーバーでは従来どおりTOTPを要求します。
|
この追加TOTP省略にはv0.4.0以降のサーバーが必要です。v0.3.0では従来どおりTOTPを要求します。
|
||||||
|
|
||||||
ユーザー名の指定は省略できます。指定済みならブラウザで認証したユーザーとの一致を確認し、
|
ユーザー名の指定は省略できます。指定済みならブラウザで認証したユーザーとの一致を確認し、
|
||||||
不一致時は発行セッションの失効を試みて保存しません。`pages logout` 後に設定を変更できます。
|
不一致時は発行セッションの失効を試みて保存しません。`pages logout` 後に設定を変更できます。
|
||||||
@@ -128,6 +128,8 @@ Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位
|
|||||||
|
|
||||||
### 言語を指定して編集する
|
### 言語を指定して編集する
|
||||||
|
|
||||||
|
`auto` 言語選択と未作成言語版の編集は、v0.4.0以降のCLIで利用できます。
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
pages edit /guide --lang auto # 表示される言語の最新版を編集
|
pages edit /guide --lang auto # 表示される言語の最新版を編集
|
||||||
pages edit /guide --lang ja # 日本語版。未作成なら既存内容から開始
|
pages edit /guide --lang ja # 日本語版。未作成なら既存内容から開始
|
||||||
@@ -151,3 +153,8 @@ go test ./internal/server -run TestRemoteCLIHTTPIntegration -count=1
|
|||||||
```
|
```
|
||||||
|
|
||||||
偽サーバと一時DBのみを使用します。本番資格情報や外部カレンダーは不要です。
|
偽サーバと一時DBのみを使用します。本番資格情報や外部カレンダーは不要です。
|
||||||
|
## タスクと連絡先
|
||||||
|
|
||||||
|
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。
|
||||||
|
`pages contacts --help` で個人アドレス帳の検索・vCard入出力を行える。
|
||||||
|
[neomutt設定と操作例](../docs/operations/neomutt-tasks.md)を参照。
|
||||||
+193
-5
@@ -1,6 +1,9 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""pages — navigate and edit PagesWiki from your terminal (pages-cli)."""
|
"""pages — navigate and edit PagesWiki from your terminal (pages-cli)."""
|
||||||
import argparse
|
import argparse
|
||||||
|
import email.policy
|
||||||
|
import email.parser
|
||||||
|
import uuid
|
||||||
import base64
|
import base64
|
||||||
import contextlib
|
import contextlib
|
||||||
import difflib
|
import difflib
|
||||||
@@ -75,16 +78,18 @@ class Client:
|
|||||||
self.base, self.token, self.lang = origin(base), token, lang
|
self.base, self.token, self.lang = origin(base), token, lang
|
||||||
self.opener = http.build_opener(NoRedirect())
|
self.opener = http.build_opener(NoRedirect())
|
||||||
|
|
||||||
def request(self, route, method='GET', data=None, form=None, limit=4 << 20):
|
def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None):
|
||||||
if not route.startswith('/') or route.startswith('//'):
|
if not route.startswith('/') or route.startswith('//'):
|
||||||
raise Failure('Invalid API route.')
|
raise Failure('Invalid API route.')
|
||||||
headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/0.1'}
|
headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/0.1'}
|
||||||
|
if etag is not None:
|
||||||
|
headers['If-Match'] = etag
|
||||||
if self.token:
|
if self.token:
|
||||||
headers['Authorization'] = 'Bearer ' + self.token
|
headers['Authorization'] = 'Bearer ' + self.token
|
||||||
body = None
|
body = None
|
||||||
if data is not None:
|
if data is not None:
|
||||||
body = json.dumps(data, ensure_ascii=False).encode()
|
body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
|
||||||
headers['Content-Type'] = 'application/json'
|
headers['Content-Type'] = content_type or 'application/json'
|
||||||
if form is not None:
|
if form is not None:
|
||||||
body = url.urlencode(form).encode()
|
body = url.urlencode(form).encode()
|
||||||
headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
||||||
@@ -107,7 +112,8 @@ class Client:
|
|||||||
if not isinstance(payload, dict):
|
if not isinstance(payload, dict):
|
||||||
payload = {}
|
payload = {}
|
||||||
messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.',
|
messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.',
|
||||||
404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.'}
|
404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.',
|
||||||
|
412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.'}
|
||||||
raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None
|
raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None
|
||||||
except (urllib.error.URLError, TimeoutError, OSError):
|
except (urllib.error.URLError, TimeoutError, OSError):
|
||||||
raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None
|
raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None
|
||||||
@@ -440,7 +446,183 @@ def editor(client, addr, mode):
|
|||||||
print('Local edit retained:', safe_text(file), file=sys.stderr)
|
print('Local edit retained:', safe_text(file), file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
TASK_API = '/_/api/v1/extension/organizer.tasks/'
|
||||||
|
|
||||||
|
|
||||||
|
def task_uuid(value):
|
||||||
|
try:
|
||||||
|
parsed = str(uuid.UUID(value))
|
||||||
|
if parsed != value: raise ValueError()
|
||||||
|
return parsed
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
raise Failure('Use a canonical task or project UUID.') from None
|
||||||
|
|
||||||
|
|
||||||
|
def task_project(client, value):
|
||||||
|
if value == '': return ''
|
||||||
|
try: return task_uuid(value)
|
||||||
|
except Failure: pass
|
||||||
|
data = client.json(TASK_API+'items?'+url.urlencode({'kind':'project','view':'all','q':value,'limit':100}))
|
||||||
|
matches = [item['uuid'] for item in data.get('items',[]) if item['title'] == value]
|
||||||
|
if len(matches) != 1 or data.get('next'):
|
||||||
|
raise Failure('Project name is missing or ambiguous; use its UUID.')
|
||||||
|
return matches[0]
|
||||||
|
|
||||||
|
|
||||||
|
def task_mail(raw, include_body=False, override_title=None):
|
||||||
|
if len(raw) > 2 << 20: raise Failure('Mail input exceeds 2 MiB; pipe one message at a time.')
|
||||||
|
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||||
|
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
||||||
|
title = override_title or clean(message.get('Subject')) or '(No subject)'
|
||||||
|
if len(title.encode()) > 300: raise Failure('Mail subject exceeds 300 UTF-8 bytes; use --title.')
|
||||||
|
notes = '\n'.join(key+': '+clean(message.get(key)) for key in ('From','Date','Message-ID') if message.get(key))
|
||||||
|
if include_body:
|
||||||
|
part = message.get_body(preferencelist=('plain',))
|
||||||
|
if part:
|
||||||
|
content = part.get_content()
|
||||||
|
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
||||||
|
notes += '\n\n' + content
|
||||||
|
if len(notes.encode()) > 16384: raise Failure('Mail notes exceed 16 KiB; omit --include-body.')
|
||||||
|
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def tasks(client, profile, words):
|
||||||
|
parser = argparse.ArgumentParser(prog='pages task',description='Private task capture, planning and work-time records. Stops do not complete a task.')
|
||||||
|
sub = parser.add_subparsers(dest='action',required=True)
|
||||||
|
p=sub.add_parser('list');p.add_argument('--view',default='all',choices=['all','today','inbox','backlog','someday','review','done','archived','carryover']);p.add_argument('--project');p.add_argument('--q',default='');p.add_argument('--before',default='')
|
||||||
|
sub.add_parser('projects')
|
||||||
|
p=sub.add_parser('project-add');p.add_argument('title');p.add_argument('--notes',default='')
|
||||||
|
p=sub.add_parser('show');p.add_argument('uuid',type=task_uuid)
|
||||||
|
for name in ('add','from-mail','update'):
|
||||||
|
p=sub.add_parser(name)
|
||||||
|
if name=='add':p.add_argument('title')
|
||||||
|
elif name=='update':p.add_argument('uuid',type=task_uuid);p.add_argument('--title')
|
||||||
|
else:p.add_argument('--title');p.add_argument('--include-body',action='store_true')
|
||||||
|
p.add_argument('--notes');p.add_argument('--project');p.add_argument('--assignee')
|
||||||
|
p.add_argument('--due');p.add_argument('--start-on');p.add_argument('--planned');p.add_argument('--review')
|
||||||
|
p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int,choices=range(1,6))
|
||||||
|
if name=='add':p.add_argument('--request-id',type=task_uuid)
|
||||||
|
for name in ('done','reopen','archive','start'):
|
||||||
|
p=sub.add_parser(name);p.add_argument('uuid',type=task_uuid)
|
||||||
|
sub.add_parser('stop');sub.add_parser('status')
|
||||||
|
p=sub.add_parser('retry');p.add_argument('request_id',type=task_uuid)
|
||||||
|
p=sub.add_parser('report');p.add_argument('--from',dest='start');p.add_argument('--to',dest='end')
|
||||||
|
p=sub.add_parser('preferences');p.add_argument('--project');p.add_argument('--assignee');p.add_argument('--due-days',type=int);p.add_argument('--start-days',type=int);p.add_argument('--planned-days',type=int);p.add_argument('--review-days',type=int);p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int);p.add_argument('--digest',choices=['on','off']);p.add_argument('--at');p.add_argument('--timezone')
|
||||||
|
for child in sub.choices.values():child.add_argument('--json',action='store_true')
|
||||||
|
a=parser.parse_args(words);action=a.action
|
||||||
|
def emit(data): print(json.dumps(data,ensure_ascii=False,indent=2))
|
||||||
|
def capture(payload):
|
||||||
|
pending=profile.data.setdefault('task_outbox',{})
|
||||||
|
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
||||||
|
pending[payload['request_id']]=payload;profile.save()
|
||||||
|
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
||||||
|
except Failure:
|
||||||
|
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr);raise
|
||||||
|
del pending[payload['request_id']];profile.save();return result
|
||||||
|
if action in ('list','projects'):
|
||||||
|
query={'kind':'project' if action=='projects' else 'task','view':getattr(a,'view','all'),'limit':100,'q':getattr(a,'q',''),'before':getattr(a,'before','')}
|
||||||
|
if getattr(a,'project',None) is not None:query['project']=task_project(client,a.project)
|
||||||
|
data=client.json(TASK_API+'items?'+url.urlencode(query))
|
||||||
|
if a.json:emit(data)
|
||||||
|
else:
|
||||||
|
for item in data.get('items',[]):print(safe_text('\t'.join([item['uuid'],item['status'],item.get('due_on',''),item['title']])))
|
||||||
|
if data.get('next'):print('Next page: --before '+data['next'],file=sys.stderr)
|
||||||
|
return
|
||||||
|
if action=='show':emit(client.json(TASK_API+'items/'+a.uuid));return
|
||||||
|
if action=='preferences':
|
||||||
|
data=client.json(TASK_API+'preferences');p=data['preferences'];changed=False
|
||||||
|
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due_days','due_days'),('start_days','start_days'),('planned_days','planned_days'),('review_days','review_days'),('estimate','estimate_minutes'),('complexity','complexity'),('at','digest_time'),('timezone','timezone')]:
|
||||||
|
value=getattr(a,attr)
|
||||||
|
if value is not None:p[key]=task_project(client,value) if attr=='project' else value;changed=True
|
||||||
|
if a.digest:p['digest_enabled']=a.digest=='on';changed=True
|
||||||
|
emit(client.json(TASK_API+'preferences',method='PUT',data=p) if changed else data);return
|
||||||
|
if action=='retry':
|
||||||
|
payload=profile.data.get('task_outbox',{}).get(a.request_id)
|
||||||
|
if not payload:raise Failure('No retained task capture with this request ID.')
|
||||||
|
emit(capture(payload));return
|
||||||
|
if action in ('add','from-mail'):
|
||||||
|
payload={'request_id':getattr(a,'request_id',None) or str(uuid.uuid4()),'title':a.title,'notes':a.notes or ''}
|
||||||
|
if action=='from-mail':
|
||||||
|
title,notes,message_id=task_mail(sys.stdin.buffer.read((2<<20)+1),a.include_body,a.title)
|
||||||
|
payload.update(title=a.title or title,notes=a.notes if a.notes is not None else notes,request_id=str(uuid.uuid5(uuid.NAMESPACE_URL,client.base+'\n'+profile.data.get('username','')+'\n'+message_id)))
|
||||||
|
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
||||||
|
value=getattr(a,attr)
|
||||||
|
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
||||||
|
emit(capture(payload));return
|
||||||
|
if action=='project-add':
|
||||||
|
emit(client.json(TASK_API+'items',method='POST',data={'uuid':str(uuid.uuid4()),'kind':'project','title':a.title,'notes':a.notes,'status':'todo','bucket':'inbox','priority':1}));return
|
||||||
|
if action in ('update','done','reopen','archive'):
|
||||||
|
item=client.json(TASK_API+'items/'+a.uuid)['item']
|
||||||
|
if item['kind']!='task':raise Failure('This operation requires a task.')
|
||||||
|
for attr,key in [('title','title'),('notes','notes'),('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
||||||
|
value=getattr(a,attr,None)
|
||||||
|
if value is not None:item[key]=task_project(client,value) if attr=='project' else value
|
||||||
|
if action=='done':item['status']='done'
|
||||||
|
elif action=='reopen':item['status']='todo'
|
||||||
|
elif action=='archive':item['archived']=True
|
||||||
|
emit(client.json(TASK_API+'items/'+a.uuid,method='PUT',data=item,etag='"'+str(item['version'])+'"'));return
|
||||||
|
if action=='start':
|
||||||
|
emit(client.json(TASK_API+'work',method='POST',data={'action':'start','uuid':str(uuid.uuid4()),'task_uuid':a.uuid,'version':0}));return
|
||||||
|
if action in ('stop','status'):
|
||||||
|
data=client.json(TASK_API+'work')
|
||||||
|
if action=='stop':
|
||||||
|
if not data['item']:raise Failure('No running work timer in this Domain.')
|
||||||
|
data=client.json(TASK_API+'work',method='POST',data={**data['item'],'action':'stop'})
|
||||||
|
emit(data);return
|
||||||
|
if action=='report':
|
||||||
|
query={k:v for k,v in [('from',a.start),('to',a.end)] if v}
|
||||||
|
data=client.json(TASK_API+'report?'+url.urlencode(query))
|
||||||
|
if a.json:emit(data);return
|
||||||
|
print('Timezone:',safe_text(data['timezone']))
|
||||||
|
print('Date\tCompleted\tPoints\tWork minutes\tPomodoro minutes')
|
||||||
|
for day in data['days']:
|
||||||
|
if day['completed'] or day['work_ms'] or day['focus_ms']:print('%s\t%d\t%d\t%.1f\t%.1f'%(day['date'],day['completed'],day['points'],day['work_ms']/60000,day['focus_ms']/60000))
|
||||||
|
print('\nTask UUID\tWork minutes\tTitle')
|
||||||
|
for task in data['tasks']:print(safe_text('%s\t%.1f\t%s'%(task['uuid'],task['work_ms']/60000,task['title'])))
|
||||||
|
if data['partial']:print('Partial report: narrow the date range.',file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
def contacts(client, words):
|
||||||
|
parser=argparse.ArgumentParser(prog='pages contacts',description='Private address book; never links contacts to login accounts.')
|
||||||
|
sub=parser.add_subparsers(dest='action',required=True)
|
||||||
|
p=sub.add_parser('list');p.add_argument('--query',default='');p.add_argument('--after',default='')
|
||||||
|
p=sub.add_parser('query');p.add_argument('query');p.add_argument('--neomutt',action='store_true')
|
||||||
|
p=sub.add_parser('show');p.add_argument('uuid',type=task_uuid)
|
||||||
|
p=sub.add_parser('export');p.add_argument('uuid',type=task_uuid)
|
||||||
|
p=sub.add_parser('import');p.add_argument('file',type=Path)
|
||||||
|
a=parser.parse_args(words);api='/_/api/v1/extension/organizer.contacts/'
|
||||||
|
if a.action=='import':
|
||||||
|
with a.file.open('rb') as f:raw=f.read(65537)
|
||||||
|
if len(raw)>65536:raise Failure('One UTF-8 vCard per import, up to 64 KiB. Use the Web importer for multiple cards.')
|
||||||
|
data=client.json(api+'import',method='POST',data=raw,content_type='text/vcard')
|
||||||
|
elif a.action=='export':
|
||||||
|
data=client.json(api+'items/'+a.uuid);sys.stdout.write(data['item']['vcard']);return
|
||||||
|
elif a.action=='show':data=client.json(api+'items/'+a.uuid)
|
||||||
|
else:
|
||||||
|
try: data=client.json(api+'items?'+url.urlencode({'q':a.query,'after':getattr(a,'after','')}))
|
||||||
|
except Failure:
|
||||||
|
if a.action=='query' and a.neomutt: print('PagesWiki address query failed; check login and permissions.')
|
||||||
|
raise
|
||||||
|
if a.action=='query' and a.neomutt:
|
||||||
|
if not any(item['emails'] for item in data.get('items',[])):
|
||||||
|
print('No matching email addresses.')
|
||||||
|
raise Failure('No matching email addresses.')
|
||||||
|
print('PagesWiki contacts'+(' (first 100; narrow query)' if data.get('next') else ''))
|
||||||
|
for item in data.get('items',[]):
|
||||||
|
clean=lambda v:' '.join(safe_text(v).split())
|
||||||
|
for address in item['emails']:
|
||||||
|
# Do not let imported metadata forge query result columns.
|
||||||
|
if '\t' not in address and '\n' not in address and '\r' not in address:
|
||||||
|
print(clean(address)+'\t'+clean(item['name'])+'\t'+clean(item['organization']))
|
||||||
|
return
|
||||||
|
print(json.dumps(data,ensure_ascii=False,indent=2))
|
||||||
|
|
||||||
|
|
||||||
def execute(client, profile, words):
|
def execute(client, profile, words):
|
||||||
|
if words and words[0] in ('contact','contacts'):
|
||||||
|
return contacts(client,words[1:])
|
||||||
|
if words and words[0] in ('task','tasks'):
|
||||||
|
return tasks(client,profile,words[1:])
|
||||||
parser = argparse.ArgumentParser(prog='pages')
|
parser = argparse.ArgumentParser(prog='pages')
|
||||||
sub = parser.add_subparsers(dest='command', required=True)
|
sub = parser.add_subparsers(dest='command', required=True)
|
||||||
for command in ('ls', 'cd', 'cat', 'view', 'edit', 'open'):
|
for command in ('ls', 'cd', 'cat', 'view', 'edit', 'open'):
|
||||||
@@ -556,7 +738,7 @@ def shell(client, profile):
|
|||||||
|
|
||||||
|
|
||||||
def main(argv=None):
|
def main(argv=None):
|
||||||
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, search, open. Use pages COMMAND --help.')
|
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, search, open, task, contacts. Use pages COMMAND --help.')
|
||||||
parser.add_argument('--profile', help='Use another configured connection for this invocation')
|
parser.add_argument('--profile', help='Use another configured connection for this invocation')
|
||||||
parser.add_argument('--lang', help='auto or an exact language tag for this invocation')
|
parser.add_argument('--lang', help='auto or an exact language tag for this invocation')
|
||||||
parser.add_argument('command', nargs='?', default='shell')
|
parser.add_argument('command', nargs='?', default='shell')
|
||||||
@@ -595,8 +777,14 @@ def main(argv=None):
|
|||||||
username = spec['username']
|
username = spec['username']
|
||||||
expires = client.login(username, getpass.getpass('Password: '))
|
expires = client.login(username, getpass.getpass('Password: '))
|
||||||
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
|
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
|
||||||
|
pending = profile.data.get('task_outbox', {})
|
||||||
|
if pending and not same_identity:
|
||||||
|
try: client.json('/_/auth/logout', method='POST')
|
||||||
|
except Failure: pass
|
||||||
|
raise Failure('Pending task drafts belong to the previous account. Use a separate profile; the drafts were retained.')
|
||||||
cwd = profile.data.get('cwd', '/') if same_identity else '/'
|
cwd = profile.data.get('cwd', '/') if same_identity else '/'
|
||||||
profile.data = {'origin': client.base, 'username': username, 'configured_username': spec.get('username', ''), 'token': client.token, 'expires': expires, 'cwd': cwd}
|
profile.data = {'origin': client.base, 'username': username, 'configured_username': spec.get('username', ''), 'token': client.token, 'expires': expires, 'cwd': cwd}
|
||||||
|
if pending: profile.data['task_outbox'] = pending
|
||||||
try:
|
try:
|
||||||
profile.save()
|
profile.save()
|
||||||
except OSError:
|
except OSError:
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import runpy
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
|
|
||||||
|
class ProductivityTests(unittest.TestCase):
|
||||||
|
def test_mail_privacy_and_long_subject_override(self):
|
||||||
|
raw=b'Subject: Test\r\nFrom: Person <person@example.invalid>\r\nMessage-ID: <id@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPRIVATE BODY'
|
||||||
|
title,notes,ident=m['task_mail'](raw)
|
||||||
|
self.assertEqual(title,'Test');self.assertNotIn('PRIVATE BODY',notes);self.assertIn('Message-ID:',notes)
|
||||||
|
self.assertIn('PRIVATE BODY',m['task_mail'](raw,True)[1])
|
||||||
|
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
||||||
|
with self.assertRaises(m['Failure']):m['task_mail'](raw)
|
||||||
|
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
||||||
|
|
||||||
|
def test_capture_retains_request_until_explicit_retry(self):
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kwargs):
|
||||||
|
calls.append(kwargs['data'].copy())
|
||||||
|
if len(calls)==1:raise m['Failure']('offline')
|
||||||
|
return {'item':{'uuid':kwargs['data']['request_id']}}
|
||||||
|
profile=SimpleNamespace(data={},save=lambda:None)
|
||||||
|
client=SimpleNamespace(json=send)
|
||||||
|
with contextlib.redirect_stdout(io.StringIO()),contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](client,profile,['add','Offline task'])
|
||||||
|
ident=next(iter(profile.data['task_outbox']))
|
||||||
|
m['tasks'](client,profile,['retry',ident])
|
||||||
|
self.assertEqual(calls[0],calls[1]);self.assertEqual(profile.data['task_outbox'],{})
|
||||||
|
|
||||||
|
def test_neomutt_query_columns_are_not_forgeable(self):
|
||||||
|
client=SimpleNamespace(json=lambda *a,**kw:{'items':[{'name':'A\tB\nC','emails':['a@example.invalid'],'organization':'Org\nInjected'}]})
|
||||||
|
out=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(out):m['contacts'](client,['query','A','--neomutt'])
|
||||||
|
rows=out.getvalue().splitlines();self.assertEqual(len(rows),2);self.assertEqual(len(rows[1].split('\t')),3)
|
||||||
|
|
||||||
|
def test_command_help_without_credentials(self):
|
||||||
|
for cmd in [('task','--help'),('contacts','--help'),('task','add','--help')]:
|
||||||
|
with contextlib.redirect_stdout(io.StringIO()),self.assertRaises(SystemExit) as raised:m['main'](list(cmd))
|
||||||
|
self.assertEqual(raised.exception.code,0)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""Called by the Go synthetic HTTP fixture; no production credentials."""
|
||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import runpy
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def run():
|
||||||
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
|
fixture=json.load(sys.stdin)
|
||||||
|
client=m['Client'](fixture['origin'],fixture['token'])
|
||||||
|
profile=m['Profile']('test',fixture['root'])
|
||||||
|
def task(*words):
|
||||||
|
output=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output):m['tasks'](client,profile,list(words))
|
||||||
|
return json.loads(output.getvalue())
|
||||||
|
with profile.locked():
|
||||||
|
prefs=task('preferences','--due-days','2','--estimate','60','--complexity','3')
|
||||||
|
assert prefs['preferences']['due_days']==2
|
||||||
|
item=task('add','CLI task')['item'];ident=item['uuid']
|
||||||
|
assert item['estimate_minutes']==60 and item['due_on']
|
||||||
|
task('start',ident);assert task('status')['item']['task_uuid']==ident
|
||||||
|
task('stop');assert task('status')['item'] is None
|
||||||
|
item=task('update',ident,'--title','Updated CLI task')['item'];assert item['title']=='Updated CLI task'
|
||||||
|
task('done',ident)
|
||||||
|
report=task('report','--json');assert sum(d['points'] for d in report['days'])==7
|
||||||
|
assert any(i['uuid']==ident for i in report['tasks'])
|
||||||
|
path=Path(fixture['root'])/'person.vcf'
|
||||||
|
path.write_text('BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:cli\r\nFN:CLI Person\r\nEMAIL:cli@example.invalid\r\nEND:VCARD\r\n')
|
||||||
|
output=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output):m['contacts'](client,['import',str(path)])
|
||||||
|
contact=json.loads(output.getvalue())['item'];output=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output):m['contacts'](client,['query','CLI','--neomutt'])
|
||||||
|
assert 'cli@example.invalid\tCLI Person\t' in output.getvalue()
|
||||||
|
output=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output):m['contacts'](client,['export',contact['uuid']])
|
||||||
|
assert 'UID:urn:test:cli' in output.getvalue()
|
||||||
|
|
||||||
|
if __name__=='__main__':run()
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#contacts-app{max-width:1200px;margin:auto;padding:1rem}#contacts-controls{display:flex;gap:.5rem;flex-wrap:wrap}.contacts-layout{display:grid;grid-template-columns:minmax(200px,1fr) minmax(300px,2fr);gap:1rem;margin-top:1rem}#contacts-list>button{display:block;width:100%;text-align:start;padding:.5rem;border:0;border-bottom:1px solid var(--border-color,#7775);background:transparent;color:inherit}#contact-editor form{display:grid;gap:.6rem}#contact-editor label{display:grid;grid-template-columns:8rem 1fr;gap:.5rem}#contact-editor input,#contact-editor textarea{width:100%;min-width:0}#contact-editor textarea{min-height:5rem}#contact-editor details pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:20rem;overflow:auto}@media(max-width:650px){.contacts-layout{grid-template-columns:1fr}#contacts-list{max-height:30vh;overflow:auto}#contact-editor label{grid-template-columns:1fr}}
|
||||||
|
#contacts-app,#contacts-app *{box-sizing:border-box}.contacts-layout>*{min-width:0}#contacts-list button{overflow-wrap:anywhere}
|
||||||
|
.contact-history-row{display:flex;align-items:center;gap:.4rem;padding:.3rem 0;flex-wrap:wrap}.contact-history-row span{flex:1;min-width:12rem}#contacts-controls>a{align-self:center}
|
||||||
|
@media(max-width:650px){#contacts-app input,#contacts-app select,#contacts-app button{min-height:44px;font-size:16px}}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
#tasks-dav-dialog{box-sizing:border-box;width:min(800px,96vw);max-height:92dvh;overflow:auto;color:var(--fg);background:var(--bg)!important;border:1px solid var(--border,#8885);border-radius:1rem;padding:1rem;box-shadow:0 1rem 4rem #0005}
|
#tasks-dav-dialog{box-sizing:border-box;width:min(800px,96vw);max-height:92dvh;overflow:auto;color:var(--fg);background:var(--bg)!important;border:1px solid var(--border,#8885);border-radius:1rem;padding:1rem;box-shadow:0 1rem 4rem #0005}
|
||||||
#tasks-dav-dialog::backdrop{background:#0007;backdrop-filter:blur(3px)}
|
#tasks-dav-dialog::backdrop{background:#0007;backdrop-filter:blur(3px)}
|
||||||
|
#tasks-dav-dialog [hidden]{display:none!important}
|
||||||
#tasks-dav-dialog header{display:flex;align-items:center;justify-content:space-between;gap:1rem}#tasks-dav-dialog h2{font-size:1.2rem;margin:.25rem 0}#tasks-dav-dialog p{font-size:.9rem}#tasks-dav-dialog form{display:flex;flex-wrap:wrap;gap:.4rem;margin:1rem 0}#tasks-dav-dialog form>input{flex:1;min-width:10rem}#tasks-dav-dialog>input,#tasks-dav-dialog section input{width:100%}#tasks-dav-dialog input,#tasks-dav-dialog select,#tasks-dav-dialog button{box-sizing:border-box;font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--border,#8885);border-radius:.4rem;padding:.5rem;min-width:0}#tasks-dav-dialog button{cursor:pointer}#tasks-dav-dialog :focus-visible{outline:2px solid var(--accent);outline-offset:2px}#tasks-dav-dialog section{padding:.7rem;border:1px solid var(--accent);border-radius:.5rem}#tasks-dav-dialog section label{display:block;font-size:.85rem;margin:.3rem 0}#tasks-dav-dialog .task-dav-table{overflow:auto}#tasks-dav-dialog table{width:100%;border-collapse:collapse;font-size:.85rem}#tasks-dav-dialog th,#tasks-dav-dialog td{padding:.35rem;text-align:left;border-bottom:1px solid var(--border,#8885)}#tasks-dav-dialog td:first-child{overflow-wrap:anywhere}#tasks-dav-dialog [role=status]{color:var(--danger,#d55)}
|
#tasks-dav-dialog header{display:flex;align-items:center;justify-content:space-between;gap:1rem}#tasks-dav-dialog h2{font-size:1.2rem;margin:.25rem 0}#tasks-dav-dialog p{font-size:.9rem}#tasks-dav-dialog form{display:flex;flex-wrap:wrap;gap:.4rem;margin:1rem 0}#tasks-dav-dialog form>input{flex:1;min-width:10rem}#tasks-dav-dialog>input,#tasks-dav-dialog section input{width:100%}#tasks-dav-dialog input,#tasks-dav-dialog select,#tasks-dav-dialog button{box-sizing:border-box;font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--border,#8885);border-radius:.4rem;padding:.5rem;min-width:0}#tasks-dav-dialog button{cursor:pointer}#tasks-dav-dialog :focus-visible{outline:2px solid var(--accent);outline-offset:2px}#tasks-dav-dialog section{padding:.7rem;border:1px solid var(--accent);border-radius:.5rem}#tasks-dav-dialog section label{display:block;font-size:.85rem;margin:.3rem 0}#tasks-dav-dialog .task-dav-table{overflow:auto}#tasks-dav-dialog table{width:100%;border-collapse:collapse;font-size:.85rem}#tasks-dav-dialog th,#tasks-dav-dialog td{padding:.35rem;text-align:left;border-bottom:1px solid var(--border,#8885)}#tasks-dav-dialog td:first-child{overflow-wrap:anywhere}#tasks-dav-dialog [role=status]{color:var(--danger,#d55)}
|
||||||
#tasks-dav-dialog .dav-compat-toggle{display:flex;align-items:center;gap:.5rem;width:100%;font-size:.9rem}#tasks-dav-dialog .dav-compat-toggle input{width:1.2rem;height:1.2rem;min-height:0;flex:none;accent-color:var(--accent)}#tasks-dav-dialog .dav-compat-help{width:100%;margin:.15rem 0;font-size:.85rem;color:var(--muted,var(--fg))}
|
#tasks-dav-dialog .dav-compat-toggle{display:flex;align-items:center;gap:.5rem;width:100%;font-size:.9rem}#tasks-dav-dialog .dav-compat-toggle input{width:1.2rem;height:1.2rem;min-height:0;flex:none;accent-color:var(--accent)}#tasks-dav-dialog .dav-compat-help{width:100%;margin:.15rem 0;font-size:.85rem;color:var(--muted,var(--fg))}
|
||||||
@media(max-width:760px){#tasks-dav-dialog{width:100%;max-width:none;height:100dvh;max-height:100dvh;margin:0;border-radius:0}#tasks-dav-dialog input,#tasks-dav-dialog select,#tasks-dav-dialog button{min-height:44px;font-size:16px}#tasks-dav-dialog .dav-compat-toggle{min-height:44px}}
|
@media(max-width:760px){#tasks-dav-dialog{width:100%;max-width:none;height:100dvh;max-height:100dvh;margin:0;border-radius:0}#tasks-dav-dialog input,#tasks-dav-dialog select,#tasks-dav-dialog button{min-height:44px;font-size:16px}#tasks-dav-dialog .dav-compat-toggle{min-height:44px}}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#task-productivity{max-width:1200px;margin:1rem auto;padding:0 1rem;color:var(--fg,var(--text-color));box-sizing:border-box}
|
||||||
|
body:has(#task-productivity) .topbar,body:has(#contacts-app) .topbar{flex-wrap:wrap;gap:.5rem}
|
||||||
|
#task-productivity,#contacts-app{min-width:0;width:100%;overflow-wrap:anywhere}
|
||||||
|
@media(max-width:600px){body:has(#task-productivity) .topbar,body:has(#contacts-app) .topbar{padding:.5rem;gap:.3rem}body:has(#task-productivity) .topbar>.brand,body:has(#contacts-app) .topbar>.brand{flex:1}body:has(#task-productivity) .topbar>nav{display:none}}
|
||||||
|
.productivity-nav,.productivity-controls{display:flex;flex-wrap:wrap;align-items:center;gap:.65rem;margin:.5rem 0}.productivity-nav a{color:var(--link,var(--accent,#478ddd))}
|
||||||
|
.productivity-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.6rem;margin:1rem 0}.productivity-stat{padding:.6rem;border:1px solid var(--border,#8885);border-radius:.4rem}.productivity-stat strong{display:block;font-size:1.5rem}
|
||||||
|
.productivity-heatmap-scroll{overflow:auto;max-width:100%;padding:.4rem 0}.productivity-heatmap{display:grid;grid-template-rows:repeat(7,13px);grid-auto-flow:column;grid-auto-columns:13px;gap:3px;width:max-content}
|
||||||
|
.productivity-day{padding:0;min-width:0;border:0;border-radius:2px;background:var(--border,#8884);cursor:pointer}.productivity-day[data-level="1"]{background:#9be9a8}.productivity-day[data-level="2"]{background:#40c463}.productivity-day[data-level="3"]{background:#30a14e}.productivity-day[data-level="4"]{background:#216e39}.productivity-day:focus-visible{outline:2px solid var(--link,#4af);outline-offset:2px}
|
||||||
|
.productivity-table-wrap{overflow:auto}.productivity-table{border-collapse:collapse;width:100%}.productivity-table th,.productivity-table td{padding:.35rem .5rem;text-align:left;border-bottom:1px solid var(--border,#8884)}.productivity-table a{color:var(--link,#478ddd)}
|
||||||
|
.productivity-settings{max-width:850px}.productivity-setting{display:grid;grid-template-columns:minmax(180px,1fr) minmax(160px,2fr);gap:.5rem;padding:.4rem 0;border-bottom:1px solid var(--border,#8884);align-items:center}.productivity-setting input,.productivity-setting select,.productivity-controls input{box-sizing:border-box;width:100%;min-width:0;color:inherit;background:var(--input-bg,var(--bg,#222));border:1px solid var(--border,#8887);border-radius:.3rem;padding:.4rem}.productivity-setting input[type=checkbox]{width:2.2rem;height:1.2rem;accent-color:var(--link,#40a060)}.productivity-controls input{width:auto}.productivity-settings button,.productivity-controls button{padding:.4rem .8rem;color:inherit;background:var(--button-bg,var(--bg,#555));border:1px solid var(--border,#8887);border-radius:.3rem;cursor:pointer}.productivity-note{font-size:.85rem;opacity:.8}.productivity-running{padding:.5rem;border:1px solid var(--border,#8885);display:flex;gap:.5rem;align-items:center;flex-wrap:wrap}
|
||||||
|
@media(max-width:600px){.productivity-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.productivity-setting{grid-template-columns:1fr}.productivity-setting input,.productivity-setting select,.productivity-settings button{min-height:42px}.productivity-controls{align-items:stretch}.productivity-controls input{max-width:43%}#task-productivity{padding:0 .6rem}.productivity-table th,.productivity-table td{padding:.5rem .3rem}}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
const app = document.getElementById('contacts-app'); if (!app) return;
|
||||||
|
const ja = document.documentElement.lang.startsWith('ja'), t = (en, jp) => ja ? jp : en;
|
||||||
|
const api = '/_/api/v1/extension/organizer.contacts/', editor = document.getElementById('contact-editor');
|
||||||
|
const el = (tag, text) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; return n; };
|
||||||
|
const exportLink = el('a', t('Export address book', 'アドレス帳を書き出す')); exportLink.href = api + 'export.vcf';
|
||||||
|
document.getElementById('contacts-controls').append(exportLink);
|
||||||
|
async function request(path, options = {}) {
|
||||||
|
const r = await fetch(api + path, { credentials: 'same-origin', signal: AbortSignal.timeout(15000), ...options, headers: { 'Content-Type': 'application/json', ...options.headers } });
|
||||||
|
const data = await r.json().catch(() => ({}));
|
||||||
|
if (!r.ok || r.redirected) throw Error(r.status === 412 ? t('Changed elsewhere. Reload before restoring.', '他で変更されています。再読込してから復元してください。') : t('Unable to load/restore. Check login and permissions.', '読込・復元できません。ログインと権限を確認してください。'));
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
function attach() {
|
||||||
|
const form = editor.querySelector('form'), link = form?.querySelector('a[href$=".vcf"]');
|
||||||
|
if (!link || form.dataset.historyAttached) return; form.dataset.historyAttached = 'true';
|
||||||
|
const id = new URL(link.href).pathname.split('/').pop().slice(0, -4);
|
||||||
|
const details = el('details'); details.className = 'contact-history';
|
||||||
|
details.append(el('summary', t('Revision history', '変更履歴')));
|
||||||
|
const status = el('p'); status.role = 'status'; const rows = el('div'), preview = el('pre'); details.append(status, rows, preview); editor.append(details);
|
||||||
|
let opened = false, busy = false, version = 0;
|
||||||
|
async function load(before = '') {
|
||||||
|
if (busy) return; busy = true;
|
||||||
|
try {
|
||||||
|
if (!version) version = (await request('items/' + id)).item.version;
|
||||||
|
const data = await request('items/' + id + '/history' + (before ? '?before=' + before : ''));
|
||||||
|
if (!details.isConnected) return;
|
||||||
|
rows.querySelector('[data-more]')?.remove();
|
||||||
|
for (const revision of data.items) {
|
||||||
|
const row = el('div'); row.className = 'contact-history-row';
|
||||||
|
row.append(el('span', '#' + revision.version + ' · ' + new Date(revision.created_ms).toLocaleString() + (revision.deleted ? t(' · deleted', ' · 削除') : '')));
|
||||||
|
const view = el('button', t('Preview', '確認')); view.type = 'button';
|
||||||
|
view.onclick = async () => { try { const d = await request('items/' + id + '/history/' + revision.version); if (details.isConnected) preview.textContent = d.item.vcard; } catch (e) { status.textContent = e.message; } };
|
||||||
|
row.append(view);
|
||||||
|
if (app.dataset.writable === 'true') {
|
||||||
|
const restore = el('button', t('Restore', '復元')); restore.type = 'button';
|
||||||
|
restore.onclick = async () => {
|
||||||
|
if (busy || !confirm(t('Restore this revision as a new version? Unsaved form edits will be discarded. The contact will be active.', 'この履歴を新しい版として復元しますか?フォームの未保存変更は破棄し、連絡先を有効な状態に戻します。'))) return;
|
||||||
|
busy = true; restore.disabled = true;
|
||||||
|
try { const d = await request('items/' + id + '/restore', { method: 'POST', headers: { 'If-Match': '"' + version + '"' }, body: JSON.stringify({ version, revision: revision.version }) }); if (details.isConnected) app.dispatchEvent(new CustomEvent('contact-restored', { detail: d.item })); }
|
||||||
|
catch (e) { status.textContent = e.message; } finally { busy = false; restore.disabled = false; }
|
||||||
|
};
|
||||||
|
row.append(restore);
|
||||||
|
}
|
||||||
|
rows.append(row);
|
||||||
|
}
|
||||||
|
if (data.next) { const more = el('button', t('Earlier revisions', '以前の履歴')); more.type = 'button'; more.dataset.more = 'true'; more.onclick = () => load(data.next); rows.append(more); }
|
||||||
|
} catch (e) { status.textContent = e.message; opened = false; } finally { busy = false; }
|
||||||
|
}
|
||||||
|
details.ontoggle = () => { if (details.open && !opened) { opened = true; load(); } };
|
||||||
|
}
|
||||||
|
new MutationObserver(attach).observe(editor, { childList: true }); attach();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
(()=>{'use strict';const app=document.getElementById('contacts-app');if(!app)return;const ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en,api='/_/api/v1/extension/organizer.contacts/',writable=app.dataset.writable==='true',status=document.getElementById('contacts-status'),list=document.getElementById('contacts-list'),editor=document.getElementById('contact-editor'),controls=document.getElementById('contacts-controls');
|
||||||
|
const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;},button=(text,fn)=>{const b=el('button',text);b.type='button';b.onclick=fn;return b;};app.querySelector('h1').textContent=t('Private contacts','個人アドレス帳');app.querySelector('nav a').textContent=t('Tasks','タスク');app.querySelector('nav a+a').textContent=t('Settings','設定');
|
||||||
|
async function request(path,options={}){const r=await fetch(api+path,{credentials:'same-origin',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json',...options.headers}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(r.status===412?t('Changed or duplicate UID. Your input is retained.','競合または同じUIDの連絡先があります。入力は保持しています。'):t('Unable to save/load. Check your login, permissions and input.','保存・読込できません。ログイン、権限、入力を確認してください。'));return d;}
|
||||||
|
let dirty=false,busy=false,ticket=0;const search=el('input');search.type='search';search.placeholder=search.ariaLabel=t('Name, email, phone, organization','名前・メール・電話・所属');controls.append(search);const trash=el('select');trash.ariaLabel=t('Contacts or trash','連絡先・削除済み');for(const [value,label]of [['0',t('Contacts','連絡先')],['1',t('Deleted contacts','削除済み')]]){const o=el('option',label);o.value=value;trash.append(o);}controls.append(trash);trash.onchange=()=>load();const allowLeave=()=>!dirty||confirm(t('Discard unsaved edits?','未保存の変更を破棄しますか?'));
|
||||||
|
function show(c){dirty=false;editor.replaceChildren();const form=el('form'),inputs={};for(const [key,label,multi] of [['name',t('Name','名前'),false],['emails',t('Emails (one per line)','メール(1行1件)'),true],['phones',t('Phones (one per line)','電話(1行1件)'),true],['organization',t('Organization','所属'),false],['notes',t('Notes','メモ'),true]]){const l=el('label',label),n=el(multi?'textarea':'input');n.value=Array.isArray(c[key])?c[key].join('\n'):c[key]||'';n.disabled=!writable;n.name=key;if(key==='name'){n.required=true;n.maxLength=300;}l.append(n);form.append(l);inputs[key]=n;n.oninput=()=>{dirty=true;};}
|
||||||
|
const actions=el('div'),save=el('button',t('Save','保存'));save.type='submit';save.disabled=!writable;actions.append(save);if(c.version){const a=el('a',t('Export vCard','vCardを書き出す'));a.href=api+'items/'+c.uuid+'.vcf';actions.append(' ',a);const remove=button(c.deleted?t('Restore','復元'):t('Delete','削除'),async()=>{if(busy||!confirm(c.deleted?t('Restore this contact?','この連絡先を復元しますか?'):t('Delete this contact?','この連絡先を削除しますか?')))return;busy=true;try{await request('items/'+c.uuid,{method:'PUT',headers:{'If-Match':'"'+c.version+'"'},body:JSON.stringify({...c,deleted:!c.deleted})});dirty=false;editor.replaceChildren();await load();}catch(e){status.textContent=e.message;}finally{busy=false;}});remove.disabled=!writable;actions.append(' ',remove);}
|
||||||
|
form.append(actions);form.onsubmit=async e=>{e.preventDefault();if(busy)return;const draft={...c};for(const key of Object.keys(inputs))draft[key]=['emails','phones'].includes(key)?inputs[key].value.split('\n').map(v=>v.trim()).filter(Boolean):inputs[key].value;busy=true;save.disabled=true;try{const d=await request('items'+(c.version?'/'+c.uuid:''),{method:c.version?'PUT':'POST',headers:c.version?{'If-Match':'"'+c.version+'"'}:{},body:JSON.stringify(draft)});show(d.item);status.textContent=t('Saved','保存しました');await load();}catch(e){status.textContent=e.message;}finally{busy=false;save.disabled=!writable;}};editor.append(form);if(c.vcard){const d=el('details'),summary=el('summary',t('Original vCard (unsupported properties are retained)','vCard(未対応プロパティも保持)'));d.append(summary,el('pre',c.vcard));editor.append(d);}inputs.name.focus();}
|
||||||
|
async function load(after='',append=false){const id=++ticket;try{const d=await request('items?'+new URLSearchParams({q:search.value,after,deleted:trash.value}));if(id!==ticket)return;if(!append)list.replaceChildren();list.querySelector('[data-more]')?.remove();for(const c of d.items){const b=button(c.name+' · '+(c.emails[0]||c.organization||''),async()=>{if(!allowLeave())return;try{const d=await request('items/'+c.uuid);show(d.item);}catch(e){status.textContent=e.message;}});list.append(b);}if(d.next){const b=button(t('More','続き'),()=>load(d.next,true));b.dataset.more='true';list.append(b);}if(!list.children.length)list.append(el('p',t('No contacts','連絡先がありません')));}catch(e){status.textContent=e.message;}}
|
||||||
|
let timer;search.oninput=()=>{clearTimeout(timer);timer=setTimeout(()=>load(),200);};if(writable){controls.append(button(t('New contact','連絡先を追加'),()=>{if(allowLeave())show({uuid:crypto.randomUUID(),version:0,emails:[],phones:[],deleted:false});}));const file=el('input');file.type='file';file.accept='.vcf,text/vcard';file.hidden=true;controls.append(button(t('Import vCard','vCardを取り込む'),()=>file.click()),file);file.onchange=async()=>{const f=file.files[0];if(!f)return;try{if(f.size>2*1024*1024)throw Error(t('Maximum 2 MiB','上限は2 MiBです'));const text=await f.text();const cards=text.match(/BEGIN:VCARD\r?\n[\s\S]*?END:VCARD(?:\r?\n|$)/g)||[];if(!cards.length||cards.length>200||text.replace(/BEGIN:VCARD\r?\n[\s\S]*?END:VCARD(?:\r?\n|$)/g,'').trim())throw Error(t('Expected up to 200 UTF-8 vCards (3.0/4.0).','UTF-8のvCard 3.0/4.0(最大200件)を指定してください。'));if(!confirm(t('Import contacts: ','連絡先を取り込みます:')+cards.length+'\n'+t('Existing identical UID/content is skipped. Conflicts are not overwritten.','同一UID・内容は重複登録しません。競合は上書きせず報告します。')))return;let success=0,failed=[];for(let i=0;i<cards.length;i++){try{await request('import',{method:'POST',headers:{'Content-Type':'text/vcard'},body:cards[i]});success++;}catch(e){failed.push(i+1);}}status.textContent=t('Imported/existing: ','取り込み済み・既存:')+success+(failed.length?t(' / Failed card numbers: ',' / 失敗したカード番号:')+failed.join(', '):'');await load();}catch(e){status.textContent=e.message;}finally{file.value='';}};}
|
||||||
|
app.addEventListener('contact-restored',e=>{show(e.detail);load();status.textContent=t('Revision restored as a new version','履歴を新しい版として復元しました');});window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}});load();})();
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
(function(root){'use strict';function parse(input){
|
||||||
|
const tokens=[];let value='',quote='',escaped=false,started=false;
|
||||||
|
for(const ch of input.trim()){if(escaped){value+=ch;escaped=false;started=true;continue;}if(ch==='\\'){escaped=true;continue;}if(quote){if(ch===quote)quote='';else value+=ch;continue;}if(ch==='"'||ch==="'"){quote=ch;started=true;continue;}if(/\s/.test(ch)){if(started){tokens.push(value);value='';started=false;}}else{value+=ch;started=true;}}
|
||||||
|
if(quote||escaped)throw Error('Unclosed quote / 引用符を閉じてください');if(started)tokens.push(value);
|
||||||
|
if(tokens[0]?.toLowerCase()!=='add'||!['task','cal'].includes(tokens[1]?.toLowerCase()))throw Error('add task / add cal');
|
||||||
|
const kind=tokens[1].toLowerCase(),options={},title=[],allowed=kind==='task'?['project','cost','due','start','review','planned','complexity']:['calendar','from','to'];
|
||||||
|
for(const token of tokens.slice(2)){const m=token.match(/^([a-z]+):(.*)$/i);if(!m){title.push(token);continue;}const key=m[1].toLowerCase();if(!allowed.includes(key)||Object.hasOwn(options,key)||!m[2])throw Error('Invalid option / オプションを確認:'+key);options[key]=m[2];}
|
||||||
|
if(!title.join(' ').trim())throw Error('Title required / 件名を入力してください');
|
||||||
|
if(options.cost){const m=options.cost.match(/^(\d+(?:\.\d+)?)(h|m)$/);if(!m)throw Error('cost:2h / cost:30m');options.estimate_minutes=Number(m[1])*(m[2]==='h'?60:1);if(!Number.isInteger(options.estimate_minutes)||options.estimate_minutes>10080)throw Error('Invalid cost / 工数を確認してください');}
|
||||||
|
for(const k of ['due','start','review','planned'])if(options[k]&&!/^\d{4}-\d{2}-\d{2}$/.test(options[k]))throw Error(k+':YYYY-MM-DD');
|
||||||
|
if(options.complexity&&!/^[1-5]$/.test(options.complexity))throw Error('complexity:1–5');
|
||||||
|
if(kind==='cal'&&(!options.from||!options.to))throw Error('from:YYYY-MM-DDTHH:mm to:YYYY-MM-DDTHH:mm');
|
||||||
|
return {kind,title:title.join(' '),options};
|
||||||
|
}root.PagesWikiHomeCommand={parse};if(typeof module!=='undefined')module.exports={parse};})(globalThis);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
const {test}=require('node:test');const assert=require('node:assert/strict');const {parse}=require('./home-command-parser.js');
|
||||||
|
test('commands preserve quoted project and title',()=>{const c=parse('add task "調査を進める" project:"開発 計画" cost:2h due:2026-11-02');assert.equal(c.title,'調査を進める');assert.equal(c.options.project,'開発 計画');assert.equal(c.options.estimate_minutes,120);});
|
||||||
|
test('calendar and malformed input',()=>{assert.equal(parse('add cal 会議 from:2026-11-02T09:00 to:2026-11-02T10:00').kind,'cal');for(const v of ['add task','add task x cost:0.001h','add task x foo:z','add task x project:a project:b','add task "x','add cal x'])assert.throws(()=>parse(v));});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
(()=>{'use strict';const input=document.querySelector('[data-home-type-search]'),parser=window.PagesWikiHomeCommand;if(!input||!parser)return;const form=input.closest('form'),ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en,api='/_/api/v1/extension/organizer.tasks/',box=document.createElement('section');box.className='home-command-panel';box.hidden=true;box.style.cssText='position:relative;z-index:30;padding:.7rem;border-radius:.5rem;background:var(--bg-color,var(--bg,#222));color:var(--text-color,var(--fg,#eee));text-align:start';form.after(box);let busy=false,sequence=0,timer,prepared=null;
|
||||||
|
const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
|
||||||
|
async function request(path,options={}){const r=await fetch(api+path,{credentials:'same-origin',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json'}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t('Check login, permissions, dates and current task settings. Input is retained.','ログイン、権限、日時、タスク設定を確認してください。入力は保持しています。'));return d;}
|
||||||
|
const matches=()=>/^add\s+(task|cal)\b/i.test(input.value.trim());
|
||||||
|
async function resolve(kind,name){const d=await request(kind==='project'?'items?'+new URLSearchParams({kind:'project',view:'all',q:name,limit:100}):'calendars'),items=d.items.filter(c=>kind==='project'?c.title===name||c.uuid===name:c.name===name||c.pretty_name===name||c.id===name||!name);if(items.length!==1||d.next)throw Error(t('Select a unique '+kind+' (name or UUID).',kind==='project'?'プロジェクトを名前またはUUIDで一意に指定してください。':'カレンダーを指定してください(calendar:名前)。'));return kind==='project'?items[0].uuid:items[0].id;}
|
||||||
|
async function suggestions(){const id=++sequence;if(!matches()){box.hidden=true;return;}box.hidden=false;box.replaceChildren(el('small',t('Enter: review → Create. Dates use the Domain timezone.','Enterで確認 → 作成。日時はドメインのタイムゾーンです。')));const m=input.value.match(/\b(project|calendar):([^\s"]*)$/i);if(!m)return;try{const kind=m[1].toLowerCase(),d=await request(kind==='project'?'items?'+new URLSearchParams({kind:'project',view:'all',q:m[2],limit:20}):'calendars');if(id!==sequence||!matches())return;for(const c of d.items.filter(c=>kind==='project'||c.name.toLowerCase().includes(m[2].toLowerCase())).slice(0,8)){const b=el('button',kind==='project'?c.title:c.name);b.type='button';b.style.display='block';b.onclick=()=>{const name=kind==='project'?c.title:c.pretty_name;input.value=input.value.slice(0,m.index)+kind+':'+JSON.stringify(name)+' ';input.focus();prepared=null;sequence++;box.replaceChildren();};box.append(b);}}catch(e){if(id===sequence)box.append(el('p',e.message));}}
|
||||||
|
input.addEventListener('input',()=>{prepared=null;sequence++;clearTimeout(timer);timer=setTimeout(suggestions,180);});input.addEventListener('keydown',e=>{if(matches()&&e.key==='Escape'){box.hidden=true;sequence++;}});
|
||||||
|
form.addEventListener('submit',async e=>{if(!matches())return;e.preventDefault();e.stopImmediatePropagation();if(busy)return;clearTimeout(timer);sequence++;busy=true;const source=input.value;box.hidden=false;box.replaceChildren();try{const cmd=parser.parse(source),o=cmd.options;let path,payload;
|
||||||
|
if(prepared?.source===source){({path,payload}=prepared);}else if(cmd.kind==='task'){path='capture';payload={request_id:crypto.randomUUID(),title:cmd.title};if(o.project)payload.project_uuid=await resolve('project',o.project);for(const [a,b]of [['due','due_on'],['start','start_on'],['planned','planned_on'],['review','review_on'],['estimate_minutes','estimate_minutes']])if(o[a]!==undefined)payload[b]=o[a];if(o.complexity)payload.complexity=Number(o.complexity);}else{path='calendar-capture';payload={request_id:crypto.randomUUID(),title:cmd.title,calendar_uuid:await resolve('calendar',o.calendar||''),from:o.from,to:o.to};}
|
||||||
|
if(source!==input.value)return;prepared={source,path,payload};box.append(el('strong',cmd.title),el('pre',Object.entries(o).map(([k,v])=>k+': '+v).join('\n')));const create=el('button',t('Create','作成')),cancel=el('button',t('Cancel','キャンセル'));create.type=cancel.type='button';cancel.onclick=()=>{box.hidden=true;};create.onclick=async()=>{if(busy)return;busy=true;create.disabled=true;cancel.disabled=true;input.disabled=true;try{const d=await request(path,{method:'POST',body:JSON.stringify(payload)});prepared=null;box.replaceChildren();const link=el('a',t('Created → Open','作成しました → 開く'));link.href=path==='capture'?'/v/plan/task/'+d.item.uuid:'/v/plan/event/'+encodeURIComponent(d.uid)+'?calendar='+encodeURIComponent(d.calendar);box.append(link);input.value='';}catch(err){box.append(el('p',err.message));}finally{busy=false;create.disabled=false;cancel.disabled=false;input.disabled=false;}};box.append(create,cancel);
|
||||||
|
}catch(err){box.append(el('p',err.message));}finally{busy=false;}},true);
|
||||||
|
})();
|
||||||
@@ -105,6 +105,7 @@
|
|||||||
candidates = [];
|
candidates = [];
|
||||||
close();
|
close();
|
||||||
const query = input.value.trim();
|
const query = input.value.trim();
|
||||||
|
if (/^add\s+(task|cal)\b/i.test(query)) return;
|
||||||
if ([...query].length < 2) return;
|
if ([...query].length < 2) return;
|
||||||
timer = setTimeout(() => request(query), 140);
|
timer = setTimeout(() => request(query), 140);
|
||||||
});
|
});
|
||||||
@@ -114,6 +115,7 @@
|
|||||||
else if (event.key === 'Escape') { event.preventDefault(); close(); }
|
else if (event.key === 'Escape') { event.preventDefault(); close(); }
|
||||||
});
|
});
|
||||||
form.addEventListener('submit', event => {
|
form.addEventListener('submit', event => {
|
||||||
|
if (/^add\s+(task|cal)\b/i.test(input.value.trim())) return;
|
||||||
if (event.ctrlKey || event.metaKey) return;
|
if (event.ctrlKey || event.metaKey) return;
|
||||||
const options = rows();
|
const options = rows();
|
||||||
let selected = active >= 0 ? options[active] : null;
|
let selected = active >= 0 ? options[active] : null;
|
||||||
|
|||||||
@@ -1,28 +1,31 @@
|
|||||||
(() => {
|
(() => {
|
||||||
'use strict';
|
'use strict';
|
||||||
const app = document.getElementById('tasks-app') || document.getElementById('calendar-app');
|
const app = document.getElementById('tasks-app') || document.getElementById('calendar-app') || document.getElementById('contacts-app');
|
||||||
if (!app) return;
|
if (!app) return;
|
||||||
const calendar = app.id === 'calendar-app';
|
const calendar = app.id === 'calendar-app';
|
||||||
|
const contacts = app.id === 'contacts-app';
|
||||||
if (calendar && !app.dataset.actor) return;
|
if (calendar && !app.dataset.actor) return;
|
||||||
const ja = document.documentElement.lang.startsWith('ja');
|
const ja = document.documentElement.lang.startsWith('ja');
|
||||||
const t = (en, jp) => ja ? jp : en;
|
const t = (en, jp) => ja ? jp : en;
|
||||||
const api = '/_/api/v1/caldav-credentials';
|
const api = '/_/api/v1/caldav-credentials';
|
||||||
const el = (tag, text) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; return n; };
|
const el = (tag, text) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; return n; };
|
||||||
const button = el('button', '⇄'); button.type = 'button'; button.id = 'tasks-dav-open';
|
const button = el('button', '⇄'); button.type = 'button'; button.id = 'tasks-dav-open';
|
||||||
button.title = button.ariaLabel = t('CalDAV / CLI access', 'CalDAV / CLI連携');
|
button.title = button.ariaLabel = contacts ? t('CardDAV access', 'CardDAV連携') : t('CalDAV / CLI access', 'CalDAV / CLI連携');
|
||||||
app.querySelector(calendar ? '.calendar-toolbar' : '.tasks-toolbar .tasks-actions').append(button);
|
app.querySelector(contacts ? '#contacts-controls' : calendar ? '.calendar-toolbar' : '.tasks-toolbar .tasks-actions').append(button);
|
||||||
const dialog = el('dialog'); dialog.id = 'tasks-dav-dialog'; dialog.setAttribute('aria-labelledby', 'tasks-dav-title');
|
const dialog = el('dialog'); dialog.id = 'tasks-dav-dialog'; dialog.setAttribute('aria-labelledby', 'tasks-dav-title');
|
||||||
const header = el('header'); header.className = 'tasks-toolbar';
|
const header = el('header'); header.className = 'tasks-toolbar';
|
||||||
const title = el('h2', t('CalDAV access', '予定・タスクのCalDAV連携')); title.id = 'tasks-dav-title';
|
const title = el('h2', t('CalDAV access', '予定・タスクのCalDAV連携')); title.id = 'tasks-dav-title';
|
||||||
|
if (contacts) title.textContent = t('CardDAV access', '連絡先のCardDAV連携');
|
||||||
const close = el('button', '×'); close.type = 'button'; close.ariaLabel = t('Close', '閉じる'); header.append(title, close);
|
const close = el('button', '×'); close.type = 'button'; close.ariaLabel = t('Close', '閉じる'); header.append(title, close);
|
||||||
const help = el('p', t('Choose calendars, tasks, or both. Calendar permissions still apply. Existing task passwords remain task-only. Wiki access is not granted. Use HTTPS.', '予定・タスクの対象を選んで発行します。予定には既存のカレンダー権限が適用されます。従来のパスワードはタスク専用のままです。Wikiへのアクセス権は付与されません。HTTPSで接続してください。'));
|
const help = el('p', t('Choose calendars, tasks, or both. Calendar permissions still apply. Existing task passwords remain task-only. Wiki access is not granted. Use HTTPS.', '予定・タスクの対象を選んで発行します。予定には既存のカレンダー権限が適用されます。従来のパスワードはタスク専用のままです。Wikiへのアクセス権は付与されません。HTTPSで接続してください。'));
|
||||||
const url = el('input'); url.readOnly = true; url.value = location.origin + '/_/api/v1/caldav/'; url.ariaLabel = 'CalDAV URL'; url.onclick = () => url.select();
|
const url = el('input'); url.readOnly = true; url.value = location.origin + '/_/api/v1/caldav/'; url.ariaLabel = 'CalDAV URL'; url.onclick = () => url.select();
|
||||||
|
if (contacts) { url.value = location.origin + '/_/api/v1/carddav/'; url.ariaLabel = 'CardDAV URL'; help.textContent = t('Private address book access only. Issue a separate password for each device. Existing CalDAV passwords cannot access contacts. Use HTTPS.', '個人アドレス帳専用です。端末ごとにパスワードを発行してください。既存のCalDAVパスワードでは連絡先へアクセスできません。HTTPSで接続してください。'); }
|
||||||
const form = el('form'); const label = el('input'); label.required = true; label.maxLength = 100; label.placeholder = t('Device / client name', '端末・クライアント名'); label.ariaLabel = label.placeholder;
|
const form = el('form'); const label = el('input'); label.required = true; label.maxLength = 100; label.placeholder = t('Device / client name', '端末・クライアント名'); label.ariaLabel = label.placeholder;
|
||||||
const access = el('select'); access.ariaLabel = t('Access', 'アクセス権限');
|
const access = el('select'); access.ariaLabel = t('Access', 'アクセス権限');
|
||||||
for (const [value, text] of [['read', t('Read only', '読み取り専用')], ['write', t('Read / write', '読み書き')]]) { const option = el('option', text); option.value = value; if (value === 'write' && !calendar && app.dataset.writable !== 'true') option.disabled = true; access.append(option); }
|
for (const [value, text] of [['read', t('Read only', '読み取り専用')], ['write', t('Read / write', '読み書き')]]) { const option = el('option', text); option.value = value; if (value === 'write' && !calendar && app.dataset.writable !== 'true') option.disabled = true; access.append(option); }
|
||||||
const scope = el('select'); scope.ariaLabel = t('Scope', '対象');
|
const scope = el('select'); scope.ariaLabel = t('Scope', '対象');
|
||||||
const scopes = { tasks: t('Tasks only', 'タスクのみ'), calendar: t('Calendars only', '予定のみ'), all: t('Calendars and tasks', '予定とタスク') };
|
const scopes = { tasks: t('Tasks only', 'タスクのみ'), calendar: t('Calendars only', '予定のみ'), all: t('Calendars and tasks', '予定とタスク'), contacts: t('Contacts only', '連絡先のみ') };
|
||||||
for (const [value, text] of Object.entries(scopes)) { const option = el('option', text); option.value = value; option.selected = value === (calendar ? 'calendar' : 'tasks'); scope.append(option); }
|
for (const [value, text] of Object.entries(scopes)) { if (contacts && value !== 'contacts') continue; const option = el('option', text); option.value = value; option.selected = value === (contacts ? 'contacts' : calendar ? 'calendar' : 'tasks'); scope.append(option); }
|
||||||
const days = el('select'); days.ariaLabel = t('Validity', '有効期間');
|
const days = el('select'); days.ariaLabel = t('Validity', '有効期間');
|
||||||
for (const n of [30, 90, 365]) { const option = el('option', n + t(' days', '日間')); option.value = String(n); option.selected = n === 90; days.append(option); }
|
for (const n of [30, 90, 365]) { const option = el('option', n + t(' days', '日間')); option.value = String(n); option.selected = n === 90; days.append(option); }
|
||||||
const issue = el('button', t('Issue password', 'パスワードを発行')); issue.type = 'submit'; form.append(label, scope, access, days, issue);
|
const issue = el('button', t('Issue password', 'パスワードを発行')); issue.type = 'submit'; form.append(label, scope, access, days, issue);
|
||||||
@@ -31,10 +34,13 @@
|
|||||||
compatLabel.append(compat, document.createTextNode(t('OneTask compatibility (calendar-access advertisement)', 'OneTask互換モード(calendar-accessを宣言)')));
|
compatLabel.append(compat, document.createTextNode(t('OneTask compatibility (calendar-access advertisement)', 'OneTask互換モード(calendar-accessを宣言)')));
|
||||||
const compatHelp = el('p', t('Opt in only for clients that require calendar-access. This is a limited implementation, not full RFC compliance. Task dates are date-only; recurrence, timezone definitions and alarms remain unsupported. Enabling this does not grant additional access.', 'calendar-accessを要求するクライアント向けの互換設定です。完全なRFC準拠ではありません。タスクの日付は日単位のみで、繰り返し・タイムゾーン定義・アラームは引き続き未対応です。アクセス権限は増えません。'));
|
const compatHelp = el('p', t('Opt in only for clients that require calendar-access. This is a limited implementation, not full RFC compliance. Task dates are date-only; recurrence, timezone definitions and alarms remain unsupported. Enabling this does not grant additional access.', 'calendar-accessを要求するクライアント向けの互換設定です。完全なRFC準拠ではありません。タスクの日付は日単位のみで、繰り返し・タイムゾーン定義・アラームは引き続き未対応です。アクセス権限は増えません。'));
|
||||||
compatHelp.id = 'tasks-dav-compat-help'; compatHelp.className = 'dav-compat-help'; form.append(compatLabel, compatHelp);
|
compatHelp.id = 'tasks-dav-compat-help'; compatHelp.className = 'dav-compat-help'; form.append(compatLabel, compatHelp);
|
||||||
|
const updateScope = () => { const card = scope.value === 'contacts'; compatLabel.hidden = compatHelp.hidden = card; if (card) compat.checked = false; url.value = location.origin + (card ? '/_/api/v1/carddav/' : '/_/api/v1/caldav/'); };
|
||||||
|
scope.onchange = updateScope; updateScope();
|
||||||
const secret = el('section'); secret.hidden = true;
|
const secret = el('section'); secret.hidden = true;
|
||||||
const status = el('p'); status.role = 'status';
|
const status = el('p'); status.role = 'status';
|
||||||
const tableWrap = el('div'); tableWrap.className = 'task-dav-table'; const table = el('table'); tableWrap.append(table);
|
const tableWrap = el('div'); tableWrap.className = 'task-dav-table'; const table = el('table'); tableWrap.append(table);
|
||||||
const note = el('p', t('Clients: chroncal, vdirsyncer + Todoman. Task start/due accept dates only. Recurring events and alarms cannot be created via DAV. Calendar events are deleted; tasks are archived.', '連携例:chroncal、vdirsyncer + Todoman。タスクの開始・期限は日付のみ対応。DAV経由の繰り返し予定・アラームの新規作成は未対応です。削除操作では予定は削除、タスクはアーカイブされます。'));
|
const note = el('p', t('Clients: chroncal, vdirsyncer + Todoman. Task start/due accept dates only. Recurring events and alarms cannot be created via DAV. Calendar events are deleted; tasks are archived.', '連携例:chroncal、vdirsyncer + Todoman。タスクの開始・期限は日付のみ対応。DAV経由の繰り返し予定・アラームの新規作成は未対応です。削除操作では予定は削除、タスクはアーカイブされます。'));
|
||||||
|
if (contacts) note.textContent = t('Use the credential ID as the username, not your account name. Deletes go to trash. Changes use ETags; stale edits are rejected. Shared books and remote-source connectors are not available.', 'ユーザー名にはアカウント名ではなく認証情報IDを使います。削除した連絡先は削除済み一覧から復元できます。ETagで競合を検知し、古い編集内容は上書きしません。共有アドレス帳・外部サービス取り込みは未対応です。');
|
||||||
dialog.append(header, help, url, form, secret, status, tableWrap, note); app.append(dialog);
|
dialog.append(header, help, url, form, secret, status, tableWrap, note); app.append(dialog);
|
||||||
let busy = false, generation = 0;
|
let busy = false, generation = 0;
|
||||||
async function request(path = '', options = {}) {
|
async function request(path = '', options = {}) {
|
||||||
@@ -48,6 +54,7 @@
|
|||||||
table.replaceChildren(); const head = el('tr');
|
table.replaceChildren(); const head = el('tr');
|
||||||
[t('Name', '名称'), t('Scope', '対象'), t('Access', '権限'), t('Expires', '有効期限'), ''].forEach(v => head.append(el('th', v))); const thead = el('thead'); thead.append(head); table.append(thead); const body = el('tbody'); table.append(body);
|
[t('Name', '名称'), t('Scope', '対象'), t('Access', '権限'), t('Expires', '有効期限'), ''].forEach(v => head.append(el('th', v))); const thead = el('thead'); thead.append(head); table.append(thead); const body = el('tbody'); table.append(body);
|
||||||
for (const c of data.items) {
|
for (const c of data.items) {
|
||||||
|
if (contacts && c.scope !== 'contacts') continue;
|
||||||
const row = el('tr'); row.append(el('td', c.label + (c.calendar_access_compat ? t(' · OneTask compatibility', ' · OneTask互換') : '')), el('td', scopes[c.scope || 'tasks']), el('td', c.write ? t('Read / write', '読み書き') : t('Read only', '読み取り専用')), el('td', new Date(c.expires_ms).toLocaleString()));
|
const row = el('tr'); row.append(el('td', c.label + (c.calendar_access_compat ? t(' · OneTask compatibility', ' · OneTask互換') : '')), el('td', scopes[c.scope || 'tasks']), el('td', c.write ? t('Read / write', '読み書き') : t('Read only', '読み取り専用')), el('td', new Date(c.expires_ms).toLocaleString()));
|
||||||
const cell = el('td'), revoke = el('button', t('Revoke', '失効')); revoke.type = 'button';
|
const cell = el('td'), revoke = el('button', t('Revoke', '失効')); revoke.type = 'button';
|
||||||
revoke.onclick = async () => { if (busy || !confirm(t('Revoke this password?', 'このパスワードを失効させますか?'))) return; busy = true; revoke.disabled = true; status.textContent = ''; try { await request('/' + encodeURIComponent(c.id), { method: 'DELETE' }); await load(); } catch (e) { status.textContent = e.message; } finally { busy = false; revoke.disabled = false; } };
|
revoke.onclick = async () => { if (busy || !confirm(t('Revoke this password?', 'このパスワードを失効させますか?'))) return; busy = true; revoke.disabled = true; status.textContent = ''; try { await request('/' + encodeURIComponent(c.id), { method: 'DELETE' }); await load(); } catch (e) { status.textContent = e.message; } finally { busy = false; revoke.disabled = false; } };
|
||||||
@@ -61,6 +68,7 @@
|
|||||||
e.preventDefault(); if (busy) return; busy = true; issue.disabled = true; status.textContent = '';
|
e.preventDefault(); if (busy) return; busy = true; issue.disabled = true; status.textContent = '';
|
||||||
try {
|
try {
|
||||||
const data = await request('', { method: 'POST', body: JSON.stringify({ label: label.value, scope: scope.value, write: access.value === 'write', days: Number(days.value), calendar_access_compat: compat.checked }) });
|
const data = await request('', { method: 'POST', body: JSON.stringify({ label: label.value, scope: scope.value, write: access.value === 'write', days: Number(days.value), calendar_access_compat: compat.checked }) });
|
||||||
|
url.value = location.origin + data.url;
|
||||||
secret.replaceChildren(el('p', t('Shown only once. Save both values in your password manager before closing.', 'この画面を閉じると再表示できません。両方をパスワードマネージャーなどに保存してください。')));
|
secret.replaceChildren(el('p', t('Shown only once. Save both values in your password manager before closing.', 'この画面を閉じると再表示できません。両方をパスワードマネージャーなどに保存してください。')));
|
||||||
for (const [name, value] of [[t('Username (credential ID)', 'ユーザー名(認証情報ID)'), data.username], [t('Password', 'パスワード'), data.password]]) { const wrapper = el('label', name), field = el('input'); field.readOnly = true; field.value = value; field.autocomplete = 'off'; field.spellcheck = false; field.onclick = () => field.select(); wrapper.append(field); secret.append(wrapper); }
|
for (const [name, value] of [[t('Username (credential ID)', 'ユーザー名(認証情報ID)'), data.username], [t('Password', 'パスワード'), data.password]]) { const wrapper = el('label', name), field = el('input'); field.readOnly = true; field.value = value; field.autocomplete = 'off'; field.spellcheck = false; field.onclick = () => field.select(); wrapper.append(field); secret.append(wrapper); }
|
||||||
secret.hidden = false; label.value = ''; await load();
|
secret.hidden = false; label.value = ''; await load();
|
||||||
|
|||||||
@@ -25,6 +25,7 @@
|
|||||||
function button(label,icon,fn){const b=el('button',icon);b.type='button';b.title=b.ariaLabel=label;b.addEventListener('click',fn);actions.append(b);return b;}
|
function button(label,icon,fn){const b=el('button',icon);b.type='button';b.title=b.ariaLabel=label;b.addEventListener('click',fn);actions.append(b);return b;}
|
||||||
const detail=el('a','⋯');detail.title=detail.ariaLabel=t('Details','詳細');detail.href='/v/plan/task/'+item.uuid;detail.dataset.action='detail';if(options.onDetail)detail.addEventListener('click',e=>{if(e.ctrlKey||e.metaKey||e.shiftKey||e.button)return;e.preventDefault();if(blocked())return;options.onDetail(item.uuid);});actions.append(detail);
|
const detail=el('a','⋯');detail.title=detail.ariaLabel=t('Details','詳細');detail.href='/v/plan/task/'+item.uuid;detail.dataset.action='detail';if(options.onDetail)detail.addEventListener('click',e=>{if(e.ctrlKey||e.metaKey||e.shiftKey||e.button)return;e.preventDefault();if(blocked())return;options.onDetail(item.uuid);});actions.append(detail);
|
||||||
function blocked(){if(saving||dirtyRows.has(row)){message(t('Save or reload this row first.','先にこの行の変更を保存するか再読込してください。'));return true;}return false;}
|
function blocked(){if(saving||dirtyRows.has(row)){message(t('Save or reload this row first.','先にこの行の変更を保存するか再読込してください。'));return true;}return false;}
|
||||||
|
if(writable&&!item.archived)button(t('Start work recording','作業時間を記録開始'),'▶',()=>{if(!blocked())document.getElementById('tasks-app')?.dispatchEvent(new CustomEvent('task-work',{detail:item}));}).dataset.action='work';
|
||||||
button(t('Calendar time blocks','カレンダーへ時間枠を追加'),'▦',async()=>{if(blocked())return;try{const d=await request(api+'/'+item.uuid);document.getElementById('tasks-app')?.dispatchEvent(new CustomEvent('task-plan',{detail:d.item}));}catch(e){message(e.message);}}).dataset.action='plan';
|
button(t('Calendar time blocks','カレンダーへ時間枠を追加'),'▦',async()=>{if(blocked())return;try{const d=await request(api+'/'+item.uuid);document.getElementById('tasks-app')?.dispatchEvent(new CustomEvent('task-plan',{detail:d.item}));}catch(e){message(e.message);}}).dataset.action='plan';
|
||||||
const reset=button(t('Reload row (discard edits)','行を再読込(編集を破棄)'),'↻',async()=>{if(saving)return;if(dirtyRows.has(row)&&!confirm(t('Discard changes in this row?','この行の変更を破棄しますか?')))return;try{const d=await request(api+'/'+item.uuid);item=d.item;draft={};dirtyRows.delete(row);Object.keys(inputs).forEach(k=>inputs[k].value=item[k]||'');paint();message('','idle');}catch(e){message(e.message);}});reset.dataset.action='reload';
|
const reset=button(t('Reload row (discard edits)','行を再読込(編集を破棄)'),'↻',async()=>{if(saving)return;if(dirtyRows.has(row)&&!confirm(t('Discard changes in this row?','この行の変更を破棄しますか?')))return;try{const d=await request(api+'/'+item.uuid);item=d.item;draft={};dirtyRows.delete(row);Object.keys(inputs).forEach(k=>inputs[k].value=item[k]||'');paint();message('','idle');}catch(e){message(e.message);}});reset.dataset.action='reload';
|
||||||
function buttonMore(cursor){const more=el('button',t('More subtasks','続きのサブタスク'));more.type='button';more.className='task-children-more';more.addEventListener('click',async()=>{if(dirtyRows.size)return;more.disabled=true;try{const d=await request(api+'?'+new URLSearchParams({view:'family',parent:item.uuid,limit:100,before:cursor}));if(dirtyRows.size)return;d.items.forEach(c=>more.before(create(c,{...options,initialChildren:[],context:false,nested:true})));if(d.next)more.replaceWith(buttonMore(d.next));else more.remove();}catch(e){message(e.message);}finally{more.disabled=false;}});return more;}
|
function buttonMore(cursor){const more=el('button',t('More subtasks','続きのサブタスク'));more.type='button';more.className='task-children-more';more.addEventListener('click',async()=>{if(dirtyRows.size)return;more.disabled=true;try{const d=await request(api+'?'+new URLSearchParams({view:'family',parent:item.uuid,limit:100,before:cursor}));if(dirtyRows.size)return;d.items.forEach(c=>more.before(create(c,{...options,initialChildren:[],context:false,nested:true})));if(d.next)more.replaceWith(buttonMore(d.next));else more.remove();}catch(e){message(e.message);}finally{more.disabled=false;}});return more;}
|
||||||
@@ -47,7 +48,7 @@
|
|||||||
if(options.initialChildren?.length){loadAll=button(t('Load all subtasks, including other dates','別の日付も含めてすべてのサブタスクを表示'),'⇊',loadChildren);loadAll.dataset.action='children-all';}
|
if(options.initialChildren?.length){loadAll=button(t('Load all subtasks, including other dates','別の日付も含めてすべてのサブタスクを表示'),'⇊',loadChildren);loadAll.dataset.action='children-all';}
|
||||||
if(writable&&!item.archived){const add=el('form',undefined,'task-child-capture'),input=el('input'),submit=el('button','+');input.required=true;input.maxLength=300;input.placeholder=input.ariaLabel=t('New subtask','サブタスクを追加');submit.type='submit';submit.title=t('Add subtask','サブタスクを追加');add.append(input,submit);add.hidden=true;row.append(add);button(t('Add subtask','サブタスクを追加'),'+',()=>{if(blocked())return;add.hidden=!add.hidden;if(!add.hidden)input.focus();}).dataset.action='add-child';
|
if(writable&&!item.archived){const add=el('form',undefined,'task-child-capture'),input=el('input'),submit=el('button','+');input.required=true;input.maxLength=300;input.placeholder=input.ariaLabel=t('New subtask','サブタスクを追加');submit.type='submit';submit.title=t('Add subtask','サブタスクを追加');add.append(input,submit);add.hidden=true;row.append(add);button(t('Add subtask','サブタスクを追加'),'+',()=>{if(blocked())return;add.hidden=!add.hidden;if(!add.hidden)input.focus();}).dataset.action='add-child';
|
||||||
input.addEventListener('input',()=>{if(input.value)dirtyRows.add(add);else dirtyRows.delete(add);});
|
input.addEventListener('input',()=>{if(input.value)dirtyRows.add(add);else dirtyRows.delete(add);});
|
||||||
add.addEventListener('submit',async e=>{e.preventDefault();if(submit.disabled||blocked())return;const title=input.value.trim();if(!title)return;submit.disabled=input.disabled=true;if(!childDraft||childDraft.title!==title)childDraft={uuid:crypto.randomUUID(),kind:'task',title,notes:'',parent_uuid:item.uuid,project_uuid:item.project_uuid,status:'todo',bucket:item.bucket,priority:item.priority,estimate_minutes:0,archived:false,version:0};try{const d=await request(api,{method:'POST',body:JSON.stringify(childDraft)});childDraft=null;childRequest++;input.value='';dirtyRows.delete(add);showChildren(true);children.querySelector('small')?.remove();children.append(create(d.item,{...options,initialChildren:[],context:false,nested:true}));document.getElementById('tasks-app')?.dispatchEvent(new Event('task-today-refresh'));}catch(err){message(err.message);}finally{submit.disabled=input.disabled=false;input.focus();}});
|
add.addEventListener('submit',async e=>{e.preventDefault();if(submit.disabled||blocked())return;const title=input.value.trim();if(!title)return;submit.disabled=input.disabled=true;try{if(!childDraft||childDraft.title!==title){const preferences=await request('/_/api/v1/extension/organizer.tasks/preferences');childDraft={...preferences.defaults,uuid:crypto.randomUUID(),kind:'task',title,notes:'',parent_uuid:item.uuid,project_uuid:item.project_uuid,status:'todo',bucket:item.bucket,priority:item.priority,archived:false,version:0};}const d=await request(api,{method:'POST',body:JSON.stringify(childDraft)});childDraft=null;childRequest++;input.value='';dirtyRows.delete(add);showChildren(true);children.querySelector('small')?.remove();children.append(create(d.item,{...options,initialChildren:[],context:false,nested:true}));document.getElementById('tasks-app')?.dispatchEvent(new Event('task-today-refresh'));}catch(err){message(err.message);}finally{submit.disabled=input.disabled=false;input.focus();}});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(options.context){row.dataset.context='true';const badge=el('small',t('Parent','親'),'task-context-badge');badge.title=t('Context only: this parent is outside the current filter.','親子関係を示すために表示しています。親自体は現在の条件の対象外です。');inputs.title.parentElement.append(badge);}
|
if(options.context){row.dataset.context='true';const badge=el('small',t('Parent','親'),'task-context-badge');badge.title=t('Context only: this parent is outside the current filter.','親子関係を示すために表示しています。親自体は現在の条件の対象外です。');inputs.title.parentElement.append(badge);}
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
const root=document.getElementById('task-productivity');if(!root)return;
|
||||||
|
const ja=document.documentElement.lang.startsWith('ja'), api='/_/api/v1/extension/organizer.tasks/';
|
||||||
|
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;};
|
||||||
|
const status=document.getElementById('productivity-status'),content=document.getElementById('productivity-content');
|
||||||
|
root.querySelectorAll('[data-word]').forEach(n=>n.textContent=t(n.dataset.word));root.querySelector('h1').textContent=t(root.dataset.view==='settings'?'settings':'report');
|
||||||
|
async function request(path,options={}){const r=await fetch(api+path,{credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(15000),...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;}
|
||||||
|
const error=e=>{status.textContent=e.message||t('error');};
|
||||||
|
async function settings(){
|
||||||
|
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');
|
||||||
|
for(const key of ['project_uuid','assignee_uuid','due_days','start_days','planned_days','review_days','estimate_minutes','complexity','digest_enabled','digest_time','timezone']){
|
||||||
|
const label=el('label',t(key));label.className='productivity-setting';const input=el(key==='project_uuid'?'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==='digest_enabled'){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=key==='digest_time'?'time':'text';
|
||||||
|
if(key!=='digest_enabled')input.value=p[key]??'';input.disabled=root.dataset.writable!=='true';fields[key]=input;label.append(input);form.append(label);
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
if(data.last_digest){const states={sent:['Sent','送信済み'],sending:['Sending / result pending','送信中・結果未確定'],uncertain:['Delivery uncertain (no automatic retry)','結果不明(自動再送なし)'],cancelled:['Cancelled','送信取消']};form.append(el('p',(ja?'直近の配信: ':'Latest delivery: ')+data.last_digest.day+' · '+(states[data.last_digest.state]||['Unknown','不明'])[ja?1:0]));}
|
||||||
|
const save=el('button',t('save'));save.type='submit';save.disabled=root.dataset.writable!=='true';form.append(save);content.replaceChildren(form);
|
||||||
|
form.onsubmit=async event=>{event.preventDefault();if(!form.reportValidity())return;save.disabled=true;const value={...p};for(const [key,input] of Object.entries(fields)){value[key]=key==='digest_enabled'?input.checked:input.type==='number'?(input.value===''?null:Number(input.value)):input.value;}try{const result=await request('preferences',{method:'PUT',body:JSON.stringify(value)});Object.assign(p,result.preferences);status.textContent=t('saved');}catch(e){error(e);}finally{save.disabled=false;}};
|
||||||
|
}
|
||||||
|
function taskTable(data){const wrap=el('div');wrap.className='productivity-table-wrap';const table=el('table');table.className='productivity-table';const head=el('tr');for(const name of [ja?'タスク':'Task',t('points'),t('work')])head.append(el('th',name));const thead=el('thead');thead.append(head);table.append(thead);const body=el('tbody');for(const task of data.tasks){const row=el('tr'),name=el('td'),link=el('a',(task.completed?'✓ ':'')+(task.title||task.uuid));link.href='/v/plan/task/'+encodeURIComponent(task.uuid);name.append(link);row.append(name,el('td',String(task.points||0)),el('td',(task.work_ms/3600000).toFixed(2)));body.append(row);}table.append(body);wrap.append(table);if(!data.tasks.length)wrap.append(el('p',t('empty')));return wrap;}
|
||||||
|
async function report(){
|
||||||
|
const controls=el('form');controls.className='productivity-controls';const from=el('input'),to=el('input');from.type=to.type='date';from.required=to.required=true;from.ariaLabel=ja?'開始日':'From';to.ariaLabel=ja?'終了日(含まない)':'To (exclusive)';const refresh=el('button','↻ '+t('refresh'));controls.append(from,to,refresh);
|
||||||
|
const results=el('section');content.replaceChildren(controls,results);let generation=0;
|
||||||
|
async function load(){const ticket=++generation;refresh.disabled=true;try{const query=new URLSearchParams();if(from.value)query.set('from',from.value);if(to.value)query.set('to',to.value);const d=await request('report?'+query);if(ticket!==generation)return;status.textContent=d.partial?t('partial'):d.timezone;
|
||||||
|
if(!from.value&&d.days.length){from.value=d.days[0].date;const end=new Date(d.days.at(-1).date+'T12:00:00Z');end.setUTCDate(end.getUTCDate()+1);to.value=end.toISOString().slice(0,10);}
|
||||||
|
const stats=el('div');stats.className='productivity-stats';for(const [label,key,divisor] of [['completed','completed',1],['points','points',1],['work','work_ms',3600000],['focus','focus_ms',3600000]]){const card=el('div',t(label));card.className='productivity-stat';const sum=d.days.reduce((total,day)=>total+day[key],0)/divisor;card.append(el('strong',divisor===1?String(sum):sum.toFixed(2)));stats.append(card);}
|
||||||
|
const scroll=el('div');scroll.className='productivity-heatmap-scroll';const grid=el('div');grid.className='productivity-heatmap';grid.ariaLabel=t('report');const detail=el('section');detail.append(taskTable(d));let detailSequence=0;
|
||||||
|
if(d.days.length){const weekday=new Date(d.days[0].date+'T12:00:00Z').getUTCDay();for(let i=0;i<weekday;i++)grid.append(el('span'));}
|
||||||
|
for(const day of d.days){const cell=el('button');cell.type='button';cell.className='productivity-day';cell.dataset.level=String(day.points===0?0:day.points<=3?1:day.points<=8?2:day.points<=20?3:4);cell.title=cell.ariaLabel=`${day.date}: ${day.completed} ${t('completed')}, ${day.points} ${t('points')}, ${(day.work_ms/3600000).toFixed(2)}h`;
|
||||||
|
cell.onclick=async()=>{const sequence=++detailSequence;try{const next=new Date(day.date+'T12:00:00Z');next.setUTCDate(next.getUTCDate()+1);const single=await request('report?'+new URLSearchParams({from:day.date,to:next.toISOString().slice(0,10)}));if(sequence!==detailSequence)return;detail.replaceChildren(el('h2',day.date),taskTable(single));}catch(e){error(e);}};grid.append(cell);}
|
||||||
|
scroll.append(grid);const note=el('p',ja?'1タスクのポイント = 1 + ⌈見積分数 / 30⌉ × 複雑度(1〜5)。完了取消は集計から除外。作業時間とPomodoroは別集計で、重複する場合は加算しません。':'Points per task = 1 + ceil(estimated minutes / 30) × complexity (1–5). Reopened tasks are excluded. Work and Pomodoro are separate; overlapping time is not added together.');note.className='productivity-note';results.replaceChildren(stats,scroll,note,detail);
|
||||||
|
}catch(e){error(e);}finally{refresh.disabled=false;}}
|
||||||
|
controls.onsubmit=e=>{e.preventDefault();load();};await load();
|
||||||
|
}
|
||||||
|
(root.dataset.view==='settings'?settings():report()).catch(error);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
(()=>{'use strict';const app=document.getElementById('tasks-app');if(!app)return;const ja=document.documentElement.lang.startsWith('ja'),t=(a,b)=>ja?b:a,api='/_/api/v1/extension/organizer.tasks/',bar=document.createElement('section'),label=document.createElement('a'),clock=document.createElement('span'),stop=document.createElement('button'),status=document.createElement('span');bar.className='task-work-bar';bar.hidden=true;bar.style.cssText='display:none;grid-column:1/-1;gap:.6rem;align-items:center;flex-wrap:wrap;padding:.5rem 0';stop.type='button';stop.textContent=t('■ Stop recording','■ 作業記録を終了');status.role='status';bar.append(label,clock,stop,status);app.prepend(bar);let current=null,busy=false;
|
||||||
|
async function request(path,options={}){const r=await fetch(api+path,{credentials:'same-origin',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json'}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t('Recording failed. Check the active timer and reload; no duplicate timer is started.','記録できません。実行中の記録と権限を確認し再読込してください。タイマーは重複開始しません。'));return d;}
|
||||||
|
function tick(){clock.textContent=current?.uuid?Math.floor(Math.max(0,Date.now()-current.start_ms)/60000)+' min':'';}
|
||||||
|
async function load(){if(busy||document.hidden)return;try{const d=await request('work');current=d.item;bar.hidden=!current?.uuid;bar.style.display=bar.hidden?'none':'flex';if(current?.uuid){label.href='/v/plan/task/'+current.task_uuid;const task=await request('items/'+current.task_uuid);label.textContent=t('Recording: ','作業記録:')+task.item.title;}tick();}catch(e){status.textContent=e.message;}}
|
||||||
|
app.addEventListener('task-work',async e=>{if(busy)return;busy=true;try{await request('work',{method:'POST',body:JSON.stringify({action:'start',uuid:crypto.randomUUID(),task_uuid:e.detail.uuid})});status.textContent='';}catch(err){bar.hidden=false;bar.style.display='flex';status.textContent=err.message;const feedback=document.getElementById('tasks-status');if(feedback)feedback.textContent=err.message;}finally{busy=false;await load();}});
|
||||||
|
stop.onclick=async()=>{if(busy||!current?.uuid)return;busy=true;stop.disabled=true;try{await request('work',{method:'POST',body:JSON.stringify({...current,action:'stop'})});status.textContent='';}catch(e){status.textContent=e.message;}finally{busy=false;stop.disabled=false;await load();}};setInterval(()=>{if(!document.hidden)tick();},10000);setInterval(load,60000);document.addEventListener('visibilitychange',load);load();})();
|
||||||
+10
-3
@@ -34,6 +34,8 @@
|
|||||||
const icons = {carryover:'↶',today:'☀',tomorrow:'⇢',inbox:'↓',backlog:'≡',someday:'◇',review:'↻',all:'☷',projects:'▱',done:'✓',archived:'▣'};
|
const icons = {carryover:'↶',today:'☀',tomorrow:'⇢',inbox:'↓',backlog:'≡',someday:'◇',review:'↻',all:'☷',projects:'▱',done:'✓',archived:'▣'};
|
||||||
Object.keys(icons).forEach(key => { const a = el('a'); a.href = routes[key] || '/v/plan/tasks/' + key; a.append(el('span',icons[key]),el('span',t(key))); if(view===key||(key==='tomorrow'&&view==='day'&&selectedDate===nextDay(today)))a.setAttribute('aria-current','page'); $('nav').append(a); });
|
Object.keys(icons).forEach(key => { const a = el('a'); a.href = routes[key] || '/v/plan/tasks/' + key; a.append(el('span',icons[key]),el('span',t(key))); if(view===key||(key==='tomorrow'&&view==='day'&&selectedDate===nextDay(today)))a.setAttribute('aria-current','page'); $('nav').append(a); });
|
||||||
const schedule=el('a','▦ '+t('schedule'));schedule.href='/v/plan/tasks/schedule'+(projectID?'?project='+projectID:'');$('nav').append(schedule);
|
const schedule=el('a','▦ '+t('schedule'));schedule.href='/v/plan/tasks/schedule'+(projectID?'?project='+projectID:'');$('nav').append(schedule);
|
||||||
|
for(const [route,label] of [['report',ja?'▥ 達成度・作業レポート':'▥ Activity report'],['settings',ja?'⚙ 既定値・メール':'⚙ Defaults and email']]){const a=el('a',label);a.href='/v/plan/tasks/'+route;$('nav').append(a);}
|
||||||
|
const contacts=el('a',ja?'♧ 連絡先':'♧ Contacts');contacts.href='/v/plan/contacts';$('nav').append(contacts);
|
||||||
$('date').textContent = view==='day'?selectedDate:today; $('heading').textContent = t(view === 'project' ? 'project' : view === 'detail' || view === 'new' ? 'all' : view);
|
$('date').textContent = view==='day'?selectedDate:today; $('heading').textContent = t(view === 'project' ? 'project' : view === 'detail' || view === 'new' ? 'all' : view);
|
||||||
$('help').textContent = t(view==='today'?'todayHelp':view==='review'?'reviewHelp':'private');
|
$('help').textContent = t(view==='today'?'todayHelp':view==='review'?'reviewHelp':'private');
|
||||||
$('search-label').textContent=t('search');$('quick-title').placeholder=t('quick');$('quick-title').setAttribute('aria-label',t('title'));
|
$('search-label').textContent=t('search');$('quick-title').placeholder=t('quick');$('quick-title').setAttribute('aria-label',t('title'));
|
||||||
@@ -53,7 +55,9 @@
|
|||||||
if(view==='carryover')$('help').textContent=ja?'昨日以前の計画・期限が残っている未完了タスク。行の矢印で割り当て直します(期限は変更しません)。':'Unfinished tasks planned or due before today. Use the row arrow to reschedule without changing the due date.';
|
if(view==='carryover')$('help').textContent=ja?'昨日以前の計画・期限が残っている未完了タスク。行の矢印で割り当て直します(期限は変更しません)。':'Unfinished tasks planned or due before today. Use the row arrow to reschedule without changing the due date.';
|
||||||
}
|
}
|
||||||
if(!writable)$('help').textContent+=' '+t('readonly');
|
if(!writable)$('help').textContent+=' '+t('readonly');
|
||||||
function blank(kind='task') { return { uuid:crypto.randomUUID(),kind,title:'',notes:'',status:'todo',bucket:['inbox','backlog','someday'].includes(view)?view:'inbox',priority:1,estimate_minutes:0,project_uuid:kind==='task'?projectID:'',page_uuid:'',due_on:'',planned_on:['today','day'].includes(view)&&kind==='task'?(view==='day'?selectedDate:today):'',review_on:'',archived:false,version:0 }; }
|
let taskDefaults={};
|
||||||
|
async function refreshDefaults(){taskDefaults=(await request('/_/api/v1/extension/organizer.tasks/preferences')).defaults;}
|
||||||
|
function blank(kind='task') { const defaults=kind==='task'?taskDefaults:{};return { ...defaults,uuid:crypto.randomUUID(),kind,title:'',notes:'',status:'todo',bucket:['inbox','backlog','someday'].includes(view)?view:'inbox',priority:1,estimate_minutes:defaults.estimate_minutes||0,project_uuid:kind==='task'?(projectID||defaults.project_uuid||''):'',page_uuid:'',due_on:defaults.due_on||'',planned_on:['today','day'].includes(view)&&kind==='task'?(view==='day'?selectedDate:today):(defaults.planned_on||''),review_on:defaults.review_on||'',archived:false,version:0 }; }
|
||||||
function listView(){return ['project','detail','new'].includes(view)?'all':view;}
|
function listView(){return ['project','detail','new'].includes(view)?'all':view;}
|
||||||
async function load(append=false) {
|
async function load(append=false) {
|
||||||
if(window.PagesWikiTaskRows?.hasDirty()){$('status').textContent=ja?'編集中の行を保存または再読込してください。':'Save or reload edited rows first.';return;}
|
if(window.PagesWikiTaskRows?.hasDirty()){$('status').textContent=ja?'編集中の行を保存または再読込してください。':'Save or reload edited rows first.';return;}
|
||||||
@@ -97,6 +101,7 @@
|
|||||||
if($('dialog').open&&!closeDialog())return;
|
if($('dialog').open&&!closeDialog())return;
|
||||||
const ticket=++detailGeneration;dialogController?.abort();dialogController=new AbortController();$('error').textContent='';editing=null;dirty=false;$('fields').replaceChildren();Object.keys(fields).forEach(k=>delete fields[k]);$('history').open=false;$('history').querySelector('ol').replaceChildren();$('dialog-title').textContent=t('loading');$('save').disabled=true;$('archive').hidden=true;$('history').hidden=true;$('project-open').hidden=true;$('dialog').showModal();
|
const ticket=++detailGeneration;dialogController?.abort();dialogController=new AbortController();$('error').textContent='';editing=null;dirty=false;$('fields').replaceChildren();Object.keys(fields).forEach(k=>delete fields[k]);$('history').open=false;$('history').querySelector('ol').replaceChildren();$('dialog-title').textContent=t('loading');$('save').disabled=true;$('archive').hidden=true;$('history').hidden=true;$('project-open').hidden=true;$('dialog').showModal();
|
||||||
try {
|
try {
|
||||||
|
if(!id&&kind==='task')await refreshDefaults();
|
||||||
const data=id?await request(api+'/'+id,{signal:dialogController.signal}):{item:blank(kind),page_path:''};if(ticket!==detailGeneration)return;editing=data.item;
|
const data=id?await request(api+'/'+id,{signal:dialogController.signal}):{item:blank(kind),page_path:''};if(ticket!==detailGeneration)return;editing=data.item;
|
||||||
$('dialog-title').textContent=t(id?'edit':kind==='project'?'newProject':'newTask');
|
$('dialog-title').textContent=t(id?'edit':kind==='project'?'newProject':'newTask');
|
||||||
const title=field('title',t('title'),'text',editing.title,true);title.required=true;title.maxLength=300;
|
const title=field('title',t('title'),'text',editing.title,true);title.required=true;title.maxLength=300;
|
||||||
@@ -108,6 +113,8 @@
|
|||||||
field('project_uuid',t('project'),'select',editing.project_uuid,true,[[editing.project_uuid,t(editing.project_uuid?'loading':'noProject')]]);await fillProjects(editing.project_uuid);if(ticket!==detailGeneration)return;
|
field('project_uuid',t('project'),'select',editing.project_uuid,true,[[editing.project_uuid,t(editing.project_uuid?'loading':'noProject')]]);await fillProjects(editing.project_uuid);if(ticket!==detailGeneration)return;
|
||||||
field('priority',t('priority'),'select',editing.priority,false,[[0,t('low')],[1,t('normal')],[2,t('high')],[3,t('urgent')]]);
|
field('priority',t('priority'),'select',editing.priority,false,[[0,t('low')],[1,t('normal')],[2,t('high')],[3,t('urgent')]]);
|
||||||
const estimate=field('estimate_minutes',t('estimate'),'number',editing.estimate_minutes);estimate.min=0;estimate.max=10080;
|
const estimate=field('estimate_minutes',t('estimate'),'number',editing.estimate_minutes);estimate.min=0;estimate.max=10080;
|
||||||
|
const complexity=field('complexity',ja?'複雑度(1〜5)':'Complexity (1–5)','number',editing.complexity||1);complexity.min=1;complexity.max=5;
|
||||||
|
field('assignee_uuid',ja?'担当者UUID(権限は付与しません)':'Assignee UUID (does not grant access)','text',editing.assignee_uuid||'',true);
|
||||||
['due_on','planned_on','review_on','start_on','end_on'].forEach(k=>field(k,t(k),'date',editing[k]));
|
['due_on','planned_on','review_on','start_on','end_on'].forEach(k=>field(k,t(k),'date',editing[k]));
|
||||||
['notify_due','notify_planned'].forEach(k=>{const input=field(k,t(k),'checkbox','',true);input.checked=!!editing[k];input.parentElement.classList.add('task-toggle');});
|
['notify_due','notify_planned'].forEach(k=>{const input=field(k,t(k),'checkbox','',true);input.checked=!!editing[k];input.parentElement.classList.add('task-toggle');});
|
||||||
const clock=field('reminder_time',t('reminder_time'),'time',editing.reminder_time||'09:00');clock.step=60;
|
const clock=field('reminder_time',t('reminder_time'),'time',editing.reminder_time||'09:00');clock.step=60;
|
||||||
@@ -132,14 +139,14 @@
|
|||||||
function closeDialog(force=false){if(saving)return false;if(!force&&dirty&&!confirm(t('discard')))return false;detailGeneration++;projectGeneration++;dialogController?.abort();$('dialog').close();editing=null;dirty=false;return true;}
|
function closeDialog(force=false){if(saving)return false;if(!force&&dirty&&!confirm(t('discard')))return false;detailGeneration++;projectGeneration++;dialogController?.abort();$('dialog').close();editing=null;dirty=false;return true;}
|
||||||
$('close').addEventListener('click',()=>closeDialog());$('dialog').addEventListener('cancel',e=>{e.preventDefault();closeDialog();});
|
$('close').addEventListener('click',()=>closeDialog());$('dialog').addEventListener('cancel',e=>{e.preventDefault();closeDialog();});
|
||||||
$('form').addEventListener('input',()=>{dirty=true;});
|
$('form').addEventListener('input',()=>{dirty=true;});
|
||||||
function readForm(){const item={...editing};['title','notes','notes_subpath','status','bucket','project_uuid','due_on','planned_on','review_on','start_on','end_on','reminder_time'].forEach(k=>{if(fields[k])item[k]=fields[k].value;});['notify_due','notify_planned'].forEach(k=>{if(fields[k])item[k]=fields[k].checked;});['priority','estimate_minutes'].forEach(k=>{if(fields[k])item[k]=Number(fields[k].value);});if(fields.page_path?.dataset.changed||(!item.page_uuid&&fields.page_path?.value))item.page_path=fields.page_path.value;return item;}
|
function readForm(){const item={...editing};['title','notes','notes_subpath','status','bucket','project_uuid','assignee_uuid','due_on','planned_on','review_on','start_on','end_on','reminder_time'].forEach(k=>{if(fields[k])item[k]=fields[k].value;});['notify_due','notify_planned'].forEach(k=>{if(fields[k])item[k]=fields[k].checked;});['priority','estimate_minutes','complexity'].forEach(k=>{if(fields[k])item[k]=Number(fields[k].value);});if(fields.page_path?.dataset.changed||(!item.page_uuid&&fields.page_path?.value))item.page_path=fields.page_path.value;return item;}
|
||||||
async function saveItem(item){const data=await request(api+(item.version?'/'+item.uuid:''),{method:item.version?'PUT':'POST',headers:item.version?{'If-Match':'"'+item.version+'"'}:{},body:JSON.stringify(item)});app.dispatchEvent(new Event('task-today-refresh'));return data;}
|
async function saveItem(item){const data=await request(api+(item.version?'/'+item.uuid:''),{method:item.version?'PUT':'POST',headers:item.version?{'If-Match':'"'+item.version+'"'}:{},body:JSON.stringify(item)});app.dispatchEvent(new Event('task-today-refresh'));return data;}
|
||||||
async function submit(archive=false){if(!editing||saving||!writable)return;if(!$('form').reportValidity())return;const item=readForm();if(archive)item.archived=!item.archived;saving=true;Object.values(fields).forEach(f=>f.disabled=true);$('save').disabled=$('archive').disabled=true;$('error').textContent='';try{await saveItem(item);saving=false;closeDialog(true);await load();if(projectID)await loadProject();}catch(e){$('error').textContent=e.message;}finally{saving=false;Object.values(fields).forEach(f=>f.disabled=!writable);$('save').disabled=$('archive').disabled=false;}}
|
async function submit(archive=false){if(!editing||saving||!writable)return;if(!$('form').reportValidity())return;const item=readForm();if(archive)item.archived=!item.archived;saving=true;Object.values(fields).forEach(f=>f.disabled=true);$('save').disabled=$('archive').disabled=true;$('error').textContent='';try{await saveItem(item);saving=false;closeDialog(true);await load();if(projectID)await loadProject();}catch(e){$('error').textContent=e.message;}finally{saving=false;Object.values(fields).forEach(f=>f.disabled=!writable);$('save').disabled=$('archive').disabled=false;}}
|
||||||
$('form').addEventListener('submit',e=>{e.preventDefault();submit();});$('archive').addEventListener('click',()=>submit(true));
|
$('form').addEventListener('submit',e=>{e.preventDefault();submit();});$('archive').addEventListener('click',()=>submit(true));
|
||||||
$('history').addEventListener('toggle',async()=>{if(!$('history').open||!editing?.version)return;const id=editing.uuid;try{const data=await request(api+'/'+id+'/history');if(editing?.uuid!==id)return;const ol=$('history').querySelector('ol');ol.replaceChildren();data.items.forEach(v=>ol.append(el('li','#'+v.version+' · '+new Date(v.created_at_ms).toLocaleString())));}catch(e){$('error').textContent=e.message;}});
|
$('history').addEventListener('toggle',async()=>{if(!$('history').open||!editing?.version)return;const id=editing.uuid;try{const data=await request(api+'/'+id+'/history');if(editing?.uuid!==id)return;const ol=$('history').querySelector('ol');ol.replaceChildren();data.items.forEach(v=>ol.append(el('li','#'+v.version+' · '+new Date(v.created_at_ms).toLocaleString())));}catch(e){$('error').textContent=e.message;}});
|
||||||
$('new').addEventListener('click',()=>open('',view==='projects'?'project':'task'));
|
$('new').addEventListener('click',()=>open('',view==='projects'?'project':'task'));
|
||||||
let capturing=false,captureDraft=null;
|
let capturing=false,captureDraft=null;
|
||||||
$('capture').addEventListener('submit',async e=>{e.preventDefault();if(capturing)return;const title=$('quick-title').value.trim();if(!title)return;capturing=true;const b=$('capture').querySelector('button');b.disabled=$('quick-title').disabled=true;if(!captureDraft||captureDraft.title!==title)captureDraft={...blank(),title};try{await saveItem(captureDraft);captureDraft=null;$('quick-title').value='';await load();}catch(err){$('status').textContent=err.message;}finally{capturing=false;b.disabled=$('quick-title').disabled=false;$('quick-title').focus();}});
|
$('capture').addEventListener('submit',async e=>{e.preventDefault();if(capturing)return;const title=$('quick-title').value.trim();if(!title)return;capturing=true;const b=$('capture').querySelector('button');b.disabled=$('quick-title').disabled=true;try{if(!captureDraft||captureDraft.title!==title){await refreshDefaults();captureDraft={...blank(),title};}await saveItem(captureDraft);captureDraft=null;$('quick-title').value='';await load();}catch(err){$('status').textContent=err.message;}finally{capturing=false;b.disabled=$('quick-title').disabled=false;$('quick-title').focus();}});
|
||||||
function debounce(fn,delay){let timer;return()=>{clearTimeout(timer);timer=setTimeout(fn,delay);};}
|
function debounce(fn,delay){let timer;return()=>{clearTimeout(timer);timer=setTimeout(fn,delay);};}
|
||||||
$('search').addEventListener('input',debounce(()=>load(),200));$('refresh').addEventListener('click',()=>load());$('more').addEventListener('click',()=>load(true));
|
$('search').addEventListener('input',debounce(()=>load(),200));$('refresh').addEventListener('click',()=>load());$('more').addEventListener('click',()=>load(true));
|
||||||
async function loadProject(){try{const {item}=await request(api+'/'+projectID);$('heading').textContent=item.title;$('help').textContent=(item.archived?t('archived')+' · ':'')+(item.notes||t('private'));$('new').hidden=$('capture').hidden=!writable||item.archived;$('project-edit').hidden=false;$('project-edit').title=$('project-edit').ariaLabel=t('edit');}catch(e){$('status').textContent=e.message;}}
|
async function loadProject(){try{const {item}=await request(api+'/'+projectID);$('heading').textContent=item.title;$('help').textContent=(item.archived?t('archived')+' · ':'')+(item.notes||t('private'));$('new').hidden=$('capture').hidden=!writable||item.archived;$('project-edit').hidden=false;$('project-edit').title=$('project-edit').ariaLabel=t('edit');}catch(e){$('status').textContent=e.message;}}
|
||||||
|
|||||||
@@ -6,4 +6,4 @@
|
|||||||
<header class="calendar-toolbar"><h1 id="calendar-heading">Calendar</h1><select id="calendar-select" aria-label="Calendar"></select><button id="calendar-create" type="button" aria-label="Create calendar">+</button><button id="calendar-settings" type="button" aria-label="Calendar settings">⚙</button><button id="calendar-refresh" type="button" aria-label="Refresh">↻</button><a id="calendar-new" href="/v/event/new">+</a></header>
|
<header class="calendar-toolbar"><h1 id="calendar-heading">Calendar</h1><select id="calendar-select" aria-label="Calendar"></select><button id="calendar-create" type="button" aria-label="Create calendar">+</button><button id="calendar-settings" type="button" aria-label="Calendar settings">⚙</button><button id="calendar-refresh" type="button" aria-label="Refresh">↻</button><a id="calendar-new" href="/v/event/new">+</a></header>
|
||||||
<nav id="calendar-nav" class="calendar-toolbar"></nav><p id="calendar-status" role="status" aria-live="polite"></p><div id="calendar-content"></div>
|
<nav id="calendar-nav" class="calendar-toolbar"></nav><p id="calendar-status" role="status" aria-live="polite"></p><div id="calendar-content"></div>
|
||||||
<dialog id="calendar-dialog"><form id="calendar-form"><header><h2 id="calendar-dialog-title"></h2><button type="button" data-close aria-label="Close">×</button></header><div id="calendar-fields"></div><p id="calendar-form-error" role="alert"></p><footer><button type="submit" id="calendar-submit"></button><button type="button" data-close id="calendar-cancel"></button></footer></form></dialog>
|
<dialog id="calendar-dialog"><form id="calendar-form"><header><h2 id="calendar-dialog-title"></h2><button type="button" data-close aria-label="Close">×</button></header><div id="calendar-fields"></div><p id="calendar-form-error" role="alert"></p><footer><button type="submit" id="calendar-submit"></button><button type="button" data-close id="calendar-cancel"></button></footer></form></dialog>
|
||||||
</main><link rel="stylesheet" href="/static/css/dav-settings.css?v=2"><script src="/static/js/calendar.js?v=13" defer></script><script src="/static/js/task-dav-settings.js?v=3" defer></script></body></html>{{ end }}
|
</main><link rel="stylesheet" href="/static/css/dav-settings.css?v=3"><script src="/static/js/calendar.js?v=13" defer></script><script src="/static/js/task-dav-settings.js?v=4" defer></script></body></html>{{ end }}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{{ define "contacts.gohtml" }}<!doctype html>
|
||||||
|
<html lang="{{ .Locale }}"><head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>{{ .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/task-productivity.css?v=1"><link rel="stylesheet" href="/static/css/contacts.css?v=2"><link rel="stylesheet" href="/static/css/dav-settings.css?v=3">
|
||||||
|
</head><body class="mode-view">
|
||||||
|
<header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div>{{ template "auth-menu" . }}</header>
|
||||||
|
<main id="contacts-app" data-writable="{{ .ContactWritable }}">
|
||||||
|
<nav><a href="/v/plan/today">Tasks</a> · <a href="/v/plan/tasks/settings">Settings</a></nav>
|
||||||
|
<h1></h1><p id="contacts-status" role="status" aria-live="polite"></p><section id="contacts-controls"></section>
|
||||||
|
<div class="contacts-layout"><section id="contacts-list"></section><section id="contact-editor"></section></div></main>
|
||||||
|
<script src="/static/js/contacts.js?v=2" defer></script>
|
||||||
|
<script src="/static/js/contact-history.js?v=1" defer></script>
|
||||||
|
<script src="/static/js/task-dav-settings.js?v=4" defer></script>
|
||||||
|
</body></html>{{ end }}
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
<link rel="stylesheet" href="{{ .ThemeCSS }}">
|
<link rel="stylesheet" href="{{ .ThemeCSS }}">
|
||||||
<script defer src="/static/js/content-viewer.js"></script>
|
<script defer src="/static/js/content-viewer.js"></script>
|
||||||
<script defer src="/static/js/home-type-search.js?v=1"></script>
|
<script defer src="/static/js/home-type-search.js?v=1"></script>
|
||||||
|
<script defer src="/static/js/home-command-parser.js?v=1"></script><script defer src="/static/js/home-commands.js?v=1"></script>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body class="mode-home" style="--home-glass-opacity:{{ .HomeGlassOpacity }}%">
|
<body class="mode-home" style="--home-glass-opacity:{{ .HomeGlassOpacity }}%">
|
||||||
|
|||||||
@@ -66,7 +66,8 @@
|
|||||||
</nav>
|
</nav>
|
||||||
<script defer src="/static/js/home-pages.js?v=2"></script>
|
<script defer src="/static/js/home-pages.js?v=2"></script>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
<script defer src="/static/js/home-search-suggest.js?v=1"></script>
|
<script defer src="/static/js/home-search-suggest.js?v=2"></script>
|
||||||
|
<script defer src="/static/js/home-command-parser.js?v=1"></script><script defer src="/static/js/home-commands.js?v=1"></script>
|
||||||
<script defer src="/static/js/home-type-search.js?v=1"></script>
|
<script defer src="/static/js/home-type-search.js?v=1"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{{ define "task_productivity.gohtml" }}<!doctype html>
|
||||||
|
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ T "tasks.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/task-productivity.css?v=1"></head>
|
||||||
|
<body class="mode-view"><header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div><nav><a href="/v/plan/today">{{ T "tasks.title" }}</a></nav>{{ template "auth-menu" . }}</header>
|
||||||
|
<main id="task-productivity" data-view="{{ .ProductivityView }}" data-writable="{{ .TaskWritable }}"><nav class="productivity-nav"><a href="/v/plan/today" data-word="tasks"></a><a href="/v/plan/tasks/report" data-word="report"></a><a href="/v/plan/tasks/settings" data-word="settings"></a><a href="/v/plan/contacts" data-word="contacts"></a></nav><h1></h1><p id="productivity-status" role="status" aria-live="polite"></p><section id="productivity-content"></section></main><script src="/static/js/task-productivity.js?v=1" defer></script></body></html>{{ end }}
|
||||||
@@ -11,4 +11,4 @@
|
|||||||
<p id="tasks-status" role="status" aria-live="polite"></p><div class="tasks-list-scroll"><div id="tasks-list" role="list"></div></div><button type="button" id="tasks-more" hidden></button>
|
<p id="tasks-status" role="status" aria-live="polite"></p><div class="tasks-list-scroll"><div id="tasks-list" role="list"></div></div><button type="button" id="tasks-more" hidden></button>
|
||||||
</section>
|
</section>
|
||||||
<dialog id="tasks-dialog" aria-labelledby="tasks-dialog-title"><form id="tasks-form"><header class="tasks-toolbar"><h2 id="tasks-dialog-title"></h2><button type="button" id="tasks-close">×</button></header><div id="tasks-fields"></div><p id="tasks-error" role="alert"></p><details id="tasks-history"><summary></summary><ol></ol></details><footer class="tasks-actions"><button type="button" id="tasks-archive"></button><a id="tasks-project-open" hidden></a><button type="submit" id="tasks-save"></button></footer></form></dialog>
|
<dialog id="tasks-dialog" aria-labelledby="tasks-dialog-title"><form id="tasks-form"><header class="tasks-toolbar"><h2 id="tasks-dialog-title"></h2><button type="button" id="tasks-close">×</button></header><div id="tasks-fields"></div><p id="tasks-error" role="alert"></p><details id="tasks-history"><summary></summary><ol></ol></details><footer class="tasks-actions"><button type="button" id="tasks-archive"></button><a id="tasks-project-open" hidden></a><button type="submit" id="tasks-save"></button></footer></form></dialog>
|
||||||
</main><link rel="stylesheet" href="/static/css/dav-settings.css?v=2"><script src="/static/js/task-inline.js?v=3" defer></script><script src="/static/js/task-today.js?v=1" defer></script><script src="/static/js/task-planning.js?v=3" defer></script><script src="/static/js/task-focus.js?v=2" defer></script><script src="/static/js/tasks.js?v=6" defer></script><script src="/static/js/task-dav-settings.js?v=3" defer></script></body></html>{{ end }}
|
</main><link rel="stylesheet" href="/static/css/dav-settings.css?v=3"><script src="/static/js/task-inline.js?v=4" defer></script><script src="/static/js/task-today.js?v=1" defer></script><script src="/static/js/task-planning.js?v=3" defer></script><script src="/static/js/task-focus.js?v=2" defer></script><script src="/static/js/task-work.js?v=1" defer></script><script src="/static/js/tasks.js?v=7" defer></script><script src="/static/js/task-dav-settings.js?v=4" defer></script></body></html>{{ end }}
|
||||||
Reference in new issue
Block a user