diff --git a/.claude/skills/store-release/windows.md b/.claude/skills/store-release/windows.md index daae54f1b..b43b05a49 100644 --- a/.claude/skills/store-release/windows.md +++ b/.claude/skills/store-release/windows.md @@ -122,6 +122,7 @@ PFX は 5 年有効。**期限切れ・流出疑い・鍵管理ホスト退役 1. **Partner Center にログイン**: → アプリ「capsicum」(`identity_name=9AFBB08E.capsicum` / `publisher_display_name=小石達也`) 2. **新規 Submission を開始** 3. **Packages**: draft Release に添付された `capsicum.msix` をそのまま upload(`msix_config.store: false` のままで OK、Store 側で再署名される) + - ⚠ **upload 後の検証が終わるまで Save を押さない。**2026-11-23(v2.14.0)に検証の途中で押したところ、申請の Packages が緑にならず、パッケージ画面を開き直しても Save が押せなくなった。選び直しや削除を重ねても戻らず、**しばらく画面遷移を繰り返すうちに押せるようになった**(検証の完了待ちだったとみられる)。⚠ 押してしまったら選び直さずに待ち、戻ったら**同じ版の行が 1 つだけ**かを確かめる 4. **Submission Options > Notes for Certification**: 毎回必須。確定文面・根本原因・Windows 固有の注意は [msstore-review-notes-login.md](../../../docs/msstore-review-notes-login.md) を single source of truth とする(capsicum は OAuth + 外部サーバー前提のため、書かないと Policy 10.3.1 *App Is Testable - Test Account* で差し戻し) 5. **System Requirements (推奨環境)**: 「イマーシブヘッドセット」項目に **明示的にチェックを入れる**罠あり(実体としては不要だが、UI が空欄を許容せず submission に進めない仕様。2026-05-16 にはまった経緯あり、参考: ) 6. **Submit for certification**: Microsoft 公称の認定期間は最大 1-3 日(初回は 3-7 日)だが、**実績では問題がなければ 1 時間程度で通過することが多い**(Android と同様に速い)。数時間経っても Pending のままなら審査で引っかかっている可能性を疑う。通過後に Store listing が自動で publish される diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md index cb4cc2a73..e8b7d8125 100644 --- a/docs/CLAUDE.md +++ b/docs/CLAUDE.md @@ -324,9 +324,9 @@ dart analyze --fatal-infos > /tmp/analyze.log 2>&1; echo "ANALYZE_EXIT=$?" [GitHub Milestones](https://github.com/pooza/capsicum/milestones) が正本。各マイルストーンの概要・スコープはマイルストーンの description に記載し、CLAUDE.md には複写しない。個別 Issue の一覧・ステータスも同様。 -最新リリース: **v2.13.0**(2026-11-19 タグ、build 221、リリース PR [#1397](https://github.com/pooza/capsicum/pull/1397)、merge `976e4297`)。**大更新なし — Akkoma(Pleroma 系)のプッシュ通知と、Akkoma 対応を謳い始める回**。Akkoma のプッシュ通知 [#1390](https://github.com/pooza/capsicum/issues/1390)([#1287](https://github.com/pooza/capsicum/issues/1287) の段階 2・旧方式の暗号 `aesgcm` の復号に対応したので、古い Mastodon(4.3 以前)にもベストエフォートで届く・relay 側は [relay#118](https://github.com/pooza/capsicum-relay/issues/118))と、「Mastodon / Misskey クライアント」の表現に Akkoma を加える [#1399](https://github.com/pooza/capsicum/issues/1399)。ほかにプライバシーとつながりやすさの設定画面 [#1375](https://github.com/pooza/capsicum/issues/1375)、フォローボタンの「リクエスト中」[#1400](https://github.com/pooza/capsicum/issues/1400)、Linux の検証で見つかった 4 件(二重起動 [#1391](https://github.com/pooza/capsicum/issues/1391)・gvfs の警告 [#1392](https://github.com/pooza/capsicum/issues/1392)(記録して close)・Secret Service が無いときの案内 [#1393](https://github.com/pooza/capsicum/issues/1393)・キーリングの保存の試し直し [#1394](https://github.com/pooza/capsicum/issues/1394))、Linux の Spotify のナウプレの歌手 [#1388](https://github.com/pooza/capsicum/issues/1388)、v2.12 の送り分 [#1396](https://github.com/pooza/capsicum/issues/1396)。relay は同時期に Ruby 4.0.10([relay#120](https://github.com/pooza/capsicum-relay/issues/120)・RCE の PoC あり)と Puma 8.1.2([relay#117](https://github.com/pooza/capsicum-relay/issues/117))へ上げた。**全 5 プラットフォーム公開完了(2026-11-21 実測)**: iOS / macOS とも 2.13.0 が `READY_FOR_SALE`(ASC API・macOS が最後)/ Android は production track の versionCode 221(Play API)/ Windows は Microsoft Store が `2.13.221.0` を返す(displaycatalog)/ Linux AppImage は [GitHub Release v2.13.0](https://github.com/pooza/capsicum/releases/tag/v2.13.0)(Latest)。 +最新リリース: **v2.14.0**(2026-11-23 タグ、build 223、リリース PR [#1406](https://github.com/pooza/capsicum/pull/1406)、merge `f98905b6`)。**大更新なし — プッシュ通知のアカウントごとのオン / オフと、通知の宛先の回**。アカウントごとのオン / オフ [#1408](https://github.com/pooza/capsicum/issues/1408)(オフでも relay の行は残す=案 A・種類ごとは [#1411](https://github.com/pooza/capsicum/issues/1411) に分けた)、複数アカウントなら見出しに宛先を添える [#1407](https://github.com/pooza/capsicum/issues/1407)(Windows のアプリ未起動の分は [#1412](https://github.com/pooza/capsicum/issues/1412)・製品版で確かめる)、アカウントの削除でサーバー側のトークンを取り消す [#1401](https://github.com/pooza/capsicum/issues/1401)(入れ直したアカウントのトークンは取り消さない)。ほかにデッキの広い幅でのカラムの一覧 [#1404](https://github.com/pooza/capsicum/issues/1404)(既定 OFF)と、一覧の「ロックしていないカラムを閉じる」[#1405](https://github.com/pooza/capsicum/issues/1405)、Misskey のギャラリーの「人気 / 新着」といいね [#1053](https://github.com/pooza/capsicum/issues/1053)、Linux のロック中のキーリングで解除の画面が出続ける [#1415](https://github.com/pooza/capsicum/issues/1415)、v2.13 の送り分 [#1403](https://github.com/pooza/capsicum/issues/1403)、Ruby の置き場 [#1376](https://github.com/pooza/capsicum/issues/1376)。モロヘイヤのハンドラーのオン / オフ画面 [#1398](https://github.com/pooza/capsicum/issues/1398) は実装が入ったが、入口が mulukhiya#4936 の版待ちで利用者にはまだ見えない(確かめは v2.15)。**提出の状況(2026-11-23)**: iOS / macOS は審査に提出(`WAITING_FOR_REVIEW`)/ Android は production の versionCode 223 / Windows は Partner Center へ提出済み / Linux AppImage は [GitHub Release v2.14.0](https://github.com/pooza/capsicum/releases/tag/v2.14.0)(Latest)。 -⚠ リリース前レビューの送り分は [#1403](https://github.com/pooza/capsicum/issues/1403)(🟡 2 件・🟢 4 件・v2.14)。リリース PR に Codex の line comment は付かなかった。⚠ App Store の年齢制限指定に追加の質問(位置情報の共有・出会い系・期限 2027-01-15)が来ており、新しい版と一緒でないと更新できないため、macOS の 2.14.0 を仮登録して入力する(どちらも「いいえ」)。 +⚠ リリース前レビュー(5 観点 + Codex)は 🔴 0 件。🟡 は develop で直してから 223 を作り直した(222 は修正前の内部ベータ)。🟢 9 件は [#1420](https://github.com/pooza/capsicum/issues/1420)(v2.15)。Codex の P2 2 件は返信 + 👍 済み。スクリーンショットは撮り直しを見送った(リリース PR の本文に記録)。 過去リリースの詳細ログは [archive/release-log.md](archive/release-log.md) に退避した(正本は [GitHub Releases](https://github.com/pooza/capsicum/releases) / Milestones)。マイルストーン移行時のログトリム手順は [milestone-transition スキル](../.claude/skills/milestone-transition/SKILL.md) の step 7。 diff --git a/docs/archive/release-log.md b/docs/archive/release-log.md index 1bca3669d..bcdea5498 100644 --- a/docs/archive/release-log.md +++ b/docs/archive/release-log.md @@ -7,6 +7,10 @@ マイルストーン移行時に旧「最新リリース」を本ファイル先頭へ移すトリム手順は [milestone-transition.md](../milestone-transition.md) を参照。 --- +**v2.13.0**(2026-11-19 タグ、build 221、リリース PR [#1397](https://github.com/pooza/capsicum/pull/1397)、merge `976e4297`)。**大更新なし — Akkoma(Pleroma 系)のプッシュ通知と、Akkoma 対応を謳い始める回**。Akkoma のプッシュ通知 [#1390](https://github.com/pooza/capsicum/issues/1390)([#1287](https://github.com/pooza/capsicum/issues/1287) の段階 2・旧方式の暗号 `aesgcm` の復号に対応したので、古い Mastodon(4.3 以前)にもベストエフォートで届く・relay 側は [relay#118](https://github.com/pooza/capsicum-relay/issues/118))と、「Mastodon / Misskey クライアント」の表現に Akkoma を加える [#1399](https://github.com/pooza/capsicum/issues/1399)。ほかにプライバシーとつながりやすさの設定画面 [#1375](https://github.com/pooza/capsicum/issues/1375)、フォローボタンの「リクエスト中」[#1400](https://github.com/pooza/capsicum/issues/1400)、Linux の検証で見つかった 4 件(二重起動 [#1391](https://github.com/pooza/capsicum/issues/1391)・gvfs の警告 [#1392](https://github.com/pooza/capsicum/issues/1392)(記録して close)・Secret Service が無いときの案内 [#1393](https://github.com/pooza/capsicum/issues/1393)・キーリングの保存の試し直し [#1394](https://github.com/pooza/capsicum/issues/1394))、Linux の Spotify のナウプレの歌手 [#1388](https://github.com/pooza/capsicum/issues/1388)、v2.12 の送り分 [#1396](https://github.com/pooza/capsicum/issues/1396)。relay は同時期に Ruby 4.0.10([relay#120](https://github.com/pooza/capsicum-relay/issues/120)・RCE の PoC あり)と Puma 8.1.2([relay#117](https://github.com/pooza/capsicum-relay/issues/117))へ上げた。**全 5 プラットフォーム公開完了(2026-11-21 実測)**: iOS / macOS とも 2.13.0 が `READY_FOR_SALE`(ASC API・macOS が最後)/ Android は production track の versionCode 221(Play API)/ Windows は Microsoft Store が `2.13.221.0` を返す(displaycatalog)/ Linux AppImage は [GitHub Release v2.13.0](https://github.com/pooza/capsicum/releases/tag/v2.13.0)(Latest)。 + +⚠ リリース前レビューの送り分は [#1403](https://github.com/pooza/capsicum/issues/1403)(🟡 2 件・🟢 4 件・v2.14)。リリース PR に Codex の line comment は付かなかった。⚠ App Store の年齢制限指定の追加の質問(位置情報の共有・出会い系)は、macOS の 2.14.0 を仮登録して入力した(どちらも「いいえ」)。 + **v2.12.0**(2026-11-15 タグ、build 220、リリース PR [#1395](https://github.com/pooza/capsicum/pull/1395)、merge `e53facd2`)。**大更新なし — Akkoma(Pleroma 系)の段階 1 と Linux の検証の回**。Akkoma で基本の操作が使えるようにする [#1287](https://github.com/pooza/capsicum/issues/1287)(段階 1・プッシュ通知の段階 2 は [#1390](https://github.com/pooza/capsicum/issues/1390) に分けて v2.13 の主に)、Linux の専用の検証機(inori・Ubuntu 26.04・Wayland)で best-effort の仕様と未検証の項目を確かめる [#1383](https://github.com/pooza/capsicum/issues/1383) と、そこで見つかったログインし直すたびに他アカウントのトークンが消える [#1387](https://github.com/pooza/capsicum/issues/1387)(`flutter_secure_storage_linux` を `4.0.0-beta.1` へ override・正式版へ戻すのは [#1389](https://github.com/pooza/capsicum/issues/1389))・キーリングのロック解除の画面が出続ける [#1386](https://github.com/pooza/capsicum/issues/1386)・最小サイズが効かない [#1385](https://github.com/pooza/capsicum/issues/1385)・install.sh の digest の照合 [#1384](https://github.com/pooza/capsicum/issues/1384)。ほかに Annict の感想・記録の自動保存 [#1382](https://github.com/pooza/capsicum/issues/1382)、デッキの間はテーマの色を固定の緑にする [#1381](https://github.com/pooza/capsicum/issues/1381)、チャンネルの中のリノートから返信するときに入る先を示す [#1380](https://github.com/pooza/capsicum/issues/1380)、v2.11 の送り分 [#1379](https://github.com/pooza/capsicum/issues/1379)、Sentry の切断の記録の間引きの確認 [#1378](https://github.com/pooza/capsicum/issues/1378)。#1373(Mastodon 5.0 の用語)は訳語待ちで v2.13 へ送った。**全 5 プラットフォーム公開完了(2026-11-17 確認)**: iOS / macOS とも 2.12.0 が `READY_FOR_SALE`(ASC API)/ Android は production の versionCode 220(公開は pooza が確認)/ Windows は Microsoft Store が `2.12.220.0` を返す(displaycatalog)/ Linux AppImage は [GitHub Release v2.12.0](https://github.com/pooza/capsicum/releases/tag/v2.12.0)(Latest)。 ⚠ リリース前レビュー(5 観点 + Codex)は赤 1 件(#1387 の書き直しの控え)ほかを直してからビルドした。リリース PR の Codex P2 1 件(ほかのインスタンスが書き換えたキーリングを考慮していない)は、2 つ同時に起動できること自体が原因として [#1391](https://github.com/pooza/capsicum/issues/1391)(v2.13)で扱う。締めの再レビューは指摘なし。送り分は [#1396](https://github.com/pooza/capsicum/issues/1396)(v2.13)。⚠ v2.12 の Linux の束は、inori の別セッションと並走して進めた。 diff --git a/docs/misskey-capsicum-api-watch.md b/docs/misskey-capsicum-api-watch.md index b6bdccc71..520e04228 100644 --- a/docs/misskey-capsicum-api-watch.md +++ b/docs/misskey-capsicum-api-watch.md @@ -139,6 +139,21 @@ daisskey(ダイスキー本番のフォーク本体)への**本番適用** ## トリアージ履歴 +### 前倒し: 上流タグ `2026.11.0..2026.11.1`(2026-11-26 記録) + +⚠ **fork(`daisskey`)が 2026.11.1 を取り込む前の前倒し**で、上流のタグどうしで差分した(49 commits・重大な脆弱性の修正を含む)。`daisskey` は `d8dfeedd12`(2026.11.0+0)。ダイスキー本番・ステージングとも **2026.11.0+0**、きゅあすきーは **2026.9.1**(いずれも `/api/meta` で実測)。 + +✅ **actionable なし。** + +- ① `autogen/`・② `models/json-schema/`・新規 / 削除 endpoint・endpoint の `required` / `limit` / `requireCredential` / `kind`・④ `router.definition.ts` はいずれも 0 件 +- **passive**: `/api/*` の受け口が GET / POST だけになった(misskey-dev/misskey#18190・それ以外のメソッドは未知のパスと同じ扱い)。capsicum の Misskey 実装は POST(と allowGet の GET)しか使っていない +- **passive**: `hashtag` チャンネルの `q` に上限が入った(グループ 32・1 グループ 32 タグ・1〜128 文字・空文字は拒否)。capsicum は `HashtagQuery.orOfAnds` で空のタグを作らない。OR が 33 個以上の条件だけがストリームを張れなくなる(REST の読み込みは残る) +- **passive**: `drive/files/create` に `NO_SUCH_FOLDER` が増えた(消えたフォルダへのアップロード)。`upstream_error_message.dart` に無いので汎用の文言に倒れる +- **passive**: `userList` チャンネルが内部のイベントを流さなくなり、所属の読み直しを 5 秒ごとの poll からイベント駆動へ変えた。クライアントへ転送するのは `note` / `userAdded` / `userRemoved` だけ。リストの削除後は `note` を送らない +- **none**: HTML の解析を `parseUntrustedHtml` へ寄せた(`i/update` のリンク認証・OAuth のクライアント情報)/ 管理者によるアイコン・バナーの解除の配信 / チャットの履歴 / IPv6 のプロキシ / フォロー解除の連合 / 管理コマンド +- **③ `@syuilo/aiscript` は 1.2.1 で据え置き**。2026.11.0 の宿題だった Flash 互換ハーネスは daisskey が 2026.11.0 になっているのでこの回に回した: **6 / 6 pass**(ダイスキー 4・きゅあすきー 2) +- ⚠⚠ **フォークの取り込み(capsicum の外・pooza/misskey)**: `git merge-tree` で、毎回の CI 定義・`package.json` に加えて **`AccountMoveService.ts` と `UserBlockingService.ts` が中身で衝突**する(どちらも依存の注入の並びで、#467 の `AutoFollowService` と上流の `UserListService` を両方残せば解ける)。🔴 **上流はアカウント移行時のリスト引き継ぎを `UserListService.copyMemberships` へ移し、そこにプロキシのフォロー(`createFollowJob`)を持ってきた。**フォークが #344 / #468 で止めていたのは旧い場所なので、**衝突しないまま新しい場所で復活する**(結果ツリーの 240 行目)。取り込むときに同じ形で止める必要がある + ### 前倒し: 上流タグ `2026.10.1..2026.11.0`(2026-11-12 記録) ⚠ **fork(`daisskey`)が 2026.11.0 を取り込む前の前倒し**で、上流のタグどうしで差分した(64 commits)。`daisskey` は `481883ac2a`(2026.10.1+0)のまま。ダイスキー本番・ステージングとも **2026.10.1+0**、きゅあすきーは **2026.9.1**(いずれも `/api/meta` で実測)。 diff --git a/packages/capsicum/lib/src/provider/account_manager_provider.dart b/packages/capsicum/lib/src/provider/account_manager_provider.dart index 8f195cc04..9f4152eb1 100644 --- a/packages/capsicum/lib/src/provider/account_manager_provider.dart +++ b/packages/capsicum/lib/src/provider/account_manager_provider.dart @@ -18,8 +18,10 @@ import '../service/account_storage.dart'; import '../service/annict_draft_store.dart'; import '../service/background_notification_service.dart'; import '../service/compose_draft_store.dart'; +import '../service/info_bot_follow_keeper.dart'; import '../service/notification_label_cache.dart'; import '../service/push_disabled_accounts.dart'; +import '../service/push_muted_alerts.dart'; import '../service/push_registration_service.dart'; import '../service/secret_service_probe.dart'; import '../service/secure_storage_health.dart'; @@ -171,39 +173,49 @@ class AccountManagerNotifier extends Notifier { // 複数アカウントかどうかを、バックグラウンドのプッシュ表示へ写す (#1407)。 // ⚠ 一覧を書き換える箇所は 10 か所を超えるので、1 か所ずつ足さずここで受ける。 // 起動時の復元は 1 件ずつ埋まるので、値が変わったときだけ書く。 + // + // ⚠⚠ **初回(previous == null)は書かない**(#1420・Windows 側と揃えた)。 + // 起動直後の空の状態で書くと、前回「複数」だった写しを「単数」で上書きし、 + // 復元が済むまでに届いたバックグラウンドのプッシュに宛先が付かない。 + // 初回の値は、復元の完了時の [_saveMultiAccountFlag] で載る。 listenSelf((previous, next) { + if (previous == null) return; final multi = isMultiAccountForPush(next); - if (previous != null && isMultiAccountForPush(previous) == multi) return; + if (isMultiAccountForPush(previous) == multi) return; + _saveMultiAccountFlag(multi); + // Windows の native 受信は shared_preferences を読めないので、 + // push_labels.json にも写す (#1412)。アカウントの増減の各所でも書き直して + // いるが、オフライン保持の出入りなど値だけが変わる場合もここで拾う。 + // ⚠ 初回は上で返している: 起動直後の空の状態で書くと push_labels.json が + // 消え、復元が済むまで bg task が既定ラベルに倒れる。復元の完了時にも + // 同期しているので、初回の値はそちらで載る。 unawaited( - NotificationLabelCache.saveMultiAccount(multi).catchError((Object e) { - // 写しが書けなくても、見出しに宛先が付かないだけ(従来どおり)。 + _syncWindowsPushLabels().catchError((Object e) { // ⚠ 例外の中身は出さない(exception_scrub_guard・型だけ)。 debugPrint( - 'capsicum: notif multi_account save failed: ${e.runtimeType}', + 'capsicum: push labels multi_account sync failed: ' + '${e.runtimeType}', ); }), ); - // Windows の native 受信は shared_preferences を読めないので、 - // push_labels.json にも写す (#1412)。アカウントの増減の各所でも書き直して - // いるが、オフライン保持の出入りなど値だけが変わる場合もここで拾う。 - // ⚠ 初回(previous == null)は書かない: 起動直後の空の状態で書くと - // push_labels.json が消え、復元が済むまで bg task が既定ラベルに倒れる。 - // 復元の完了時にも同期しているので、初回の値はそちらで載る。 - if (previous != null) { - unawaited( - _syncWindowsPushLabels().catchError((Object e) { - // ⚠ 例外の中身は出さない(exception_scrub_guard・型だけ)。 - debugPrint( - 'capsicum: push labels multi_account sync failed: ' - '${e.runtimeType}', - ); - }), - ); - } }); return const AccountManagerState(); } + /// 複数アカウントかどうかの写しを書く (#1407)。待たない。 + /// + /// 写しが書けなくても、見出しに宛先が付かないだけ(従来どおり)。 + void _saveMultiAccountFlag(bool multi) { + unawaited( + NotificationLabelCache.saveMultiAccount(multi).catchError((Object e) { + // ⚠ 例外の中身は出さない(exception_scrub_guard・型だけ)。 + debugPrint( + 'capsicum: notif multi_account save failed: ${e.runtimeType}', + ); + }), + ); + } + /// provider が破棄されたか。背景再試行ループ ([_runOfflineRetryLoop]) は /// 打ち切りを持たないので、これを見て抜ける。 bool _disposed = false; @@ -348,6 +360,10 @@ class AccountManagerNotifier extends Notifier { preferMisskey: account.adapter is ReactionSupport, ); + // ログインしたときに、外れていたお知らせボットのフォローを戻す (#1402)。 + // ⚠ 待たない(ログインを遅らせない)。 + unawaited(InfoBotFollowKeeper.ensureFor(enriched)); + // 通知ラベル(ブースト/投稿)を FCM バックグラウンド isolate 用に焼く。 // registerAccount より先に完了させる: 登録直後に届く最初のプッシュが // ラベル未保存のまま既定値(ブースト/投稿)に化けないように。 @@ -470,6 +486,8 @@ class AccountManagerNotifier extends Notifier { // プッシュ通知をオフにした印も捨てる (#1408)。残すと、入り直したときに // 何も知らせないままオフで始まる。 await PushDisabledAccounts.forget(account.key.toStorageKey()); + // 受け取らない通知の分類も捨てる (#1411・同じ理由)。 + await PushMutedAlerts.forget(account.key.toStorageKey()); final remaining = state.accounts .where((a) => a.key != account.key) @@ -525,11 +543,40 @@ class AccountManagerNotifier extends Notifier { account.userSecret, clientSecret: account.clientSecret, ); - } catch (e) { + } catch (e, st) { debugPrint('capsicum: logout: token revoke failed: ${e.runtimeType}'); + if (shouldReportRevokeFailure(adapter, e)) { + reportOpFailure( + tagKey: 'logout.op', + operation: 'revoke', + error: e, + stackTrace: st, + account: account, + ); + } } } + /// 取り消しの失敗を Sentry へ送るか (#1420)。 + /// + /// debugPrint だけでは、Mastodon の `/oauth/revoke` が仕組みとして通っているかを + /// 現場で確かめられない(v2.14 のリリース前レビュー)。送るのは **Mastodon 系の、 + /// サーバーが応答した失敗**だけ。 + /// + /// - 401 は送らない(もう失効している=取り消したかった状態になっている) + /// - 回線の失敗([isConnectionLevelFailure])は送らない(端末側の事象・#1246) + /// - ⚠ Misskey は今のまま送らない。取り消しの口が無い古い版のエラーは + /// 想定どおりで、送ると版の差を数えるだけになる + @visibleForTesting + static bool shouldReportRevokeFailure(Object adapter, Object error) { + if (adapter is! MastodonAdapter) return false; + if (isConnectionLevelFailure(error)) return false; + if (error is DioException && error.response?.statusCode == 401) { + return false; + } + return true; + } + /// Re-detect mulukhiya on the current account's server and update state. Future redetectMulukhiya() async { final before = state.current; @@ -1012,6 +1059,11 @@ class AccountManagerNotifier extends Notifier { ); } } + // 複数アカウントかどうかの写しを、復元の結果で書き直す (#1420)。 + // ⚠ 一覧の変化を待つ listenSelf は初回を書かないので、**値が変わらない + // 起動(復元しても単数のまま)では誰も書かない**。前の起動から残った写しを + // ここで必ず正す。 + _saveMultiAccountFlag(isMultiAccountForPush(state)); // ⚠ **起動条件は `offline` 全体**であって `retriableFailures` ではない // (#974)。probe に失敗した分(secret は読めた)と、secret 自体が一過性で @@ -1161,7 +1213,7 @@ class AccountManagerNotifier extends Notifier { } final softwareVersion = await softwareVersionFuture; - return Account( + final account = Account( key: accountKey, adapter: adapter, user: user, @@ -1170,6 +1222,10 @@ class AccountManagerNotifier extends Notifier { mulukhiya: mulukhiya, softwareVersion: softwareVersion, ); + // 起動したときに、外れていたお知らせボットのフォローを戻す (#1402)。 + // ⚠ 待たない(復元を遅らせない・失敗しても復元は続ける)。 + unawaited(InfoBotFollowKeeper.ensureFor(account)); + return account; } /// 1 アカウントを probe して、成功したら state へ追加する。 @@ -1601,6 +1657,7 @@ class AccountManagerNotifier extends Notifier { await AnnictDraftStore.clearForAccount(key.toStorageKey()); // プッシュ通知をオフにした印も捨てる (#1408・[logout] と同じ)。 await PushDisabledAccounts.forget(key.toStorageKey()); + await PushMutedAlerts.forget(key.toStorageKey()); _removeOffline(key); await _syncWindowsPushLabels(); } diff --git a/packages/capsicum/lib/src/provider/clip_provider.dart b/packages/capsicum/lib/src/provider/clip_provider.dart index a2ca00f81..5f62db8d0 100644 --- a/packages/capsicum/lib/src/provider/clip_provider.dart +++ b/packages/capsicum/lib/src/provider/clip_provider.dart @@ -78,3 +78,24 @@ final clipNotesProvider = AsyncNotifierProvider.autoDispose ClipNotesNotifier.new, dependencies: [currentAdapterProvider], ); + +/// クリップ 1 つ (#1377)。お気に入りの状態と持ち主を見るのに使う。 +/// +/// ⚠ ほかの人のクリップを見る口が無いアダプターでは null(ボタンを出さない)。 +final clipDetailProvider = FutureProvider.autoDispose.family( + (ref, clipId) async { + final adapter = ref.watch(currentAdapterProvider); + if (adapter is! ClipFavoriteSupport) return null; + return (adapter as ClipFavoriteSupport).getClip(clipId); + }, + dependencies: [currentAdapterProvider], +); + +/// お気に入りに入れたクリップ (#1377)。 +final favoriteClipsProvider = FutureProvider.autoDispose>(( + ref, +) async { + final adapter = ref.watch(currentAdapterProvider); + if (adapter is! ClipFavoriteSupport) return const []; + return (adapter as ClipFavoriteSupport).getFavoriteClips(); +}, dependencies: [currentAdapterProvider]); diff --git a/packages/capsicum/lib/src/provider/gallery_provider.dart b/packages/capsicum/lib/src/provider/gallery_provider.dart index 97cd33d1f..776a847e6 100644 --- a/packages/capsicum/lib/src/provider/gallery_provider.dart +++ b/packages/capsicum/lib/src/provider/gallery_provider.dart @@ -176,3 +176,23 @@ final userGalleryPostsProvider = AsyncNotifierProvider.autoDispose UserGalleryPostsNotifier.new, dependencies: [currentAdapterProvider], ); + +/// ギャラリーの投稿 1 つのいいねの状態 (#1420)。 +typedef GalleryLike = ({bool isLiked, int likedCount}); + +/// 詳細で変えたいいねの、画面をまたいだ写し (#1420)。キーは投稿の id。 +/// +/// 一覧(人気・新着・プロフィール・デッキのカラム)が持つ [GalleryPost] は +/// 取得した時点のままなので、詳細でいいね → 戻る → 開き直すと「未いいね」で +/// 出ていた(押すと `ALREADY_LIKED` で揃うが、件数が 1 多く見える)。 +/// 一覧を取り直すとスクロール位置を失うので、詳細はこの写しを初期値に使う。 +/// +/// ⚠ **アカウントごと**([currentAdapterProvider] を見る)。いいねは自分の +/// 状態なので、別のアカウントの写しを出さない。⚠ autoDispose にしない —— +/// 詳細を閉じたあと誰も見ていない間に消えると、開き直したときに使えない。 +final galleryLikeOverridesProvider = StateProvider>(( + ref, +) { + ref.watch(currentAdapterProvider); + return const {}; +}, dependencies: [currentAdapterProvider]); diff --git a/packages/capsicum/lib/src/router.dart b/packages/capsicum/lib/src/router.dart index 64f5c7fa7..5c271605a 100644 --- a/packages/capsicum/lib/src/router.dart +++ b/packages/capsicum/lib/src/router.dart @@ -29,6 +29,7 @@ import 'ui/screen/chat_room_timeline_screen.dart'; import 'ui/screen/chat_thread_list_screen.dart'; import 'ui/screen/chat_thread_screen.dart'; import 'ui/screen/clip_edit_screen.dart'; +import 'ui/screen/clip_favorites_screen.dart'; import 'ui/screen/clip_management_screen.dart'; import 'ui/screen/clip_notes_screen.dart'; import 'ui/screen/collection_detail_screen.dart'; @@ -421,6 +422,11 @@ final routerProvider = Provider((ref) { path: '/clips/manage', builder: (context, state) => const ClipManagementScreen(), ), + // お気に入りに入れたクリップ (#1377)。クイックチューザの奥から開く。 + GoRoute( + path: '/clips/favorites', + builder: (context, state) => const ClipFavoritesScreen(), + ), // ⚠⚠ 開いた側(デッキのカラム)のスコープで動かす。運ばないと、別 // アカウントのカラムの投稿から「新しいクリップ」を開いたとき、ルートで // 選ばれているアカウントにクリップを作る。 @@ -705,12 +711,20 @@ final routerProvider = Provider((ref) { final id = state.pathParameters['id']!; // 管理画面からはクリップそのもの、クイックチューザからは名前が来る // (#1050)。 + // ⚠ プロフィールのクリップの一覧からは `{'clip': NoteClip}` に開く側の + // スコープを載せて来る (#1377)。デッキの別アカウントのカラムから + // 開いたとき、クリップの id をそのアカウントのサーバーで引くため。 final extra = state.extra; - return ClipNotesScreen( - clipId: id, - clipName: extra is NoteClip - ? extra.name - : (extra is String ? extra : null), + final carried = extra is Map ? extra['clip'] : null; + final named = carried ?? extra; + return withExtraProviderScope( + extra, + ClipNotesScreen( + clipId: id, + clipName: named is NoteClip + ? named.name + : (named is String ? named : null), + ), ); }, ), diff --git a/packages/capsicum/lib/src/service/desktop_notification_dispatcher.dart b/packages/capsicum/lib/src/service/desktop_notification_dispatcher.dart index c43530dea..651f61f3e 100644 --- a/packages/capsicum/lib/src/service/desktop_notification_dispatcher.dart +++ b/packages/capsicum/lib/src/service/desktop_notification_dispatcher.dart @@ -23,6 +23,7 @@ import '../util/sentry_tag_hash.dart'; import 'bounded_key_set.dart'; import 'delivered_push_cleaner.dart'; import 'notification_dedup_channel.dart'; +import 'notification_label_cache.dart' show titleWithRecipient; import 'notification_tag.dart'; import 'stream_connect_failure_reporter.dart'; @@ -359,9 +360,14 @@ class DesktopNotificationDispatcher { } final subsystem = _ref.read(notificationSubsystemProvider); final display = notificationTypeDisplay(n.type); - // 複数アカウントがログインしているときだけ宛先を明示する (単一垢では冗長)。 - final multiAccount = _ref.read(accountManagerProvider).accounts.length > 1; - final title = _title(n, display, multiAccount ? account.key : null); + // 複数アカウントのときだけ宛先を明示する (単一垢では冗長)。 + // ⚠ 判定はプッシュの経路と同じ [isMultiAccountForPush](#1420)。オフライン + // 保持中のアカウントも数える —— オンライン 1 件 + オフライン 1 件の端末で、 + // プッシュの見出しには宛先が付き、こちらには付かない、を起こさない。 + final multiAccount = isMultiAccountForPush( + _ref.read(accountManagerProvider), + ); + final title = _title(n, display, account.key, multiAccount: multiAccount); final body = _body(n, localHost: account.key.host); // 本文(ユーザーコンテンツ)はログに残さない。account/id/type と有無のみ。 debugPrint( @@ -504,16 +510,20 @@ class DesktopNotificationDispatcher { ); } + /// 見出し。複数アカウントなら宛先を末尾に添える(#1407)。 + /// + /// ⚠ **添え方はプッシュの経路と同じ [titleWithRecipient] を通す**(#1420)。 + /// 自前で組んでいた間は、形を揃えるのがコメント頼みだった。 String _title( Notification n, NotificationTypeDisplay display, - AccountKey? recipient, - ) { - final base = _baseTitle(n, display); - if (recipient == null) return base; - // 宛先アカウントを末尾に添える (複数垢の区別用)。 - return '$base (${recipient.handle})'; - } + AccountKey recipient, { + required bool multiAccount, + }) => titleWithRecipient( + _baseTitle(n, display), + '${recipient.username}@${recipient.host}', + multiAccount: multiAccount, + ); String _baseTitle(Notification n, NotificationTypeDisplay display) { if (n.type == NotificationType.announcement) { diff --git a/packages/capsicum/lib/src/service/info_bot_follow_keeper.dart b/packages/capsicum/lib/src/service/info_bot_follow_keeper.dart new file mode 100644 index 000000000..aaab50a79 --- /dev/null +++ b/packages/capsicum/lib/src/service/info_bot_follow_keeper.dart @@ -0,0 +1,158 @@ +import 'package:capsicum_core/capsicum_core.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; + +import '../model/account.dart'; +import '../util/exception_scrub.dart'; +import '../util/user_acct.dart'; + +/// お知らせボット(モロヘイヤの `info_bot`)のフォローを、capsicum の利用者に +/// ついて保つ (#1402)。 +/// +/// - **自分のサーバーのお知らせボットだけ**が対象。別のサーバーのボットは +/// ふつうに解除できる +/// - capsicum からは外させない(プロフィールで解除・ブロックを出さない → +/// [isOwnInfoBot]) +/// - 外れていれば、ログインしたときと起動したときにフォローし直す +/// ([ensureFollowing])。⚠ 勧めるだけでは足りない(Misskey のおすすめ +/// ユーザーと同じ不足になる・2026-11-19 pooza) +/// +/// ⚠ 本体はサーバー側(pooza/mastodon#1007・pooza/misskey#467 で解除とブロック +/// を拒む)。capsicum 側は、すでに外れている利用者と、フォークが入るまでの +/// サーバーのために残す。 +class InfoBotFollowKeeper { + InfoBotFollowKeeper._(); + + /// このプロセスで確かめ終えたアカウント(`AccountKey.toStorageKey()`)。 + /// 復元の再試行や再ログインで何度も呼ばれても、API は 1 回だけ叩く。 + static final _checked = {}; + + @visibleForTesting + static void resetForTesting() => _checked.clear(); + + /// `@info@host` / `info@host` を (username, host) に分ける。読めなければ null。 + @visibleForTesting + static ({String username, String host})? parseAcct(String? acct) { + if (acct == null) return null; + final normalized = acct.startsWith('@') ? acct.substring(1) : acct; + final parts = normalized.split('@'); + if (parts.length != 2 || parts[0].isEmpty || parts[1].isEmpty) return null; + return (username: parts[0], host: parts[1]); + } + + /// サーバーがフォローの解除・ブロックを拒んだ(フォークの 403)ときの、 + /// 利用者に出す文言。拒まれたのでなければ null。 + /// + /// ⚠ 両フォークは同じ英文を返す(pooza/mastodon#1007 は `{"error": "…"}`、 + /// pooza/misskey#467 は `{"error": {"message": "…", "code": "…"}}`)。 + /// 英文が一致したときだけ、Mastodon の Web(`alert.protected_follow.*`)と + /// 同じ日本語に差し替える。 + static String? refusalMessage(Object error) { + if (error is! DioException || error.response?.statusCode != 403) { + return null; + } + final body = '${error.response?.data}'; + if (!body.contains('is specified by the server')) return null; + if (body.contains('cannot be unfollowed')) { + return 'このユーザーはサーバーが指定しているため、フォローを解除できません。'; + } + if (body.contains('cannot be blocked')) { + return 'このユーザーはサーバーが指定しているため、ブロックできません。'; + } + return null; + } + + /// [user] が、[localHost] のサーバーのお知らせボット([infoBotAcct])か。 + /// + /// ⚠ ボットの acct が別のサーバーを指していたら false(対象は自分の + /// サーバーのボットだけ)。username と host は大文字小文字を区別しない。 + static bool isOwnInfoBot({ + required User user, + required String? infoBotAcct, + required String localHost, + }) { + final bot = parseAcct(infoBotAcct); + if (bot == null) return false; + if (bot.host.toLowerCase() != localHost.toLowerCase()) return false; + if (user.username.toLowerCase() != bot.username.toLowerCase()) return false; + return isLocalHost(user.host, localHost: localHost); + } + + /// [account] で、自分のサーバーのお知らせボットをフォローしていなければ + /// フォローする。失敗しても投げない(次に起動したときにまた確かめる)。 + static Future ensureFor(Account account) async { + final adapter = account.adapter; + if (adapter is! FollowSupport) return; + final follow = adapter as FollowSupport; + if (account.mulukhiya?.infoBotAcct == null) return; + final key = account.key.toStorageKey(); + if (_checked.contains(key)) return; + _checked.add(key); + try { + final result = await ensureFollowing( + infoBotAcct: account.mulukhiya?.infoBotAcct, + localHost: account.key.host, + ownUsername: account.key.username, + lookup: adapter.getUser, + relationship: follow.getRelationship, + follow: follow.followUser, + ); + debugPrint('capsicum: info_bot follow: ${result.name}'); + } catch (e) { + // ⚠ 失敗したら控えから外す。次の復元の再試行や再ログインで確かめ直せる。 + _checked.remove(key); + debugLogException('capsicum: info_bot follow failed', e); + } + } + + /// [ensureFor] の中身。API を関数で受けるのはテストのため。 + @visibleForTesting + static Future ensureFollowing({ + required String? infoBotAcct, + required String localHost, + required String ownUsername, + required Future Function(String username, String host) lookup, + required Future Function(String userId) relationship, + required Future Function(String userId) follow, + }) async { + final bot = parseAcct(infoBotAcct); + if (bot == null) return InfoBotFollowResult.noBot; + if (bot.host.toLowerCase() != localHost.toLowerCase()) { + return InfoBotFollowResult.noBot; + } + // ボット自身でログインしている。 + if (bot.username.toLowerCase() == ownUsername.toLowerCase()) { + return InfoBotFollowResult.self; + } + final user = await lookup(bot.username, bot.host); + if (user == null) return InfoBotFollowResult.notFound; + final rel = await relationship(user.id); + if (rel.following || rel.requested) return InfoBotFollowResult.following; + // ⚠ ブロックしている相手はフォローし直さない(ブロックは #1402 の対象外・ + // フォローするとブロックが解けるサーバーがある)。 + if (rel.blocking) return InfoBotFollowResult.blocking; + await follow(user.id); + return InfoBotFollowResult.followed; + } +} + +/// [InfoBotFollowKeeper.ensureFollowing] の結果。ログとテストのため。 +enum InfoBotFollowResult { + /// ボットが無い・読めない・別のサーバーのボット。 + noBot, + + /// ボット自身でログインしている。 + self, + + /// ボットのアカウントが見つからない。 + notFound, + + /// もうフォローしている(承認待ちを含む)。 + following, + + /// ブロックしているので触らない。 + blocking, + + /// フォローし直した。 + followed, +} diff --git a/packages/capsicum/lib/src/service/mastodon_push_refetch.dart b/packages/capsicum/lib/src/service/mastodon_push_refetch.dart new file mode 100644 index 000000000..c45b29dee --- /dev/null +++ b/packages/capsicum/lib/src/service/mastodon_push_refetch.dart @@ -0,0 +1,214 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../ui/widget/content_parser.dart' show stripHtml; +import 'account_storage.dart'; +import 'push_failure_recorder.dart'; +import 'push_message_dispatcher.dart' show DecryptedPushContent; + +/// 復号できなかった Mastodon 系のプッシュを、API で最新の通知を引き直して +/// 中身つきで出す(Android・#1426)。 +/// +/// ⚠ **なぜ復号できない 1 通が届くのか。**上流のサーバーに、同じ宛先への古い +/// 購読(以前のログインのトークンに付いたもの)が残っていると、同じ通知が +/// 別々の鍵で複数通届く。relay の重複の抑止(capsicum-relay の +/// `push_dedup.rb`・#692)は最初に着いた 1 通だけを通すので、**古い鍵の 1 通が +/// 勝つと端末では読めない**。どれが勝つかはその場の運で、今の鍵の 1 通が届く +/// とは限らない。 +/// +/// iOS の NSE が Misskey の縮退した通知を引き直す仕組み(#1215・ +/// `NotificationService.swift` の `DegradedRefetch`)と同じ守りを持つ: +/// +/// - 作られてから [freshness] 以内の通知だけを採る(古い通知を新着として +/// 出さない) +/// - 出した通知の id を [shownIdsLimit] 件まで控え、同じ通知を二度出さない。 +/// 復号できた通知の id も [noteShown] で控える(取り直しと二重にならない) +/// +/// ⚠ 対象は Mastodon 系(Akkoma を含む・保存先が `mastodon://`)だけ。 +/// トークンは本体の [AccountStorage] から読む(Android はアプリ本体の Dart が +/// バックグラウンドで動くので、iOS の NSE のような写しは要らない)。 +class MastodonPushRefetch { + MastodonPushRefetch._(); + + /// 採る通知の新しさ。iOS の NSE と同じ。 + static const freshness = Duration(seconds: 60); + + /// 控えておく id の数。iOS の NSE と同じ。 + static const shownIdsLimit = 8; + + static const _shownIdsPrefix = 'capsicum_push_shown_ids_'; + + /// 失敗の記録のコード。末尾に失敗の種類が付く(`.network` など)。 + static const failureCode = 'dispatch.refetch_failed'; + + /// テストで差し替える。 + @visibleForTesting + static Dio Function() dioFactory = () => Dio( + BaseOptions( + connectTimeout: const Duration(seconds: 8), + receiveTimeout: const Duration(seconds: 8), + ), + ); + + /// テストで差し替える。 + @visibleForTesting + static Future Function(String storageKey) tokenReader = _readToken; + + static Future _readToken(String storageKey) async { + final secrets = await AccountStorage().getSecrets(storageKey); + return secrets?['access_token']; + } + + /// [account](`username@host`)の最新の通知を引き、使えるなら中身を返す。 + /// 使えない・引けないときは null(呼び出し側は汎用の文面のまま出す)。 + static Future fetchLatest( + String account, { + DateTime Function() now = DateTime.now, + }) async { + final at = account.lastIndexOf('@'); + if (at <= 0 || at == account.length - 1) return null; + final host = account.substring(at + 1); + + final String? token; + try { + token = await tokenReader('mastodon://$account'); + } catch (_) { + await _fail('token', host); + return null; + } + // Mastodon 系のアカウントでない(Misskey など)か、ログインしていない。 + // ⚠ 失敗として記録しない —— 対象外なだけ。 + if (token == null || token.isEmpty) return null; + + final Object? data; + try { + final response = await dioFactory().get( + 'https://$host/api/v1/notifications', + queryParameters: {'limit': 1}, + options: Options(headers: {'Authorization': 'Bearer $token'}), + ); + data = response.data; + } on DioException catch (e) { + final status = e.response?.statusCode; + await _fail(status != null ? 'http_$status' : 'network', host); + return null; + } catch (_) { + await _fail('network', host); + return null; + } + + if (data is! List) { + await _fail('parse', host); + return null; + } + // 0 件は失敗ではない(通知を消した直後など)。汎用の文面のまま。 + if (data.isEmpty) return null; + final latest = data.first; + if (latest is! Map) { + await _fail('parse', host); + return null; + } + return accept(latest, account: account, now: now()); + } + + /// 引いた通知を使ってよいかを決め、使うなら中身を返す(控えにも足す)。 + @visibleForTesting + static Future accept( + Map notification, { + required String account, + required DateTime now, + }) async { + final id = notification['id']; + if (id is! String || id.isEmpty) return null; + if (!isFresh(notification, now)) return null; + if (await _wasShown(id, account)) return null; + await noteShown(id, account); + return contentFromNotification(notification); + } + + /// 作られてから [freshness] 以内か。日時が読めなければ false。 + @visibleForTesting + static bool isFresh(Map notification, DateTime now) { + final raw = notification['created_at']; + if (raw is! String) return false; + final createdAt = DateTime.tryParse(raw); + if (createdAt == null) return false; + final age = now.toUtc().difference(createdAt.toUtc()); + return age <= freshness; + } + + /// Mastodon の通知(`GET /api/v1/notifications` の 1 件)を、プッシュを + /// 復号したときと同じ形に直す。 + /// + /// 見出しは呼び出し側が `type` から作るので、ここでは本文だけを組む: + /// - 投稿がある → CW があれば CW の見出しだけ(本文は出さない・#1282 と同じ)、 + /// 無ければ投稿の本文 + /// - 投稿が無い(フォローなど)→ 相手の表示名(空なら `@acct`) + @visibleForTesting + static DecryptedPushContent contentFromNotification( + Map notification, + ) { + final type = notification['type']; + String? body; + final status = notification['status']; + if (status is Map) { + final spoiler = status['spoiler_text']; + if (spoiler is String && spoiler.trim().isNotEmpty) { + body = spoiler.trim(); + } else { + final content = status['content']; + if (content is String) body = stripHtml(content).trim(); + } + } + if (body == null || body.isEmpty) { + final from = notification['account']; + if (from is Map) { + final name = from['display_name']; + final acct = from['acct']; + if (name is String && name.trim().isNotEmpty) { + body = name.trim(); + } else if (acct is String && acct.isNotEmpty) { + body = '@$acct'; + } + } + } + return DecryptedPushContent( + body: (body == null || body.isEmpty) ? null : body, + type: type is String ? type : null, + notificationId: notification['id'] as String?, + ); + } + + /// 通知を出した(または引き直しで使った)ことを控える。 + static Future noteShown(String id, String account) async { + try { + final prefs = await SharedPreferences.getInstance(); + final key = '$_shownIdsPrefix$account'; + final ids = List.of(prefs.getStringList(key) ?? const []) + ..remove(id) + ..add(id); + if (ids.length > shownIdsLimit) { + ids.removeRange(0, ids.length - shownIdsLimit); + } + await prefs.setStringList(key, ids); + } catch (_) { + // 控えられなくても通知は出す(二重に出るほうが、出ないよりよい)。 + } + } + + static Future _wasShown(String id, String account) async { + try { + final prefs = await SharedPreferences.getInstance(); + return prefs.getStringList('$_shownIdsPrefix$account')?.contains(id) ?? + false; + } catch (_) { + return false; + } + } + + static Future _fail(String kind, String host) async { + debugPrint('capsicum: push.refetch: failed ($kind)'); + await PushFailureRecorder.record('$failureCode.$kind', host: host); + } +} diff --git a/packages/capsicum/lib/src/service/push_message_dispatcher.dart b/packages/capsicum/lib/src/service/push_message_dispatcher.dart index 4d6e69204..f52464e68 100644 --- a/packages/capsicum/lib/src/service/push_message_dispatcher.dart +++ b/packages/capsicum/lib/src/service/push_message_dispatcher.dart @@ -10,6 +10,7 @@ import '../ui/util/notification_type_display.dart'; import '../util/chat_attachment_label.dart'; import '../util/exception_scrub.dart'; import '../util/sentry_tag_hash.dart'; +import 'mastodon_push_refetch.dart'; import 'notification_init.dart'; import 'notification_label_cache.dart'; import 'push_failure_recorder.dart'; @@ -90,6 +91,12 @@ class PushMessageDispatcher { final decrypted = await _tryDecrypt(account, data); if (decrypted != null) { + // 出した通知の id を控える (#1426)。古い鍵の 1 通を引き直したときに、 + // 復号できて出した通知と二重にならないように。 + final notificationId = decrypted.notificationId; + if (notificationId != null) { + await MastodonPushRefetch.noteShown(notificationId, account); + } // 用語統一: Mastodon サーバー生成 title の「返信」等は UI と表記揺れ // するので、notification_type から capsicum 規定のラベルを作る。 // type が取れないケースのみサーバー title を fallback に使う。 @@ -289,7 +296,13 @@ class PushMessageDispatcher { elapsedMs: elapsed(), decryptError: e.runtimeType.toString(), ); - return null; + // 上流に古い購読が残っていると、古い鍵の 1 通が relay の重複の抑止を + // 通り抜けて届く (#1426)。最新の通知を API で引き直して中身を出す。 + // ⚠ 鍵が無い・base64 が壊れている経路では引き直さない(鍵が合わない + // 1 通だけが、別の購読から来た同じ通知である見込みが高い)。 + final refetched = await MastodonPushRefetch.fetchLatest(account); + _trace('refetch ${refetched != null ? 'ok' : 'unused'}'); + return refetched; } } diff --git a/packages/capsicum/lib/src/service/push_muted_alerts.dart b/packages/capsicum/lib/src/service/push_muted_alerts.dart new file mode 100644 index 000000000..89de07833 --- /dev/null +++ b/packages/capsicum/lib/src/service/push_muted_alerts.dart @@ -0,0 +1,74 @@ +import 'dart:convert'; + +import 'package:capsicum_core/capsicum_core.dart'; +import 'package:flutter/foundation.dart'; + +import '../util/shared_preferences_cache.dart'; + +/// アカウントごとに、プッシュ通知で受け取らない通知の分類 (#1411)。 +/// +/// 値は `{storageKey: [分類の名前…]}` の JSON。**端末ごと**の設定(#1408 の +/// [PushDisabledAccounts] と同じ理由・プッシュの登録は端末ごと)。バックアップでは +/// 端末固有の側(`deviceLocalKeys`)。 +/// +/// ⚠ 効くのはサーバー側で絞れるアカウントだけ +/// ([PushSubscriptionSupport.supportsPushAlertFilter])。 +class PushMutedAlerts { + PushMutedAlerts._(); + + /// ⚠ `settings_backup_coverage_test.dart` がこの形で拾う。名前を変えない。 + static const prefsKey = 'push_muted_alert_categories'; + + static Map> _readAll() { + final raw = sharedPrefsOrThrow.getString(prefsKey); + if (raw == null) return {}; + final decoded = jsonDecode(raw); + if (decoded is! Map) return {}; + return { + for (final e in decoded.entries) + if (e.key is String && e.value is List) + e.key as String: [ + for (final v in e.value as List) + if (v is String) v, + ], + }; + } + + /// [storageKey] で受け取らない分類。読めなければ空(=今どおり全部受ける)。 + static Set mutedFor(String storageKey) { + try { + final names = _readAll()[storageKey] ?? const []; + return { + for (final c in PushAlertCategory.values) + if (names.contains(c.name)) c, + }; + } catch (e) { + debugPrint('capsicum: push.muted: read failed: ${e.runtimeType}'); + return const {}; + } + } + + static Future setMuted( + String storageKey, + Set muted, + ) async { + final all = _readAll(); + if (muted.isEmpty) { + if (all.remove(storageKey) == null) return; + } else { + all[storageKey] = [for (final c in muted) c.name]..sort(); + } + await (all.isEmpty + ? sharedPrefsOrThrow.remove(prefsKey) + : sharedPrefsOrThrow.setString(prefsKey, jsonEncode(all))); + } + + /// アカウントの削除で捨てる。⚠ **投げない**(削除の途中で止めない)。 + static Future forget(String storageKey) async { + try { + await setMuted(storageKey, const {}); + } catch (e) { + debugPrint('capsicum: push.muted: forget failed: ${e.runtimeType}'); + } + } +} diff --git a/packages/capsicum/lib/src/service/push_registration_service.dart b/packages/capsicum/lib/src/service/push_registration_service.dart index 1fc1842b2..43538e6f2 100644 --- a/packages/capsicum/lib/src/service/push_registration_service.dart +++ b/packages/capsicum/lib/src/service/push_registration_service.dart @@ -22,6 +22,7 @@ import 'fcm_service.dart'; import 'push_device_type.dart'; import 'push_disabled_accounts.dart'; import 'push_key_store.dart'; +import 'push_muted_alerts.dart'; import 'push_registration_status.dart'; import 'push_relay_client.dart'; import 'wns_service.dart'; @@ -434,6 +435,8 @@ class PushRegistrationService { endpoint: endpoint, p256dh: keys.p256dh, auth: keys.auth, + // 利用者が切った通知の分類 (#1411)。絞れないサーバーは無視する。 + mutedCategories: PushMutedAlerts.mutedFor(accountKey), ); } diff --git a/packages/capsicum/lib/src/service/settings_backup.dart b/packages/capsicum/lib/src/service/settings_backup.dart index 8684f6327..228fca740 100644 --- a/packages/capsicum/lib/src/service/settings_backup.dart +++ b/packages/capsicum/lib/src/service/settings_backup.dart @@ -191,6 +191,8 @@ const deviceLocalKeys = { // スマホでは受けるがタブレットでは受けない、を成り立たせる。⚠ 持ち込むと、 // 取り込み先の端末で黙って通知が止まる。 'push_disabled_accounts', + // プッシュ通知で受け取らない通知の分類 (#1411)。上と同じ理由で端末ごと。 + 'push_muted_alert_categories', }; /// **意図的に**書き出さない、アカウントごとの設定 (#857 / #1119)。 diff --git a/packages/capsicum/lib/src/ui/screen/avatar_decoration_screen.dart b/packages/capsicum/lib/src/ui/screen/avatar_decoration_screen.dart index abeb9d017..8f4039b6e 100644 --- a/packages/capsicum/lib/src/ui/screen/avatar_decoration_screen.dart +++ b/packages/capsicum/lib/src/ui/screen/avatar_decoration_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../provider/account_manager_provider.dart'; import '../../provider/list_fetch.dart'; import '../../service/sentry_op_failure.dart'; +import '../../util/exception_scrub.dart'; import '../../util/misskey_api_error.dart'; import '../../util/oauth_scope_error.dart'; import '../util/op_error.dart'; @@ -41,6 +42,53 @@ final avatarDecorationLimitProvider = FutureProvider.autoDispose(( } }, dependencies: [currentAdapterProvider, currentAccountProvider]); +/// 実況のためにモロヘイヤが付けたデコ (#1409)。実況中でなければ null。 +/// +/// ⚠ **読めなければ null(何も出さない)。**モロヘイヤが無い・5.48.0 より前・ +/// 一過性の失敗のどれでも、デコの画面そのものは使える。⚠ 404(口が無い)は +/// サービスが null にするので、ここに来る例外は一過性のものだけ。 +final liveDecorationProvider = + FutureProvider.autoDispose((ref) async { + final adapter = ref.watch(currentAdapterProvider); + final account = ref.watch(currentAccountProvider); + final mulukhiya = account?.mulukhiya; + if (adapter is! AvatarDecorationSupport || + account == null || + mulukhiya == null) { + return null; + } + try { + final status = await mulukhiya.getLiveDecoration( + accessToken: account.userSecret.accessToken, + ); + return status != null && status.live ? status : null; + } catch (e) { + debugLogException('live decoration fetch failed', e); + return null; + } + }, dependencies: [currentAdapterProvider, currentAccountProvider]); + +/// 実況中のデコの帯の文面 (#1409)。 +/// +/// 「実況のために付いています」と、分かれば番組名・外れる予定の時刻を添える。 +/// ⚠ 外れる時刻は端末の時刻帯で出す(サーバーは +09:00 で返す)。 +String liveDecorationBannerText(MulukhiyaLiveDecoration live) { + final name = live.name; + final program = live.program; + final restoreAt = live.restoreAt?.toLocal(); + final head = name == null ? '実況中のデコが付いています' : '「$name」は実況中のデコです'; + final parts = [ + head, + if (program != null) '($program)', + if (restoreAt != null) + '。${restoreAt.hour}:${restoreAt.minute.toString().padLeft(2, '0')}' + 'ごろ、番組の終わりに外れます。' + else + '。番組の終わりに外れます。', + ]; + return parts.join(); +} + /// 一覧の上に出す、あといくつ付けられるか (#1359)。上限が読めなければ null。 /// /// ⚠ 上限が 1 のサーバーでは、付けると入れ替わる(#1349)。「あと 0 個」と @@ -172,6 +220,51 @@ class _AvatarDecorationScreenState } } + /// 実況のために付いたデコを、番組の終わりを待たずに外す (#1409)。 + /// + /// 外したあとはサーバー側でデコが変わっているので、自分のユーザーを引き + /// 直して手元とアカウントへ反映する([_run] と同じ書き戻し先)。 + bool _restoringLive = false; + + Future _restoreLive() async { + if (_restoringLive || _savingId != null) return; + final account = ref.read(currentAccountProvider); + final mulukhiya = account?.mulukhiya; + if (account == null || mulukhiya == null) return; + final messenger = ScaffoldMessenger.of(context); + final accounts = ref.read(accountManagerProvider.notifier); + setState(() => _restoringLive = true); + try { + await mulukhiya.restoreLiveDecoration( + accessToken: account.userSecret.accessToken, + ); + if (!mounted) return; + ref.invalidate(liveDecorationProvider); + // ⚠ 外すのは済んでいる。引き直しの失敗を「外せませんでした」にしない + // (次に開いたとき・アカウントの再取得で揃う)。 + try { + final user = await account.adapter.getMyself(); + accounts.updateUserOf(account.key, user); + if (mounted) setState(() => _localUser = user); + } catch (e) { + debugLogException('refetch after live decoration restore failed', e); + } + } catch (e, st) { + reportOpFailure( + tagKey: 'avatar_decoration.op', + operation: 'restore_live', + error: e, + stackTrace: st, + account: account, + ); + messenger.showSnackBar( + SnackBar(content: Text('外せませんでした\n${summarizeOpError(e)}')), + ); + } finally { + if (mounted) setState(() => _restoringLive = false); + } + } + Future _toggle(AvatarDecorationOption option, bool attached) => _run( option, attached @@ -225,6 +318,8 @@ class _AvatarDecorationScreenState attached: attachedById.length, limit: limit, ); + // 実況のために付いたデコ (#1409)。⚠ 読めなければ null で、帯を出さない。 + final live = ref.watch(liveDecorationProvider).valueOrNull; return Scaffold( appBar: AppBar(title: const Text('アイコンデコレーション')), body: BottomSafeArea( @@ -235,6 +330,12 @@ class _AvatarDecorationScreenState padding: const EdgeInsets.all(24), child: UserAvatar(user: user, size: 96), ), + if (live != null) + _LiveDecorationBanner( + live: live, + restoring: _restoringLive, + onRestore: _savingId != null ? null : _restoreLive, + ), if (remaining != null) Padding( padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), @@ -262,7 +363,13 @@ class _AvatarDecorationScreenState final option = list[index]; final decoration = attachedById[option.id]; final attached = decoration != null; - final description = option.description; + // ⚠ 実況のために付いたものは行でも示す(どれが外れるかが + // 一覧で分かるように・#1409)。 + final isLive = + attached && live?.id != null && live!.id == option.id; + final description = isLive + ? '実況中(番組の終わりに外れます)' + : option.description; return ListTile( leading: Image.network( option.url, @@ -327,6 +434,64 @@ class _AvatarDecorationScreenState } } +/// 実況のために付いたデコの帯 (#1409)。外れる予定と、待たずに外す操作。 +/// +/// ⚠ 外す相手が分からない(実況を始める前から同じデコを付けていた)ときは +/// 「外す」を出さない([MulukhiyaLiveDecoration.restorable])。 +class _LiveDecorationBanner extends StatelessWidget { + const _LiveDecorationBanner({ + required this.live, + required this.restoring, + required this.onRestore, + }); + + final MulukhiyaLiveDecoration live; + final bool restoring; + final VoidCallback? onRestore; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Card( + key: const ValueKey('live-decoration-banner'), + margin: const EdgeInsets.fromLTRB(16, 0, 16, 12), + color: theme.colorScheme.secondaryContainer, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 8, 12), + child: Row( + children: [ + Icon(Icons.live_tv, color: theme.colorScheme.onSecondaryContainer), + const SizedBox(width: 12), + Expanded( + child: Text( + liveDecorationBannerText(live), + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSecondaryContainer, + ), + ), + ), + if (live.restorable) + restoring + ? const Padding( + padding: EdgeInsets.all(12), + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ) + : TextButton( + key: const ValueKey('live-decoration-restore'), + onPressed: onRestore, + child: const Text('いま外す'), + ), + ], + ), + ), + ); + } +} + /// デコレーション 1 つの位置・角度・反転を調整するシート (#1359)。決めたら /// 新しい値を返し、やめたら null。 /// diff --git a/packages/capsicum/lib/src/ui/screen/clip_favorites_screen.dart b/packages/capsicum/lib/src/ui/screen/clip_favorites_screen.dart new file mode 100644 index 000000000..dacb8f612 --- /dev/null +++ b/packages/capsicum/lib/src/ui/screen/clip_favorites_screen.dart @@ -0,0 +1,85 @@ +import 'package:capsicum_core/capsicum_core.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../provider/clip_provider.dart'; +import '../../util/oauth_scope_error.dart'; +import '../widget/bottom_safe_area.dart'; +import '../widget/retry_error_view.dart'; + +/// お気に入りに入れたクリップ (#1377)。入口はクリップのクイックチューザの奥 +/// (#805 の基準・クリップと同じ場所)。 +/// +/// ほかの人のクリップなので、誰のクリップかを添える。 +class ClipFavoritesScreen extends ConsumerWidget { + const ClipFavoritesScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final clips = ref.watch(favoriteClipsProvider); + return Scaffold( + appBar: AppBar(title: const Text('お気に入りのクリップ')), + body: BottomSafeArea( + child: clips.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, _) => RetryErrorView( + // ⚠ 旧トークン(`read:clip-favorite` が無い)は再ログインを案内する。 + message: isOAuthScopeError(e) + ? oauthScopeErrorMessage + : '読み込みに失敗しました', + isRetrying: clips.isLoading, + onRetry: () => ref.invalidate(favoriteClipsProvider), + ), + data: (list) { + if (list.isEmpty) { + return const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Text( + 'お気に入りのクリップはありません。' + 'ほかの人のクリップを開いて、☆ から入れられます。', + textAlign: TextAlign.center, + ), + ), + ); + } + return RefreshIndicator( + onRefresh: () => ref.refresh(favoriteClipsProvider.future), + child: ListView( + children: [ + for (final clip in list) _FavoriteClipTile(clip: clip), + ], + ), + ); + }, + ), + ), + ); + } +} + +class _FavoriteClipTile extends StatelessWidget { + const _FavoriteClipTile({required this.clip}); + + final NoteClip clip; + + @override + Widget build(BuildContext context) { + final owner = clip.ownerName; + final description = clip.description; + final sub = [ + ?owner, + if (description != null && description.isNotEmpty) description, + ].join(' · '); + return ListTile( + key: ValueKey('favorite-clip-${clip.id}'), + leading: const Icon(Icons.star_outline), + title: Text(clip.name), + subtitle: sub.isEmpty + ? null + : Text(sub, maxLines: 2, overflow: TextOverflow.ellipsis), + onTap: () => context.push('/clip/${clip.id}', extra: clip), + ); + } +} diff --git a/packages/capsicum/lib/src/ui/screen/clip_notes_screen.dart b/packages/capsicum/lib/src/ui/screen/clip_notes_screen.dart index a92c7f828..2b0565fbc 100644 --- a/packages/capsicum/lib/src/ui/screen/clip_notes_screen.dart +++ b/packages/capsicum/lib/src/ui/screen/clip_notes_screen.dart @@ -4,6 +4,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../provider/account_manager_provider.dart'; import '../../provider/clip_provider.dart'; +import '../../service/sentry_op_failure.dart'; +import '../../util/oauth_scope_error.dart'; import '../util/scroll_thresholds.dart'; import '../widget/bottom_safe_area.dart'; import '../widget/clip_actions_sheet.dart'; @@ -61,6 +63,8 @@ class _ClipNotesScreenState extends ConsumerState { title: Text(clip?.name ?? widget.clipName ?? 'クリップ'), backgroundColor: Theme.of(context).colorScheme.inversePrimary, actions: [ + // ほかの人のクリップなら、お気に入りに入れる / 外す (#1377)。 + if (clip == null) _ClipFavoriteButton(clipId: widget.clipId), if (canManage && clip != null) IconButton( icon: const Icon(Icons.more_horiz), @@ -106,3 +110,89 @@ class _ClipNotesScreenState extends ConsumerState { ); } } + +/// ほかの人のクリップを、お気に入りに入れる / 外す (#1377)。 +/// +/// - 自分のクリップ・状態が読めないとき([clipDetailProvider] が null か失敗)は +/// 出さない +/// - 押したらすぐ見た目を変え(楽観更新)、失敗したら戻す(ギャラリーのいいねと +/// 同じ形)。既に入っていた / もう外れていたは、アダプターが成功にする +/// - 旧トークン(`write:clip-favorite` が無い)の 403 は、再ログインを案内する +class _ClipFavoriteButton extends ConsumerStatefulWidget { + const _ClipFavoriteButton({required this.clipId}); + + final String clipId; + + @override + ConsumerState<_ClipFavoriteButton> createState() => + _ClipFavoriteButtonState(); +} + +class _ClipFavoriteButtonState extends ConsumerState<_ClipFavoriteButton> { + /// 押したあとの値。null なら [clipDetailProvider] の値を出す。 + bool? _favorited; + bool _busy = false; + + Future _toggle(bool wasFavorited) async { + if (_busy) return; + final raw = ref.read(currentAdapterProvider); + if (raw is! ClipFavoriteSupport) return; + final support = raw as ClipFavoriteSupport; + final account = ref.accountForReport; + final messenger = ScaffoldMessenger.of(context); + setState(() { + _busy = true; + _favorited = !wasFavorited; + }); + try { + if (wasFavorited) { + await support.unfavoriteClip(widget.clipId); + } else { + await support.favoriteClip(widget.clipId); + } + // お気に入りの一覧を取り直させる(次に開いたとき揃うように)。 + ref.invalidate(favoriteClipsProvider); + } catch (e, st) { + if (mounted) setState(() => _favorited = wasFavorited); + if (e is ClipNotFound) { + messenger.showSnackBar( + const SnackBar(content: Text('このクリップはもう見られません')), + ); + } else if (isOAuthScopeError(e)) { + messenger.showSnackBar( + const SnackBar(content: Text(oauthScopeErrorMessage)), + ); + } else { + reportOpFailure( + tagKey: 'clip.op', + operation: wasFavorited ? 'unfavorite' : 'favorite', + error: e, + stackTrace: st, + account: account, + ); + messenger.showSnackBar( + const SnackBar(content: Text('お気に入りを更新できませんでした')), + ); + } + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext context) { + final detail = ref.watch(clipDetailProvider(widget.clipId)).valueOrNull; + final me = ref.watch(currentAccountProvider)?.user.id; + // ⚠ 自分のクリップには出さない(一覧に無くても、持ち主が自分なら自分のもの)。 + if (detail == null || detail.userId == null || detail.userId == me) { + return const SizedBox.shrink(); + } + final favorited = _favorited ?? detail.isFavorited ?? false; + return IconButton( + key: const ValueKey('clip-favorite'), + icon: Icon(favorited ? Icons.star : Icons.star_border), + tooltip: favorited ? 'お気に入りから外す' : 'お気に入りに入れる', + onPressed: _busy ? null : () => _toggle(favorited), + ); + } +} diff --git a/packages/capsicum/lib/src/ui/screen/gallery_detail_screen.dart b/packages/capsicum/lib/src/ui/screen/gallery_detail_screen.dart index f7bf09999..6d752955f 100644 --- a/packages/capsicum/lib/src/ui/screen/gallery_detail_screen.dart +++ b/packages/capsicum/lib/src/ui/screen/gallery_detail_screen.dart @@ -6,6 +6,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import '../../provider/account_manager_provider.dart'; +import '../../provider/gallery_provider.dart'; import '../../service/sentry_op_failure.dart'; import '../../util/misskey_api_error.dart'; import '../../util/oauth_scope_error.dart'; @@ -170,8 +171,12 @@ class _GalleryLikeButton extends ConsumerStatefulWidget { } class _GalleryLikeButtonState extends ConsumerState<_GalleryLikeButton> { - late bool _isLiked = widget.post.isLiked ?? false; - late int _likedCount = widget.post.likedCount; + // ⚠ 前に詳細で変えていれば、その写しを使う(#1420・一覧の投稿は取得時のまま)。 + late final GalleryLike? _remembered = ref.read( + galleryLikeOverridesProvider, + )[widget.post.id]; + late bool _isLiked = _remembered?.isLiked ?? widget.post.isLiked ?? false; + late int _likedCount = _remembered?.likedCount ?? widget.post.likedCount; bool _toggling = false; Future _toggle() async { @@ -180,6 +185,12 @@ class _GalleryLikeButtonState extends ConsumerState<_GalleryLikeButton> { if (raw is! GallerySupport) return; final gallery = raw as GallerySupport; final account = ref.accountForReport; + // ⚠ 写しの書き先は先に取っておく。応答の前に詳細を閉じると `ref` が + // 使えなくなるが、そこで書けないと「押してすぐ戻る」がまさに取りこぼす。 + final overrides = ref.read(galleryLikeOverridesProvider.notifier); + void remember(bool isLiked, int likedCount) => overrides.update( + (m) => {...m, widget.post.id: (isLiked: isLiked, likedCount: likedCount)}, + ); final wasLiked = _isLiked; setState(() { @@ -187,16 +198,25 @@ class _GalleryLikeButtonState extends ConsumerState<_GalleryLikeButton> { _isLiked = !wasLiked; _likedCount += wasLiked ? -1 : 1; }); + // 押したあとの見た目(楽観更新の値)。成功したら写しへ残す。 + final likedAfter = !wasLiked; + final countAfter = _likedCount; try { if (wasLiked) { await gallery.unlikeGalleryPost(widget.post.id); } else { await gallery.likeGalleryPost(widget.post.id); } + remember(likedAfter, countAfter); } catch (e, st) { final code = misskeyApiErrorCode(e); if ((!wasLiked && code == 'ALREADY_LIKED') || (wasLiked && code == 'NOT_LIKED')) { + // サーバーの状態と揃っただけ。⚠ 件数は数え直せないので、押す前の値に + // 戻す(もともとその状態だった=件数にはもう含まれている)。 + final settled = wasLiked ? countAfter + 1 : countAfter - 1; + remember(likedAfter, settled); + if (mounted) setState(() => _likedCount = settled); return; } if (!mounted) return; diff --git a/packages/capsicum/lib/src/ui/screen/home_screen.dart b/packages/capsicum/lib/src/ui/screen/home_screen.dart index a46218365..801e02f09 100644 --- a/packages/capsicum/lib/src/ui/screen/home_screen.dart +++ b/packages/capsicum/lib/src/ui/screen/home_screen.dart @@ -29,6 +29,7 @@ import '../../url_helper.dart'; import '../../util/startup_trace.dart'; import '../util/deck_navigation.dart'; import '../util/deck_notification_fallback.dart'; +import '../util/deck_tabs.dart'; import '../util/keyboard_list_navigation.dart'; import '../util/mouse_drag_scroll_behavior.dart'; import '../util/offline_account_display.dart'; diff --git a/packages/capsicum/lib/src/ui/screen/mulukhiya_handlers_screen.dart b/packages/capsicum/lib/src/ui/screen/mulukhiya_handlers_screen.dart index 566b7aa83..0a125d5ac 100644 --- a/packages/capsicum/lib/src/ui/screen/mulukhiya_handlers_screen.dart +++ b/packages/capsicum/lib/src/ui/screen/mulukhiya_handlers_screen.dart @@ -2,6 +2,7 @@ import 'package:capsicum_core/capsicum_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../model/account_key.dart'; import '../../provider/account_manager_provider.dart'; import '../../service/sentry_op_failure.dart'; import '../widget/bottom_safe_area.dart'; @@ -59,12 +60,32 @@ class _MulukhiyaHandlersScreenState final _busy = {}; /// 切り替えたあとの値(一覧を取り直すまで画面に反映する)。 + /// + /// ⚠ **[_overridesAccount] のアカウントのもの**(#1420)。キーはハンドラー名 + /// だけなので、画面を開いたままアカウントを切り替えると、前のアカウントの + /// 上書きが新しいアカウントの一覧に乗っていた。 final _overrides = {}; + AccountKey? _overridesAccount; + + /// [_overrides] を [key] のアカウントのものにする。変わったら捨てる。 + void _adoptAccount(AccountKey? key) { + if (key == _overridesAccount) return; + _overrides.clear(); + _overridesAccount = key; + } + + /// [key] のアカウントの上書きとして書く。⚠ 応答が届く前にアカウントが + /// 切り替わっていたら書かない(新しいアカウントの一覧に乗せない)。 + void _setOverride(AccountKey key, String handler, bool disabled) { + if (!mounted || key != _overridesAccount) return; + setState(() => _overrides[handler] = disabled); + } Future _toggle(MulukhiyaUserHandler handler, bool enabled) async { final account = ref.read(currentAccountProvider); final mulukhiya = account?.mulukhiya; if (account == null || mulukhiya == null || _busy.isNotEmpty) return; + _adoptAccount(account.key); // ⚠ 戻す先は一覧を取った時点の値ではなく、いま画面に出ている値(直前に // 成功した切り替えを含む)。 final before = _overrides[handler.name] ?? handler.disabled; @@ -78,7 +99,7 @@ class _MulukhiyaHandlersScreenState handler: handler.name, disabled: !enabled, ); - if (mounted) setState(() => _overrides[handler.name] = disabled); + _setOverride(account.key, handler.name, disabled); } catch (e, st) { reportOpFailure( tagKey: 'handler.op', @@ -89,7 +110,7 @@ class _MulukhiyaHandlersScreenState ); if (!mounted) return; // 送る前の値へ戻す。 - setState(() => _overrides[handler.name] = before); + _setOverride(account.key, handler.name, before); ScaffoldMessenger.of( context, ).showSnackBar(const SnackBar(content: Text('切り替えられませんでした'))); @@ -100,6 +121,8 @@ class _MulukhiyaHandlersScreenState @override Widget build(BuildContext context) { + // ⚠ アカウントが替わっていたら、前のアカウントの上書きを捨てる(#1420)。 + _adoptAccount(ref.watch(currentAccountProvider)?.key); final handlersAsync = ref.watch(mulukhiyaUserHandlersProvider); return Scaffold( appBar: AppBar(title: const Text('投稿の自動処理')), diff --git a/packages/capsicum/lib/src/ui/screen/profile_screen.dart b/packages/capsicum/lib/src/ui/screen/profile_screen.dart index a5548b3ea..1deae67dd 100644 --- a/packages/capsicum/lib/src/ui/screen/profile_screen.dart +++ b/packages/capsicum/lib/src/ui/screen/profile_screen.dart @@ -15,6 +15,7 @@ import '../../provider/is_cat_provider.dart'; import '../../provider/preferences_provider.dart'; import '../../provider/server_config_provider.dart'; import '../../provider/supporter_status_provider.dart'; +import '../../service/info_bot_follow_keeper.dart'; import '../../service/server_version_checker.dart'; import '../../service/tco_resolver.dart'; import '../../url_helper.dart'; @@ -44,7 +45,7 @@ import '../widget/user_avatar.dart'; /// プロフィール画面のタブ種別。表示するタブ集合は adapter のケーパビリティと /// Mastodon 4.6 の show_media 設定(#732)で動的に決まるため、位置インデックスの /// 直書きをやめ、この列挙で意味付けする。 -enum _ProfileTab { posts, media, gallery, pages } +enum _ProfileTab { posts, media, gallery, pages, clips } /// 相手が、開いているアカウント([accountHost])と同じサーバーの人か。 /// host が無い(空も含む)相手は同じサーバーとして扱い、host は大文字小文字を @@ -152,8 +153,17 @@ class _ProfileScreenState extends ConsumerState bool _hasMorePages = true; bool _pagesTabLoaded = false; + // その人の公開のクリップ (#1377)。 + List _clips = []; + bool _loadingClips = true; + bool _loadingMoreClips = false; + bool _hasMoreClips = true; + bool _clipsTabLoaded = false; + bool get _hasGalleryTab => ref.read(currentAdapterProvider) is GallerySupport; bool get _hasPagesTab => ref.read(currentAdapterProvider) is PagesSupport; + bool get _hasClipsTab => + ref.read(currentAdapterProvider) is ClipFavoriteSupport; /// 表示するタブの順序付きリスト。adapter のケーパビリティに加え、Mastodon 4.6 /// の show_media 設定(#732)でメディアタブの有無が決まる。show_media が未対応 @@ -163,6 +173,7 @@ class _ProfileScreenState extends ConsumerState if (_user.showMedia != false) _ProfileTab.media, if (_hasGalleryTab) _ProfileTab.gallery, if (_hasPagesTab) _ProfileTab.pages, + if (_hasClipsTab) _ProfileTab.clips, ]; static const _tabLabels = <_ProfileTab, String>{ @@ -170,6 +181,7 @@ class _ProfileScreenState extends ConsumerState _ProfileTab.media: 'メディア', _ProfileTab.gallery: 'ギャラリー', _ProfileTab.pages: 'ページ', + _ProfileTab.clips: 'クリップ', }; UserRelationship? _relationship; @@ -245,6 +257,8 @@ class _ProfileScreenState extends ConsumerState if (!_galleryTabLoaded) _loadGalleryPosts(); case _ProfileTab.pages: if (!_pagesTabLoaded) _loadPages(); + case _ProfileTab.clips: + if (!_clipsTabLoaded) _loadClips(); case _ProfileTab.posts: break; } @@ -276,6 +290,8 @@ class _ProfileScreenState extends ConsumerState _loadMoreGalleryPosts(); case _ProfileTab.pages: _loadMorePages(); + case _ProfileTab.clips: + _loadMoreClips(); } } } @@ -537,7 +553,57 @@ class _ProfileScreenState extends ConsumerState } } + Future _loadClips() async { + final adapter = ref.read(currentAdapterProvider); + if (adapter is! ClipFavoriteSupport) return; + + _clipsTabLoaded = true; + try { + final clips = await (adapter as ClipFavoriteSupport).getUserClips( + widget.user.id, + query: const TimelineQuery(limit: 20), + ); + if (mounted) { + setState(() { + _clips = clips; + _loadingClips = false; + _hasMoreClips = clips.length >= 20; + }); + } + } catch (e) { + _clipsTabLoaded = false; + if (mounted) setState(() => _loadingClips = false); + } + } + + Future _loadMoreClips() async { + if (_loadingMoreClips || !_hasMoreClips || _clips.isEmpty) return; + final adapter = ref.read(currentAdapterProvider); + if (adapter is! ClipFavoriteSupport) return; + + setState(() => _loadingMoreClips = true); + try { + final older = await (adapter as ClipFavoriteSupport).getUserClips( + widget.user.id, + query: TimelineQuery(maxId: _clips.last.id, limit: 20), + ); + if (mounted) { + setState(() { + _clips = [..._clips, ...older]; + _loadingMoreClips = false; + _hasMoreClips = older.length >= 20; + }); + } + } catch (e) { + if (mounted) setState(() => _loadingMoreClips = false); + } + } + Future _loadRelationship() async { + // ⚠ 操作の await 中に画面を閉じると、ここへは dispose 後に来る(#1423)。 + // `_isOwnProfile` も `ref` を読むので、その前に降りる。`_performAction` の + // catch から呼ぶ 2 回目は try の外なので、投げると fatal になる。 + if (!mounted) return; if (_isOwnProfile) return; final adapter = ref.read(currentAdapterProvider); if (adapter == null || adapter is! FollowSupport) return; @@ -551,6 +617,19 @@ class _ProfileScreenState extends ConsumerState } } + /// 開いているのが、自分のサーバーのお知らせボットか (#1402)。 + bool get _isOwnInfoBot { + final host = ref.read(currentAccountProvider)?.key.host; + if (host == null) return false; + return InfoBotFollowKeeper.isOwnInfoBot( + user: widget.user, + infoBotAcct: ref.read(currentMulukhiyaProvider)?.infoBotAcct, + localHost: host, + ); + } + + static const _infoBotLockReason = 'お知らせボットのフォローは外せません'; + Future _performAction(Future Function() action) async { if (_relationshipLoading) return false; setState(() => _relationshipLoading = true); @@ -560,9 +639,11 @@ class _ProfileScreenState extends ConsumerState return true; } catch (e) { if (mounted) { + // サーバーが解除・ブロックを拒んだ (#1402) ならその理由を出す。 + final refusal = InfoBotFollowKeeper.refusalMessage(e); ScaffoldMessenger.of( context, - ).showSnackBar(SnackBar(content: Text('操作に失敗しました'))); + ).showSnackBar(SnackBar(content: Text(refusal ?? '操作に失敗しました'))); } debugLogException('User action error', e); // ⚠ 失敗したときも関係を取り直す(v2.13 のリリース前レビュー)。開いている @@ -779,6 +860,8 @@ class _ProfileScreenState extends ConsumerState return _buildGalleryTab(); case _ProfileTab.pages: return _buildPagesTab(); + case _ProfileTab.clips: + return _buildClipsTab(); } } @@ -1043,6 +1126,56 @@ class _ProfileScreenState extends ConsumerState ]; } + /// その人の公開のクリップ (#1377)。開くと既存のクリップの画面。 + /// + /// ⚠⚠ **開く側のスコープを運ぶ**(`extraWithProviderScope`)。デッキの別アカウントの + /// カラムから開いても、クリップの id をそのアカウントのサーバーで引く + /// (クリップのカラム種別は無いので全画面で開く)。 + List _buildClipsTab() { + if (_loadingClips) { + return [ + const SliverFillRemaining( + child: Center(child: CircularProgressIndicator()), + ), + ]; + } + if (_clips.isEmpty) { + return [ + const SliverFillRemaining(child: Center(child: Text('クリップはありません'))), + ]; + } + return [ + SliverList( + delegate: SliverChildBuilderDelegate((context, index) { + if (index >= _clips.length) { + return const Padding( + padding: EdgeInsets.all(16), + child: Center(child: CircularProgressIndicator()), + ); + } + final clip = _clips[index]; + final description = clip.description; + return ListTile( + key: ValueKey('profile-clip-${clip.id}'), + leading: const Icon(Icons.content_paste), + title: Text(clip.name), + subtitle: description == null || description.isEmpty + ? null + : Text( + description, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + onTap: () => context.push( + '/clip/${clip.id}', + extra: extraWithProviderScope(context, {'clip': clip}), + ), + ); + }, childCount: _clips.length + (_loadingMoreClips ? 1 : 0)), + ), + ]; + } + /// ミュート中の相手には「ミュート中」バッジをプロフィール本体にも出す。 /// 期限付きミュート(Mastodon 4.6, #734)は「〇〇まで」を併記する。 /// 自分のプロフィール・関係性未ロード・非ミュートでは何も出さない。 @@ -1562,9 +1695,13 @@ class _ProfileScreenState extends ConsumerState final boostLabel = ref.read(reblogLabelProvider); final messenger = ScaffoldMessenger.of(context); final followState = followButtonStateOf(rel); + // 自分のサーバーのお知らせボットは、フォローを外させない・ブロックさせない + // (#1402)。⚠ フォローしていないときは「フォロー」を押せるようにする。 + final isInfoBot = _isOwnInfoBot; + final lockFollow = isInfoBot && followState == FollowButtonState.unfollow; final followButton = FilledButton.icon( key: const ValueKey('profile-follow-button'), - onPressed: _relationshipLoading + onPressed: _relationshipLoading || lockFollow ? null : () => _performAction( () => switch (followButtonStateOf(rel)) { @@ -1577,8 +1714,8 @@ class _ProfileScreenState extends ConsumerState FollowButtonState.follow => adapter.followUser(widget.user.id), }, ), - icon: Icon(followState.icon), - label: Text(followState.label), + icon: Icon(lockFollow ? Icons.lock_outline : followState.icon), + label: Text(lockFollow ? 'フォロー中' : followState.label), style: followState != FollowButtonState.follow ? FilledButton.styleFrom( backgroundColor: Theme.of( @@ -1588,10 +1725,16 @@ class _ProfileScreenState extends ConsumerState ) : null, ); - final followTooltip = followState.tooltip; + final followTooltip = lockFollow ? _infoBotLockReason : followState.tooltip; return [ if (followTooltip != null) - Tooltip(message: followTooltip, child: followButton) + Tooltip( + message: followTooltip, + // ⚠ 押せないボタン (#1402) は、軽く押しただけで理由を出す。長押しの + // ままだと、スマホでは押せない理由に辿り着けない。 + triggerMode: lockFollow ? TooltipTriggerMode.tap : null, + child: followButton, + ) else followButton, PopupMenuButton( @@ -1729,7 +1872,9 @@ class _ProfileScreenState extends ConsumerState ), if (rel.blocking) const PopupMenuItem(value: 'unblock', child: Text('ブロック解除')) - else + // お知らせボットはブロックさせない (#1402)。ブロックするとフォローが + // 外れる。⚠ すでにブロックしているなら解除は出す(上の分岐)。 + else if (!isInfoBot) const PopupMenuItem(value: 'block', child: Text('ブロック')), // 通報はミュート / ブロックと同じ「相手への対処」なので隣に置く。 // 投稿の長押しメニューにしか無く、プロフィールから辿れなかった (#998)。 diff --git a/packages/capsicum/lib/src/ui/screen/settings/push_notification_settings_screen.dart b/packages/capsicum/lib/src/ui/screen/settings/push_notification_settings_screen.dart index 4db521abb..db993671a 100644 --- a/packages/capsicum/lib/src/ui/screen/settings/push_notification_settings_screen.dart +++ b/packages/capsicum/lib/src/ui/screen/settings/push_notification_settings_screen.dart @@ -1,3 +1,7 @@ +import 'dart:async'; + +import 'package:capsicum_core/capsicum_core.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -9,8 +13,10 @@ import '../../../provider/push_registration_status_provider.dart'; import '../../../provider/supporter_purchase_provider.dart'; import '../../../service/announcement_subscription_service.dart'; import '../../../service/push_disabled_accounts.dart'; +import '../../../service/push_muted_alerts.dart'; import '../../../service/push_registration_service.dart'; import '../../../service/push_registration_status.dart'; +import '../../util/notification_type_display.dart'; import '../../widget/push_registration_status_section.dart'; import '../../widget/relay_entitlement_purchase_section.dart'; import '../../widget/section_header.dart'; @@ -335,6 +341,9 @@ class _AccountStatusTileState extends ConsumerState<_AccountStatusTile> { state, eligible, snapshot?.reason, + disabledByUser: PushDisabledAccounts.isDisabled( + account.key.toStorageKey(), + ), ); // お知らせ通知 (#477 / #919)。判断は [resolveAnnouncementRow] に集約する。 @@ -371,6 +380,16 @@ class _AccountStatusTileState extends ConsumerState<_AccountStatusTile> { eligible && state != PushRegistrationState.notSupported) _PushEnabledToggle(account: account, eligible: hasPreset), + // 受け取る通知の種類 (#1411)。⚠ サーバー側で絞れるアカウントだけ + // (Mastodon 系)。オフにしているアカウントには出さない(効かない)。 + if (PushRegistrationService.isPushBackendWired && + eligible && + state != PushRegistrationState.notSupported && + account.adapter is PushSubscriptionSupport && + (account.adapter as PushSubscriptionSupport) + .supportsPushAlertFilter && + !PushDisabledAccounts.isDisabled(account.key.toStorageKey())) + _PushAlertTypesTile(account: account, eligible: hasPreset), switch (announcementRow) { AnnouncementRowKind.none => const SizedBox.shrink(), AnnouncementRowKind.toggle => _AnnouncementToggle(account: account), @@ -389,6 +408,136 @@ class _AccountStatusTileState extends ConsumerState<_AccountStatusTile> { } } +/// 受け取る通知の種類 (#1411)。押すとシートで種類ごとに切り替える。 +/// +/// ⚠ 切り替えは閉じたときにまとめて送る(購読し直す)。1 つ切り替えるたびに +/// 送ると、続けて押したときに購読が何度も作り直される。 +class _PushAlertTypesTile extends StatefulWidget { + const _PushAlertTypesTile({required this.account, required this.eligible}); + + final Account account; + + /// [PushRegistrationService.registerAccount] の `eligible`。 + final bool eligible; + + @override + State<_PushAlertTypesTile> createState() => _PushAlertTypesTileState(); +} + +class _PushAlertTypesTileState extends State<_PushAlertTypesTile> { + String get _storageKey => widget.account.key.toStorageKey(); + + Future _open() async { + final before = PushMutedAlerts.mutedFor(_storageKey); + final messenger = ScaffoldMessenger.of(context); + final after = await showModalBottomSheet>( + context: context, + showDragHandle: true, + isScrollControlled: true, + builder: (_) => PushAlertTypesSheet(initialMuted: before), + ); + if (after == null || setEquals(after, before)) return; + try { + await PushMutedAlerts.setMuted(_storageKey, after); + } catch (e) { + debugPrint('capsicum: push.muted: save failed: ${e.runtimeType}'); + messenger.showSnackBar(const SnackBar(content: Text('保存できませんでした'))); + return; + } + if (mounted) setState(() {}); + // サーバー側の絞りを新しい値で張り直す。⚠ 待たない(登録の状況は行に出る)。 + unawaited( + PushRegistrationService.registerAccount( + widget.account, + eligible: widget.eligible, + ), + ); + } + + @override + Widget build(BuildContext context) { + final muted = PushMutedAlerts.mutedFor(_storageKey); + return Padding( + padding: const EdgeInsets.fromLTRB(40, 0, 0, 4), + child: ListTile( + key: ValueKey('push-alert-types-$_storageKey'), + dense: true, + title: const Text('受け取る通知の種類', style: TextStyle(fontSize: 14)), + subtitle: Text( + muted.isEmpty + ? 'すべて' + : '${PushAlertCategory.values.length - muted.length} / ' + '${PushAlertCategory.values.length} 種類', + ), + trailing: const Icon(Icons.chevron_right), + onTap: _open, + ), + ); + } +} + +/// 通知の種類ごとのスイッチ (#1411)。閉じるとき(「完了」)に受け取らない分類を +/// 返す。⚠ 引っ張って閉じたときは null(変えない)。 +@visibleForTesting +class PushAlertTypesSheet extends StatefulWidget { + const PushAlertTypesSheet({super.key, required this.initialMuted}); + + final Set initialMuted; + + @override + State createState() => _PushAlertTypesSheetState(); +} + +class _PushAlertTypesSheetState extends State { + late final Set _muted = {...widget.initialMuted}; + + @override + Widget build(BuildContext context) { + return SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 4), + child: Text( + '受け取る通知の種類', + style: Theme.of(context).textTheme.titleMedium, + ), + ), + const Padding( + padding: EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text( + 'オフにした種類は、サーバーがプッシュ通知を送らなくなります。' + 'アプリの通知の一覧には、これまでどおり出ます。', + style: TextStyle(fontSize: 13), + ), + ), + for (final category in PushAlertCategory.values) + SwitchListTile( + key: ValueKey('push-alert-${category.name}'), + title: Text(pushAlertCategoryLabel(category)), + value: !_muted.contains(category), + onChanged: (on) => setState( + () => on ? _muted.remove(category) : _muted.add(category), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: FilledButton( + key: const ValueKey('push-alert-types-done'), + onPressed: () => Navigator.pop(context, {..._muted}), + child: const Text('完了'), + ), + ), + ], + ), + ), + ); + } +} + /// このアカウントのプッシュ通知を受け取るか (#1408)。 /// /// ⚠ オフにしても relay の行は残す([PushRegistrationService.setAccountEnabled])。 diff --git a/packages/capsicum/lib/src/ui/util/deck_close_unlocked.dart b/packages/capsicum/lib/src/ui/util/deck_close_unlocked.dart index 77e1ad817..6d1766966 100644 --- a/packages/capsicum/lib/src/ui/util/deck_close_unlocked.dart +++ b/packages/capsicum/lib/src/ui/util/deck_close_unlocked.dart @@ -10,9 +10,11 @@ import '../../provider/preferences_provider.dart'; // 使い捨てのカラム(スレッド・プロフィール・検索など)を 1 回で片付ける。 // // - 入口はカラム編集のシートと、メニューバーの「表示 > カラム」 -// (Cmd / Ctrl + Shift + W) +// (Cmd / Ctrl + Shift + W)と、デッキの帯の右端(#1405) // - ロック中が 1 本以上、かつロックしていないカラムが 1 本以上のときだけ // 押せる。条件を満たさないときは隠さず、押せなくする +// - 項目名は [kCloseUnlockedDeckColumnsLabel]、押せない理由は +// [closeUnlockedDisabledReason]。⚠ 入口ごとに文字列を書かない(#1420) // - 確認も「元に戻す」も挟まない。閉じるのは使い捨てのカラムだけで、 // 失っても開き直せる // - 閉じたあとのフォーカスは deckFocusAfterClosingUnlocked @@ -53,11 +55,35 @@ String? deckFocusAfterClosingUnlocked( return null; } +/// 項目名。シート・メニューバー・帯で揃える(#1420)。 +const kCloseUnlockedDeckColumnsLabel = 'ロックしていないカラムを閉じる'; + +/// 押せない理由。押せるときは null(#1420)。 +/// +/// ⚠ **理由は 2 つある。**ロック中が 1 本も無いときと、全部のカラムがロック +/// されていて閉じるものが無いとき。後者に「ロックしたカラムがあると使えます」を +/// 出すと、ロックしてあるのに押せない理由として噛み合わない(v2.14 のリリース前 +/// レビュー)。 +String? closeUnlockedDisabledReason( + List columnIds, + Set locked, +) { + if (unlockedDeckColumnIdsToClose(columnIds, locked).isNotEmpty) return null; + if (columnIds.isNotEmpty && columnIds.every(locked.contains)) { + return 'すべてのカラムがロックされています'; + } + return 'ロックしたカラムがあると使えます'; +} + +/// いまの列で押せない理由。押せるときは null。 +String? closeUnlockedDeckColumnsDisabledReason(WidgetRef ref) => + closeUnlockedDisabledReason([ + for (final c in ref.watch(deckColumnsProvider)) c.id, + ], ref.watch(deckLockedColumnsProvider)); + /// いまの列で押せるか。 -bool canCloseUnlockedDeckColumns(WidgetRef ref) => unlockedDeckColumnIdsToClose( - [for (final c in ref.watch(deckColumnsProvider)) c.id], - ref.watch(deckLockedColumnsProvider), -).isNotEmpty; +bool canCloseUnlockedDeckColumns(WidgetRef ref) => + closeUnlockedDeckColumnsDisabledReason(ref) == null; /// ロックしていないカラムを閉じる。押せないときは何もしない。 /// diff --git a/packages/capsicum/lib/src/ui/util/deck_tabs.dart b/packages/capsicum/lib/src/ui/util/deck_tabs.dart index a278d58df..3b16a5645 100644 --- a/packages/capsicum/lib/src/ui/util/deck_tabs.dart +++ b/packages/capsicum/lib/src/ui/util/deck_tabs.dart @@ -3,10 +3,78 @@ import 'package:capsicum_core/capsicum_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../provider/account_manager_provider.dart'; +import '../../provider/channel_provider.dart'; +import '../../provider/hashtag_provider.dart'; +import '../../provider/list_provider.dart'; import '../../provider/server_config_provider.dart'; import '../../util/action_labels.dart'; import '../screen/post_list_screen.dart'; import '../screen/user_list_screen.dart'; +import 'timeline_type_label.dart'; + +/// タブ / カラムの種別のラベル。[adapter] はそのタブのアカウントのもの。 +/// +/// ⚠ カラムのラベルは [columnTabLabel] / [columnTabLabelInScope] から呼ぶ。 +/// これを直に呼ぶのは、`isMastodon` を自前で持っているタブ UI だけ。 +String tabLabel( + WidgetRef ref, + TabType tab, + bool isMastodon, + DecentralizedBackendAdapter? adapter, + List allLists, +) { + return switch (tab) { + TimelineTab(:final type) => timelineTypeLabel( + ref, + type, + isMastodon: isMastodon, + adapter: adapter, + ), + ListTab(:final id, :final name) => + name ?? allLists.where((l) => l.id == id).firstOrNull?.title ?? id, + HashtagTab(:final tag) => hashtagSpecLabel(tag), + ChannelTab(:final id, :final name) => channelTabLabel(ref, id, name), + NotificationsTab() => '通知', + AnnouncementsTab() => 'お知らせ', + MessagesTab() => 'メッセージ', + final DeckOnlyTab t => deckOnlyTabLabel(ref, t, adapter), + }; +} + +/// カラムの種別のラベルを、[adapter] のアカウントで組む(#1420)。 +/// +/// ⚠⚠ **カラムのラベルはここを通す。**見出し(`deck_column_view.dart`)・ +/// カラム編集のシート(`deck_columns_sheet.dart`)・メニューバーと帯 +/// (`home_menu.dart` の `deckColumnMenuLabel`)の 3 か所が、それぞれ +/// `isMastodon` とリストの引き方を写して持っていた(v2.14 のリリース前レビュー)。 +/// 写しは片方だけ直されてずれる —— 実際にリストを引く条件がシートだけ違っていた。 +String columnTabLabel( + WidgetRef ref, + TabType tab, + DecentralizedBackendAdapter? adapter, + List lists, +) { + final isMastodon = + adapter != null && + !adapter.capabilities.supportedTimelines.contains(TimelineType.social); + return tabLabel(ref, tab, isMastodon, adapter, lists); +} + +/// 周りのスコープ(カラムのアカウント)で [tab] のラベルを出す(#1420)。 +/// +/// 見出しとカラム編集のシートが使う。ルートのスコープで組むメニューバーと帯は +/// `deckColumnMenuLabel` が [columnTabLabel] を直に呼ぶ。 +/// +/// リスト名はキーに持たない(決定済み事項 4)ので、実行時に一覧から引く。 +/// ⚠ リスト以外のカラム・リストに対応しないアカウントで、一覧の取得を起こさない。 +String columnTabLabelInScope(WidgetRef ref, TabType tab) { + final adapter = ref.watch(currentAdapterProvider); + final lists = tab is ListTab && adapter is ListSupport + ? ref.watch(listsProvider).valueOrNull ?? const [] + : const []; + return columnTabLabel(ref, tab, adapter, lists); +} /// デッキ専用のカラム種別([DeckOnlyTab])の見出し・アイコン・取得 (#1148 / #1150)。 /// diff --git a/packages/capsicum/lib/src/ui/util/notification_type_display.dart b/packages/capsicum/lib/src/ui/util/notification_type_display.dart index 6051cf5c8..8b0d1bba3 100644 --- a/packages/capsicum/lib/src/ui/util/notification_type_display.dart +++ b/packages/capsicum/lib/src/ui/util/notification_type_display.dart @@ -258,3 +258,24 @@ NotificationType notificationTypeFromString(String? raw) { return NotificationType.other; } } + +/// プッシュ通知の種類ごとのオン / オフ (#1411) で出す名前。 +/// +/// ⚠ **通知の一覧と同じ名前にする**([notificationTypeDisplay] から引く)。分類が +/// 2 つの種類を束ねるもの(フォロー・編集)は、両方の名前を並べる。 +/// 絞れるのは Mastodon 系だけなので、ブースト・投稿は既定の呼び名でよい。 +String pushAlertCategoryLabel(PushAlertCategory category) { + String of(NotificationType type) => notificationTypeDisplay(type).label; + return switch (category) { + PushAlertCategory.mention => of(NotificationType.mention), + PushAlertCategory.favourite => of(NotificationType.favourite), + PushAlertCategory.reblog => of(NotificationType.reblog), + PushAlertCategory.follow => + '${of(NotificationType.follow)}・${of(NotificationType.followRequest)}', + PushAlertCategory.poll => of(NotificationType.poll), + PushAlertCategory.status => of(NotificationType.newPost), + PushAlertCategory.update => + '${of(NotificationType.update)}・${of(NotificationType.quotedUpdate)}', + PushAlertCategory.quote => of(NotificationType.quote), + }; +} diff --git a/packages/capsicum/lib/src/ui/widget/deck_column_strip.dart b/packages/capsicum/lib/src/ui/widget/deck_column_strip.dart index 3d4339e3b..ecc659bf0 100644 --- a/packages/capsicum/lib/src/ui/widget/deck_column_strip.dart +++ b/packages/capsicum/lib/src/ui/widget/deck_column_strip.dart @@ -120,7 +120,7 @@ class _DeckColumnStripState extends ConsumerState { Widget build(BuildContext context) { final theme = Theme.of(context); final hostColors = ref.watch(hostThemeColorProvider); - final canCloseUnlocked = canCloseUnlockedDeckColumns(ref); + final closeUnlockedDisabled = closeUnlockedDeckColumnsDisabledReason(ref); return Material( color: theme.colorScheme.surfaceContainer, child: SizedBox( @@ -136,7 +136,7 @@ class _DeckColumnStripState extends ConsumerState { // 「元に戻す」も挟まないので、区切り線と余白でコマから離す。 const VerticalDivider(width: 1, indent: 10, endIndent: 10), const SizedBox(width: 4), - _CloseUnlockedButton(enabled: canCloseUnlocked), + _CloseUnlockedButton(disabledReason: closeUnlockedDisabled), const SizedBox(width: 4), ], ), @@ -234,18 +234,22 @@ class _DeckColumnStripState extends ConsumerState { /// シートやメニューバーと同じ [closeUnlockedDeckColumns] に任せる。⚠ **押せない /// ときは隠さず、押せなくする**(#1307 の規則)。名前はシートの項目名と揃える。 class _CloseUnlockedButton extends ConsumerWidget { - const _CloseUnlockedButton({required this.enabled}); + const _CloseUnlockedButton({required this.disabledReason}); - final bool enabled; - - static const label = 'ロックしていないカラムを閉じる'; + /// 押せない理由。押せるときは null([closeUnlockedDisabledReason])。 + final String? disabledReason; @override - Widget build(BuildContext context, WidgetRef ref) => IconButton( - key: const ValueKey('deck-strip-close-unlocked'), - icon: const Icon(Icons.close_fullscreen), - // 押せないときは、シートの項目と同じ理由を添える。 - tooltip: enabled ? label : '$label(ロックしたカラムがあると使えます)', - onPressed: enabled ? () => closeUnlockedDeckColumns(ref) : null, - ); + Widget build(BuildContext context, WidgetRef ref) { + final reason = disabledReason; + return IconButton( + key: const ValueKey('deck-strip-close-unlocked'), + icon: const Icon(Icons.close_fullscreen), + // 押せないときは、シートの項目と同じ理由を添える。 + tooltip: reason == null + ? kCloseUnlockedDeckColumnsLabel + : '$kCloseUnlockedDeckColumnsLabel($reason)', + onPressed: reason == null ? () => closeUnlockedDeckColumns(ref) : null, + ); + } } diff --git a/packages/capsicum/lib/src/ui/widget/deck_column_view.dart b/packages/capsicum/lib/src/ui/widget/deck_column_view.dart index f38f8ab07..7a75ed6f7 100644 --- a/packages/capsicum/lib/src/ui/widget/deck_column_view.dart +++ b/packages/capsicum/lib/src/ui/widget/deck_column_view.dart @@ -33,7 +33,6 @@ import '../util/scroll_thresholds.dart'; import '../util/stream_connection_display.dart'; import 'emoji_text.dart'; import 'filter_scope.dart'; -import 'home_menu.dart' show tabLabel; import 'notification_filter_button.dart'; import 'post_tile.dart'; import 'retry_error_view.dart'; @@ -263,15 +262,8 @@ class _DeckColumnHeader extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); final adapter = ref.watch(currentAdapterProvider); - final isMastodon = - adapter != null && - !adapter.capabilities.supportedTimelines.contains(TimelineType.social); - // リスト名はキーに持たない(決定済み事項 4)ので、実行時に一覧から引く。 - // ⚠ リスト以外のカラムで一覧の取得を起こさない。 - final lists = column.tab is ListTab - ? ref.watch(listsProvider).valueOrNull ?? const [] - : const []; - final label = tabLabel(ref, column.tab, isMastodon, adapter, lists); + // ⚠ 種別のラベルはシートと同じものを使う(#1420)。 + final label = columnTabLabelInScope(ref, column.tab); final account = column.account; final acct = account.handle; // カラムのスコープの中なので、別アカウントのカラムでもここはそのカラムの diff --git a/packages/capsicum/lib/src/ui/widget/deck_columns_sheet.dart b/packages/capsicum/lib/src/ui/widget/deck_columns_sheet.dart index 0853c111e..330b0da46 100644 --- a/packages/capsicum/lib/src/ui/widget/deck_columns_sheet.dart +++ b/packages/capsicum/lib/src/ui/widget/deck_columns_sheet.dart @@ -13,7 +13,6 @@ import '../util/deck_close_unlocked.dart'; import '../util/deck_tabs.dart'; import 'emoji_text.dart'; import 'hashtag_condition_dialog.dart'; -import 'home_menu.dart' show tabLabel; import 'user_avatar.dart'; /// デッキのカラムを追加・並べ替え・削除するシート (#1093)。 @@ -65,7 +64,7 @@ class _DeckColumnsSheetState extends ConsumerState { final columns = ref.watch(deckColumnsProvider); final locked = ref.watch(deckLockedColumnsProvider); // ⚠ メニューと同じ入口で判定する(決定済み事項 17)。 - final canCloseUnlocked = canCloseUnlockedDeckColumns(ref); + final closeUnlockedDisabled = closeUnlockedDeckColumnsDisabledReason(ref); final accounts = ref.watch(accountManagerProvider).accounts; final currentKey = ref.watch(currentAccountKeyProvider); final selected = accounts.any((a) => a.key == _selectedAccount) @@ -207,11 +206,11 @@ class _DeckColumnsSheetState extends ConsumerState { ListTile( key: const ValueKey('deck-close-unlocked'), leading: const Icon(Icons.close_fullscreen), - title: const Text('ロックしていないカラムを閉じる'), - subtitle: canCloseUnlocked + title: const Text(kCloseUnlockedDeckColumnsLabel), + subtitle: closeUnlockedDisabled == null ? null - : const Text('ロックしたカラムがあると使えます'), - enabled: canCloseUnlocked, + : Text(closeUnlockedDisabled), + enabled: closeUnlockedDisabled == null, onTap: () => closeUnlockedDeckColumns(ref), ), _sectionHeader(theme, 'カラムを追加'), @@ -352,20 +351,6 @@ class _DeckSheetSectionHeader extends StatelessWidget { } } -/// 周りのスコープのアカウントで [tab] のラベルを出す。 -String _labelInScope(WidgetRef ref, TabType tab) { - final adapter = ref.watch(currentAdapterProvider); - final isMastodon = - adapter != null && - !adapter.capabilities.supportedTimelines.contains(TimelineType.social); - // リスト名はキーに持たない(決定済み事項 4)ので、実行時に一覧から引く。 - // ⚠ リスト以外で一覧の取得を起こさない。 - final lists = tab is ListTab && adapter is ListSupport - ? ref.watch(listsProvider).valueOrNull ?? const [] - : const []; - return tabLabel(ref, tab, isMastodon, adapter, lists); -} - class _TabTitle extends ConsumerWidget { const _TabTitle({required this.tab}); @@ -376,7 +361,7 @@ class _TabTitle extends ConsumerWidget { children: [ Icon(deckTabIcon(tab), size: 18), const SizedBox(width: 8), - Expanded(child: Text(_labelInScope(ref, tab))), + Expanded(child: Text(columnTabLabelInScope(ref, tab))), ], ); } @@ -552,7 +537,7 @@ class _DeckColumnCandidatesState extends ConsumerState<_DeckColumnCandidates> { Widget _candidateTile(TabType tab) => ListTile( key: ValueKey('candidate-${tab.toIdentityKey()}'), leading: Icon(deckTabIcon(tab)), - title: Text(_labelInScope(ref, tab)), + title: Text(columnTabLabelInScope(ref, tab)), trailing: const Icon(Icons.add), onTap: () => _add(tab), ); diff --git a/packages/capsicum/lib/src/ui/widget/home_menu.dart b/packages/capsicum/lib/src/ui/widget/home_menu.dart index 122c775b6..452c41a27 100644 --- a/packages/capsicum/lib/src/ui/widget/home_menu.dart +++ b/packages/capsicum/lib/src/ui/widget/home_menu.dart @@ -10,9 +10,7 @@ import 'package:window_manager/window_manager.dart'; import '../../model/account.dart'; import '../../model/deck_column.dart'; import '../../provider/account_manager_provider.dart'; -import '../../provider/channel_provider.dart'; import '../../provider/deck_provider.dart'; -import '../../provider/hashtag_provider.dart'; import '../../provider/list_provider.dart'; import '../../provider/platform_providers.dart'; import '../../provider/preferences_provider.dart'; @@ -28,7 +26,6 @@ import '../util/deck_close_unlocked.dart'; import '../util/deck_navigation.dart'; import '../util/deck_tabs.dart'; import '../util/provider_scope_carrier.dart'; -import '../util/timeline_type_label.dart'; import 'desktop_menu_model.dart'; import 'notification_filter_button.dart'; @@ -69,31 +66,6 @@ class HomeNavItem { }); } -String tabLabel( - WidgetRef ref, - TabType tab, - bool isMastodon, - DecentralizedBackendAdapter? adapter, - List allLists, -) { - return switch (tab) { - TimelineTab(:final type) => timelineTypeLabel( - ref, - type, - isMastodon: isMastodon, - adapter: adapter, - ), - ListTab(:final id, :final name) => - name ?? allLists.where((l) => l.id == id).firstOrNull?.title ?? id, - HashtagTab(:final tag) => hashtagSpecLabel(tag), - ChannelTab(:final id, :final name) => channelTabLabel(ref, id, name), - NotificationsTab() => '通知', - AnnouncementsTab() => 'お知らせ', - MessagesTab() => 'メッセージ', - final DeckOnlyTab t => deckOnlyTabLabel(ref, t, adapter), - }; -} - /// 「表示 > カラム」に出す 1 行 (#1170・`docs/deck-ui-plan.md` 決定済み事項 11)。 /// /// **カラムの見出しと同じ「タブ名 · 表示名」**にする(#1152)。デッキはアカウントを @@ -117,11 +89,8 @@ String deckColumnMenuLabel( final account = accountState.accounts .where((a) => a.key == column.account) .firstOrNull; - final adapter = account?.adapter; - final isMastodon = - adapter != null && - !adapter.capabilities.supportedTimelines.contains(TimelineType.social); - final label = tabLabel(ref, column.tab, isMastodon, adapter, allLists); + // ⚠ 種別のラベルは見出し・シートと同じ芯を通す(#1420)。 + final label = columnTabLabel(ref, column.tab, account?.adapter, allLists); // ⚠ アカウントをまたぐカラムには、アカウント名を添えない (#1259)。 if (column.tab.spansAccounts) return label; final who = @@ -898,7 +867,7 @@ List buildDesktopMenuModel( // 判断)。⚠ 押せないとき(ロック中が無い・ロックしていないカラムが // 無い)も隠さず、無効にして出す。確認は挟まない。 MenuActionEntry( - label: 'ロックしていないカラムを閉じる', + label: kCloseUnlockedDeckColumnsLabel, icon: Icons.close_fullscreen, shortcut: const MenuShortcut( LogicalKeyboardKey.keyW, @@ -1104,7 +1073,10 @@ Future showClipList(BuildContext context, WidgetRef ref) async { // ⚠ 管理できるなら 0 件でも開く。ここが新しいクリップへの唯一の入口 // (#1050・アンテナの #1052 と同じ型)。 final canManage = adapter is ClipManagementSupport; - if (clips.isEmpty && !canManage) { + // お気に入りのクリップの入口 (#1377)。⚠ 自分のクリップが 0 件でも開く + // (お気に入りだけ使う人がいる)。 + final canFavorite = adapter is ClipFavoriteSupport; + if (clips.isEmpty && !canManage && !canFavorite) { if (context.mounted) { ScaffoldMessenger.of( context, @@ -1143,6 +1115,17 @@ Future showClipList(BuildContext context, WidgetRef ref) async { ), if (clips.isEmpty) const ListTile(dense: true, title: Text('クリップはありません')), + if (canFavorite) + ListTile( + key: const ValueKey('clip-chooser-favorites'), + leading: const Icon(Icons.star_outline, size: 20), + title: const Text('お気に入りのクリップ'), + dense: true, + onTap: () { + Navigator.pop(context); + context.push('/clips/favorites'); + }, + ), if (canManage) ListTile( leading: const Icon(Icons.settings, size: 20), diff --git a/packages/capsicum/lib/src/ui/widget/push_registration_status_section.dart b/packages/capsicum/lib/src/ui/widget/push_registration_status_section.dart index 5251fc806..2d836270b 100644 --- a/packages/capsicum/lib/src/ui/widget/push_registration_status_section.dart +++ b/packages/capsicum/lib/src/ui/widget/push_registration_status_section.dart @@ -4,6 +4,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../provider/account_manager_provider.dart'; import '../../provider/entitlement_status_provider.dart'; import '../../provider/push_registration_status_provider.dart'; +import '../../service/push_disabled_accounts.dart'; import '../../service/push_registration_service.dart'; import '../../service/push_registration_status.dart'; import 'section_header.dart'; @@ -11,12 +12,28 @@ import 'section_header.dart'; /// プッシュ通知登録状態の表示文言・色・アイコンを返す共通ロジック。 /// 設定 → プッシュ通知画面とサーバー情報 / プロフィールの /// [PushRegistrationStatusSection] が同一の判定を使うために抽出してある。 +/// +/// [disabledByUser] は利用者がこのアカウントのプッシュ通知をオフにしているか +/// (`PushDisabledAccounts`・#1408)。 (String, Color, IconData) describePushRegistrationStatus( ThemeData theme, PushRegistrationState state, bool eligible, - PushRegistrationFailureReason? reason, -) { + PushRegistrationFailureReason? reason, { + bool disabledByUser = false, +}) { + // ⚠ オフにする途中で relay への登録が落ちると、状態は「失敗」のまま残る + // (#1420)。スイッチはオフなので「登録に失敗しました」だけでは食い違う。 + // オフであることを先に言い、止まっていることを添える。⚠ 再試行は残す + // ([isPushRegistrationRetryable])—— relay の行はプリセットの特例の根拠で、 + // 再試行すれば行を作ってから「オフ」に落ち着く。 + if (eligible && disabledByUser && state == PushRegistrationState.failed) { + return ( + 'オフ(プッシュ通知リレーへの登録が途中で止まっています)', + theme.colorScheme.outline, + Icons.toggle_off_outlined, + ); + } if (!eligible) { return ( // ⚠ **買えば使えることが分かる文面にする (#1218)。**以前は @@ -158,6 +175,9 @@ class PushRegistrationStatusSection extends ConsumerWidget { state, eligible, snapshot?.reason, + disabledByUser: PushDisabledAccounts.isDisabled( + account.key.toStorageKey(), + ), ); final retryable = isPushRegistrationRetryable(state, eligible: eligible); diff --git a/packages/capsicum/lib/src/util/exception_scrub.dart b/packages/capsicum/lib/src/util/exception_scrub.dart index 01d9cf770..ccd89f66a 100644 --- a/packages/capsicum/lib/src/util/exception_scrub.dart +++ b/packages/capsicum/lib/src/util/exception_scrub.dart @@ -26,10 +26,9 @@ Object scrubException(Object e) { // `/api/miauth//check` は認可待ちのセッション UUID をパスに持つ // ため、ポーリング失敗 (#276) の DioException でそのまま載ると Sentry に // 有効な session が出る。既知の機密セグメントはマスクする (#790 レビュー)。 - final path = e.requestOptions.path - .split('?') - .first - .replaceAllMapped(_sensitivePathSegment, (m) => '${m[1]}***${m[2]}'); + final path = _scrubAuthority( + e.requestOptions.path.split('?').first, + ).replaceAllMapped(_sensitivePathSegment, (m) => '${m[1]}***${m[2]}'); return StateError( 'DioException ${e.type.name} ' 'status=${e.response?.statusCode ?? '-'} ' @@ -92,6 +91,29 @@ final _sensitiveQueryParam = RegExp( caseSensitive: false, ); +/// 絶対 URL の authority から、利用者が打ったものを落とす (#1424)。 +/// +/// サーバーの接続の確認(probe)は、サーバーの欄に打たれた文字列をそのまま +/// `https://<入力>/...` に組むので、メールアドレスを打たれると path に残る +/// (CAPSICUM-7C)。 +/// +/// - `@`(半角・全角)より前は userinfo として落とす +/// - 残りに ASCII の `.` が無ければ、ホスト名として成り立たないので +/// `` にする(`serverProbeHostTag` と同じ線・IDN は `.` を持つので残る) +/// +/// 相対パス(relay の `/register/` など)には当たらない。 +String _scrubAuthority(String path) => + path.replaceFirstMapped(_absoluteUrlAuthority, (m) { + var authority = m[2]!; + final at = authority.lastIndexOf(_userinfoSeparator); + if (at >= 0) authority = authority.substring(at + 1); + if (!authority.contains('.')) authority = ''; + return '${m[1]}$authority'; + }); + +final _absoluteUrlAuthority = RegExp(r'^([a-zA-Z][a-zA-Z0-9+.-]*://)([^/]*)'); +final _userinfoSeparator = RegExp('[@@]'); + /// パスに載る機密セグメントのマスク。現状は MiAuth の /// `/api/miauth//check` の session UUID を対象にする (#790)。 final _sensitivePathSegment = RegExp(r'(/api/miauth/)[^/]+(/check)'); diff --git a/packages/capsicum/pubspec.yaml b/packages/capsicum/pubspec.yaml index 548554190..cbef5f34a 100644 --- a/packages/capsicum/pubspec.yaml +++ b/packages/capsicum/pubspec.yaml @@ -1,7 +1,7 @@ name: capsicum description: Flutter-based Mastodon / Misskey / Akkoma client publish_to: none -version: 2.14.0+223 +version: 2.15.0+224 environment: sdk: ^3.11.0 diff --git a/packages/capsicum/test/account_cleanup_symmetry_guard_test.dart b/packages/capsicum/test/account_cleanup_symmetry_guard_test.dart index 093e72f95..c6b182a41 100644 --- a/packages/capsicum/test/account_cleanup_symmetry_guard_test.dart +++ b/packages/capsicum/test/account_cleanup_symmetry_guard_test.dart @@ -71,6 +71,12 @@ void main() { logout: 'PushDisabledAccounts.forget(', offline: 'PushDisabledAccounts.forget(', ), + ( + // 同じ理由。残すと、入り直したときに一部の種類が黙って届かない。 + what: '受け取らない通知の分類 (#1411)', + logout: 'PushMutedAlerts.forget(', + offline: 'PushMutedAlerts.forget(', + ), ( what: 'Windows の push_labels.json', logout: '_syncWindowsPushLabels(', diff --git a/packages/capsicum/test/channel_tab_label_test.dart b/packages/capsicum/test/channel_tab_label_test.dart index 6f832bef8..c2f62077b 100644 --- a/packages/capsicum/test/channel_tab_label_test.dart +++ b/packages/capsicum/test/channel_tab_label_test.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'package:capsicum/src/provider/channel_provider.dart'; -import 'package:capsicum/src/ui/widget/home_menu.dart'; +import 'package:capsicum/src/ui/util/deck_tabs.dart'; import 'package:capsicum_core/capsicum_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; diff --git a/packages/capsicum/test/clip_favorite_test.dart b/packages/capsicum/test/clip_favorite_test.dart new file mode 100644 index 000000000..da24d316b --- /dev/null +++ b/packages/capsicum/test/clip_favorite_test.dart @@ -0,0 +1,166 @@ +// #1377: ほかの人のクリップをお気に入りに入れる・お気に入りのクリップの一覧。 +import 'package:capsicum/src/model/account.dart'; +import 'package:capsicum/src/model/account_key.dart'; +import 'package:capsicum/src/provider/account_manager_provider.dart'; +import 'package:capsicum/src/ui/screen/clip_favorites_screen.dart'; +import 'package:capsicum/src/ui/screen/clip_notes_screen.dart'; +import 'package:capsicum_backends/capsicum_backends.dart'; +import 'package:capsicum_core/capsicum_core.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _Adapter extends Mock + implements + DecentralizedBackendAdapter, + ClipSupport, + ClipManagementSupport, + ClipFavoriteSupport {} + +class _AccountNotifier extends AccountManagerNotifier { + _AccountNotifier(this._current); + + final Account _current; + + @override + AccountManagerState build() => + AccountManagerState(accounts: [_current], current: _current); +} + +void main() { + late _Adapter adapter; + + setUpAll(() => registerFallbackValue(const TimelineQuery())); + + setUp(() { + adapter = _Adapter(); + when(() => adapter.getClips()).thenAnswer((_) async => const []); + when( + () => adapter.getClipNotes(any(), query: any(named: 'query')), + ).thenAnswer((_) async => const []); + }); + + Account account() => Account( + key: const AccountKey( + type: BackendType.misskey, + host: 'misskey.example', + username: 'me', + ), + adapter: adapter, + user: const User(id: 'me', username: 'me'), + userSecret: const UserSecret(accessToken: 'token'), + ); + + Future pump(WidgetTester tester, Widget home) async { + final current = account(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + accountManagerProvider.overrideWith(() => _AccountNotifier(current)), + ], + child: MaterialApp(home: home), + ), + ); + await tester.pumpAndSettle(); + } + + final star = find.byKey(const ValueKey('clip-favorite')); + + group('クリップの画面の ☆', () { + testWidgets('⚠⚠ ほかの人のクリップなら出し、押すとお気に入りに入れる', (tester) async { + when(() => adapter.getClip('c1')).thenAnswer( + (_) async => const NoteClip( + id: 'c1', + name: '名場面', + userId: 'alice', + isFavorited: false, + ), + ); + when(() => adapter.favoriteClip(any())).thenAnswer((_) async {}); + await pump(tester, const ClipNotesScreen(clipId: 'c1')); + + expect(star, findsOneWidget); + expect(find.byIcon(Icons.star_border), findsOneWidget); + + await tester.tap(star); + await tester.pumpAndSettle(); + + verify(() => adapter.favoriteClip('c1')).called(1); + expect(find.byIcon(Icons.star), findsOneWidget); + }); + + testWidgets('お気に入り済みなら外す', (tester) async { + when(() => adapter.getClip('c1')).thenAnswer( + (_) async => const NoteClip( + id: 'c1', + name: '名場面', + userId: 'alice', + isFavorited: true, + ), + ); + when(() => adapter.unfavoriteClip(any())).thenAnswer((_) async {}); + await pump(tester, const ClipNotesScreen(clipId: 'c1')); + + await tester.tap(star); + await tester.pumpAndSettle(); + + verify(() => adapter.unfavoriteClip('c1')).called(1); + expect(find.byIcon(Icons.star_border), findsOneWidget); + }); + + testWidgets('⚠ 持ち主が自分なら出さない(一覧に無くても)', (tester) async { + when(() => adapter.getClip('c1')).thenAnswer( + (_) async => const NoteClip(id: 'c1', name: '自分の', userId: 'me'), + ); + await pump(tester, const ClipNotesScreen(clipId: 'c1')); + + expect(star, findsNothing); + }); + + testWidgets('失敗したら戻して知らせる', (tester) async { + when(() => adapter.getClip('c1')).thenAnswer( + (_) async => const NoteClip( + id: 'c1', + name: '名場面', + userId: 'alice', + isFavorited: false, + ), + ); + when(() => adapter.favoriteClip(any())).thenThrow(const ClipNotFound()); + await pump(tester, const ClipNotesScreen(clipId: 'c1')); + + await tester.tap(star); + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.star_border), findsOneWidget); + expect(find.text('このクリップはもう見られません'), findsOneWidget); + }); + }); + + group('お気に入りのクリップの一覧', () { + testWidgets('誰のクリップかを添えて並べる', (tester) async { + when(() => adapter.getFavoriteClips()).thenAnswer( + (_) async => const [ + NoteClip( + id: 'c1', + name: '名場面', + ownerName: 'アリス', + description: '第 1 話', + ), + ], + ); + await pump(tester, const ClipFavoritesScreen()); + + expect(find.text('名場面'), findsOneWidget); + expect(find.text('アリス · 第 1 話'), findsOneWidget); + }); + + testWidgets('0 件なら入れ方を案内する', (tester) async { + when(() => adapter.getFavoriteClips()).thenAnswer((_) async => const []); + await pump(tester, const ClipFavoritesScreen()); + + expect(find.textContaining('お気に入りのクリップはありません'), findsOneWidget); + }); + }); +} diff --git a/packages/capsicum/test/column_tab_label_delegation_guard_test.dart b/packages/capsicum/test/column_tab_label_delegation_guard_test.dart new file mode 100644 index 000000000..e71f345b0 --- /dev/null +++ b/packages/capsicum/test/column_tab_label_delegation_guard_test.dart @@ -0,0 +1,156 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +import 'support/dart_source.dart'; + +/// カラムのラベルを組む 3 か所が `deck_tabs.dart` の芯に委譲していることを見る +/// (#1420)。 +/// +/// ⚠⚠ **集約の再発は「壊れること」ではなく「使わなくなること」として現れる** +/// (`docs/CLAUDE.md`「ソース検査ガードの書き方」・#1083-A)。見出し・カラム編集の +/// シート・メニューバーと帯は、それぞれ `isMastodon` とリストの引き方を写して +/// 持っていて、リストを引く条件がシートだけずれていた(v2.14 のリリース前レビュー)。 +/// どれかが自前の組み立てへ戻ると、芯を直してもその場所には効かない。 +/// +/// ⚠ `home_menu.dart` は `deckColumnMenuLabel` の本体だけを見る。同じファイルの +/// 「表示 > タブ」(デッキでないときのタブ UI)は `isMastodon` を自前で持って +/// `tabLabel` を直に呼ぶ側で、カラムではない。 +void main() { + // 値は (パス, 見る関数)。関数が null ならファイル全体を見る。 + const files = { + '見出し': ('lib/src/ui/widget/deck_column_view.dart', null), + 'カラム編集のシート': ('lib/src/ui/widget/deck_columns_sheet.dart', null), + 'メニューバーと帯': ( + 'lib/src/ui/widget/home_menu.dart', + 'String deckColumnMenuLabel(', + ), + }; + + group('判定(合成ソース)', () { + test('芯を呼んでいれば委譲している', () { + expect( + selfBuiltColumnLabel( + 'final label = columnTabLabelInScope(ref, column.tab);', + ), + isEmpty, + ); + expect( + selfBuiltColumnLabel( + 'final label = columnTabLabel(ref, tab, adapter, lists);', + ), + isEmpty, + ); + }); + + test('⚠⚠ tabLabel を直に呼んでいたら自前で組んでいる', () { + expect( + selfBuiltColumnLabel( + 'final label = tabLabel(ref, tab, isMastodon, adapter, lists);', + ), + contains('tabLabel('), + ); + }); + + test('⚠⚠ Mastodon の判定を写していたら自前で組んでいる', () { + expect( + selfBuiltColumnLabel(''' + final isMastodon = + adapter != null && + !adapter.capabilities.supportedTimelines.contains(TimelineType.social); +'''), + contains('supportedTimelines.contains(TimelineType.social)'), + ); + }); + + test('コメントの中にあるだけなら当てない', () { + expect( + selfBuiltColumnLabel(''' + // 以前は tabLabel(ref, tab, isMastodon, adapter, lists) を直に呼んでいた + /// supportedTimelines.contains(TimelineType.social) で判定していた + final label = columnTabLabelInScope(ref, tab); +'''), + isEmpty, + ); + }); + + test('芯の名前の一部として出る tabLabel には当てない', () { + expect(selfBuiltColumnLabel('columnTabLabel(ref, tab, a, l);'), isEmpty); + }); + }); + + test('芯は deck_tabs.dart にある(走査の空振りを緑にしない)', () { + final source = maskComments( + File('lib/src/ui/util/deck_tabs.dart').readAsStringSync(), + ); + expect(source, contains('String columnTabLabel(')); + expect(source, contains('String columnTabLabelInScope(')); + }); + + group('関数の本体の切り出し', () { + test('見る関数の本体だけを返す', () { + const source = ''' +String other() => tabLabel(ref, t, true, a, l); +String target(int x) { + if (x > 0) { return columnTabLabel(ref, t, a, l); } + return ''; +} +String after() => tabLabel(ref, t, true, a, l); +'''; + final body = functionBody(source, 'String target(')!; + expect(body, contains('columnTabLabel(')); + expect(selfBuiltColumnLabel(body), isEmpty); + }); + + test('見る関数が無ければ null(走査の空振りを緑にしない)', () { + expect(functionBody('void x() {}', 'String target('), isNull); + }); + }); + + for (final entry in files.entries) { + test('⚠⚠ ${entry.key} はカラムのラベルを芯に委譲している', () { + final (path, function) = entry.value; + final file = File(path); + expect(file.existsSync(), isTrue, reason: '走査の対象が無い(パスを確かめる)'); + final whole = file.readAsStringSync(); + final source = function == null ? whole : functionBody(whole, function); + expect(source, isNotNull, reason: '$function が見つからない(名前を確かめる)'); + expect( + maskComments(source!), + matches(RegExp(r'\bcolumnTabLabel(InScope)?\(')), + reason: '芯を呼んでいない', + ); + expect(selfBuiltColumnLabel(source), isEmpty); + }); + } +} + +/// [head](`String name(` の形)で始まる関数の本体(`{` から対応する `}` まで)。 +/// コメントは落としてから数える。見つからなければ null。 +String? functionBody(String source, String head) { + final masked = maskComments(source); + final start = masked.indexOf(head); + if (start < 0) return null; + final open = masked.indexOf('{', start); + if (open < 0) return null; + var depth = 0; + for (var i = open; i < masked.length; i++) { + final c = masked[i]; + if (c == '{') depth++; + if (c == '}') { + depth--; + if (depth == 0) return masked.substring(open, i + 1); + } + } + return null; +} + +/// カラムのラベルを自前で組んでいる形を返す。コメントは落として見る。 +List selfBuiltColumnLabel(String source) { + final masked = maskComments(source); + return [ + if (RegExp(r'(? const AccountManagerState(); - void setAccounts(List accounts) { + void setAccounts( + List accounts, { + List offline = const [], + }) { state = AccountManagerState( accounts: accounts, current: accounts.isEmpty ? null : accounts.first, + offlineAccounts: offline, ); } } @@ -244,6 +249,32 @@ void main() { expect(subsystem.shown.single.title, contains('(@bob@h2)')); }); + // #1420: プッシュの経路(isMultiAccountForPush)と同じ判定にする。 + test('⚠⚠ オンライン 1 件 + オフライン 1 件でも、宛先を添える', () async { + final a = _makeAccount('alice', 'h1'); + notifier.setAccounts( + [a.account], + offline: [ + OfflineAccount( + key: AccountKey( + type: BackendType.mastodon, + host: 'h2', + username: 'bob', + ), + ), + ], + ); + await _settle(); + + final user = _MockUser(); + when(() => user.displayName).thenReturn('送信者'); + when(() => user.username).thenReturn('sender'); + a.controller.add(_mention('a1', user: user)); + await _settle(); + + expect(subsystem.shown.single.title, endsWith(' (@alice@h1)')); + }); + test('単一垢のときは title に宛先を添えない', () async { final a = _makeAccount('alice', 'h1'); notifier.setAccounts([a.account]); diff --git a/packages/capsicum/test/exception_scrub_test.dart b/packages/capsicum/test/exception_scrub_test.dart index f27f304c2..7650894de 100644 --- a/packages/capsicum/test/exception_scrub_test.dart +++ b/packages/capsicum/test/exception_scrub_test.dart @@ -47,6 +47,54 @@ void main() { expect(scrubException(e).toString(), contains('/api/v1/timelines/home')); }); + group('⚠ 絶対 URL の authority から、利用者が打ったものを落とす (#1424)', () { + String scrubPath(String path) => scrubException( + DioException( + requestOptions: RequestOptions(path: path), + type: DioExceptionType.unknown, + ), + ).toString(); + + test('半角のメールアドレスは @ より前を落とす', () { + final scrubbed = scrubPath( + 'https://someone+test@example.com/api/v1/instance', + ); + expect(scrubbed, isNot(contains('someone'))); + expect(scrubbed, contains('https://example.com/api/v1/instance')); + }); + + test('全角のまま打たれたメールアドレスは にする(CAPSICUM-7C の形)', () { + final scrubbed = scrubPath( + 'https://someおね+てst@exあmple.com/api/v1/instance', + ); + expect(scrubbed, isNot(contains('some'))); + expect(scrubbed, isNot(contains('ex'))); + expect(scrubbed, contains('https:///api/v1/instance')); + }); + + test('普通のホスト・IDN・ポート付きはそのまま残す', () { + expect( + scrubPath('https://mstdn.b-shock.org/api/v1/instance'), + contains('https://mstdn.b-shock.org/api/v1/instance'), + ); + expect( + scrubPath('https://日本語.jp/nodeinfo/2.0'), + contains('https://日本語.jp/nodeinfo/2.0'), + ); + expect( + scrubPath('https://example.com:8443/api/meta'), + contains('https://example.com:8443/api/meta'), + ); + }); + + test('相対パスには当たらない(@ を含んでも)', () { + expect( + scrubPath('/api/v1/accounts/lookup/@someone'), + contains('/api/v1/accounts/lookup/@someone'), + ); + }); + }); + test('URL の機密クエリ値をマスクする', () { final e = StateError( 'WebSocketException: wss://example.com/streaming?i=SECRET_TOKEN', diff --git a/packages/capsicum/test/gallery_like_and_recent_test.dart b/packages/capsicum/test/gallery_like_and_recent_test.dart index 3370b00e6..94421acb4 100644 --- a/packages/capsicum/test/gallery_like_and_recent_test.dart +++ b/packages/capsicum/test/gallery_like_and_recent_test.dart @@ -95,6 +95,39 @@ void main() { expect(find.byIcon(Icons.favorite), findsOneWidget); expect(find.byType(SnackBar), findsNothing); + // ⚠ もともといいね済みだった=件数には含まれている。足さない(#1420)。 + expect(find.text('2'), findsOneWidget); + }); + + // #1420: 一覧の投稿は取得した時点のまま。詳細で変えたものを開き直しで失わない。 + testWidgets('⚠⚠ いいねして閉じ、同じ(古い)投稿で開き直しても、いいね済みで出る', (tester) async { + when(() => adapter.likeGalleryPost(any())).thenAnswer((_) async {}); + final stale = _post('p1', isLiked: false); + final open = ValueNotifier(true); + await tester.pumpWidget( + ProviderScope( + overrides: [currentAdapterProvider.overrideWithValue(adapter)], + child: MaterialApp( + home: ValueListenableBuilder( + valueListenable: open, + builder: (_, isOpen, _) => isOpen + ? GalleryDetailScreen(key: UniqueKey(), post: stale) + : const SizedBox(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(like); + await tester.pumpAndSettle(); + open.value = false; + await tester.pumpAndSettle(); + open.value = true; + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.favorite), findsOneWidget); + expect(find.text('3'), findsOneWidget); }); testWidgets('自分の投稿(YOUR_POST)は戻して専用の文言', (tester) async { diff --git a/packages/capsicum/test/info_bot_follow_keeper_test.dart b/packages/capsicum/test/info_bot_follow_keeper_test.dart new file mode 100644 index 000000000..b177c979c --- /dev/null +++ b/packages/capsicum/test/info_bot_follow_keeper_test.dart @@ -0,0 +1,206 @@ +import 'package:capsicum/src/service/info_bot_follow_keeper.dart'; +import 'package:capsicum_core/capsicum_core.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// #1402: 自分のサーバーのお知らせボットのフォローを保つ。 + +const _host = 'mstdn.b-shock.org'; +const _bot = '@info@mstdn.b-shock.org'; + +User _user(String username, {String? host, String id = 'u1'}) => + User(id: id, username: username, host: host); + +DioException _refusal(Object? data, {int status = 403}) { + final options = RequestOptions(path: '/x'); + return DioException( + requestOptions: options, + response: Response(requestOptions: options, statusCode: status, data: data), + type: DioExceptionType.badResponse, + ); +} + +void main() { + group('parseAcct', () { + test('先頭の @ はあってもなくてもよい', () { + expect(InfoBotFollowKeeper.parseAcct(_bot), ( + username: 'info', + host: _host, + )); + expect(InfoBotFollowKeeper.parseAcct('info@$_host'), ( + username: 'info', + host: _host, + )); + }); + + test('読めない形は null', () { + expect(InfoBotFollowKeeper.parseAcct(null), isNull); + expect(InfoBotFollowKeeper.parseAcct('info'), isNull); + expect(InfoBotFollowKeeper.parseAcct('@info@'), isNull); + expect(InfoBotFollowKeeper.parseAcct('a@b@c'), isNull); + }); + }); + + group('isOwnInfoBot', () { + test('自分のサーバーのボット(host は空でも自サーバーでも・大文字小文字を問わない)', () { + for (final user in [ + _user('info'), + _user('info', host: _host), + _user('Info', host: 'MSTDN.b-shock.org'), + ]) { + expect( + InfoBotFollowKeeper.isOwnInfoBot( + user: user, + infoBotAcct: _bot, + localHost: _host, + ), + isTrue, + reason: '${user.username}@${user.host}', + ); + } + }); + + test('別のサーバーの同名のアカウントはボットではない', () { + expect( + InfoBotFollowKeeper.isOwnInfoBot( + user: _user('info', host: 'misskey.delmulin.com'), + infoBotAcct: _bot, + localHost: _host, + ), + isFalse, + ); + }); + + test('ボットの acct が別のサーバーを指していたら対象外', () { + expect( + InfoBotFollowKeeper.isOwnInfoBot( + user: _user('info'), + infoBotAcct: '@info@misskey.delmulin.com', + localHost: _host, + ), + isFalse, + ); + }); + + test('ボットが無ければ誰も対象外', () { + expect( + InfoBotFollowKeeper.isOwnInfoBot( + user: _user('info'), + infoBotAcct: null, + localHost: _host, + ), + isFalse, + ); + }); + }); + + group('ensureFollowing', () { + late List followed; + late List<(String, String)> lookedUp; + + setUp(() { + followed = []; + lookedUp = []; + }); + + Future run({ + String? acct = _bot, + String own = 'pooza', + User? bot, + UserRelationship rel = const UserRelationship(), + }) => InfoBotFollowKeeper.ensureFollowing( + infoBotAcct: acct, + localHost: _host, + ownUsername: own, + lookup: (u, h) async { + lookedUp.add((u, h)); + return bot ?? _user('info', id: 'bot'); + }, + relationship: (_) async => rel, + follow: (id) async => followed.add(id), + ); + + test('外れていればフォローし直す', () async { + expect(await run(), InfoBotFollowResult.followed); + expect(lookedUp, [('info', _host)]); + expect(followed, ['bot']); + }); + + test('フォロー中・承認待ちなら何もしない', () async { + expect( + await run(rel: const UserRelationship(following: true)), + InfoBotFollowResult.following, + ); + expect( + await run(rel: const UserRelationship(requested: true)), + InfoBotFollowResult.following, + ); + expect(followed, isEmpty); + }); + + test('ブロックしている相手はフォローし直さない', () async { + expect( + await run(rel: const UserRelationship(blocking: true)), + InfoBotFollowResult.blocking, + ); + expect(followed, isEmpty); + }); + + test('ボット自身・ボットが無い・別のサーバーのボットでは API を叩かない', () async { + expect(await run(own: 'Info'), InfoBotFollowResult.self); + expect(await run(acct: null), InfoBotFollowResult.noBot); + expect( + await run(acct: '@info@misskey.delmulin.com'), + InfoBotFollowResult.noBot, + ); + expect(lookedUp, isEmpty); + expect(followed, isEmpty); + }); + }); + + group('refusalMessage', () { + test('Mastodon のフォーク({"error": "…"})', () { + expect( + InfoBotFollowKeeper.refusalMessage( + _refusal({ + 'error': + 'This user is specified by the server and cannot be unfollowed.', + }), + ), + 'このユーザーはサーバーが指定しているため、フォローを解除できません。', + ); + }); + + test('Misskey のフォーク({"error": {"message", "code"}})', () { + expect( + InfoBotFollowKeeper.refusalMessage( + _refusal({ + 'error': { + 'message': + 'This user is specified by the server and cannot be blocked.', + 'code': 'CANNOT_BLOCK_AUTO_FOLLOW_USER', + }, + }), + ), + 'このユーザーはサーバーが指定しているため、ブロックできません。', + ); + }); + + test('ほかの 403・ほかの状態・ほかの例外では null', () { + expect( + InfoBotFollowKeeper.refusalMessage(_refusal({'error': 'Forbidden'})), + isNull, + ); + expect( + InfoBotFollowKeeper.refusalMessage( + _refusal({ + 'error': + 'This user is specified by the server and cannot be unfollowed.', + }, status: 422), + ), + isNull, + ); + expect(InfoBotFollowKeeper.refusalMessage(StateError('x')), isNull); + }); + }); +} diff --git a/packages/capsicum/test/live_decoration_test.dart b/packages/capsicum/test/live_decoration_test.dart new file mode 100644 index 000000000..f3e9040bd --- /dev/null +++ b/packages/capsicum/test/live_decoration_test.dart @@ -0,0 +1,232 @@ +// #1409: 実況のためにモロヘイヤが付けたデコを、デコの画面で示して外せるようにする。 +import 'package:capsicum/src/model/account.dart'; +import 'package:capsicum/src/model/account_key.dart'; +import 'package:capsicum/src/provider/account_manager_provider.dart'; +import 'package:capsicum/src/ui/screen/avatar_decoration_screen.dart'; +import 'package:capsicum_backends/capsicum_backends.dart'; +import 'package:capsicum_core/capsicum_core.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _Adapter extends Mock + implements DecentralizedBackendAdapter, AvatarDecorationSupport {} + +class _Mulukhiya extends Mock implements MulukhiyaService {} + +class _AccountNotifier extends AccountManagerNotifier { + _AccountNotifier(this._current); + + final Account _current; + + @override + AccountManagerState build() => + AccountManagerState(accounts: [_current], current: _current); +} + +const _live = AvatarDecorationOption( + id: 'live-1', + name: '実況中 ゴメちゃん', + url: 'https://example.invalid/live.png', +); + +const _other = AvatarDecorationOption( + id: 'other', + name: 'かぼちゃ', + url: 'https://example.invalid/a.png', +); + +void main() { + group('応答の読み取り', () { + test('実況中の応答を読む', () { + final live = MulukhiyaLiveDecoration.fromJson({ + 'live': true, + 'id': 'live-1', + 'name': '実況中 ゴメちゃん', + 'program': 'ダイの大冒険', + 'restore_at': '2026-11-22T10:47:00+09:00', + }); + expect(live.live, isTrue); + expect(live.restorable, isTrue); + expect(live.program, 'ダイの大冒険'); + expect(live.restoreAt, DateTime.utc(2026, 11, 22, 1, 47)); + }); + + test('⚠⚠ id が無ければ外せない(実況の前から同じデコを付けていた)', () { + final live = MulukhiyaLiveDecoration.fromJson({'live': true}); + expect(live.live, isTrue); + expect(live.restorable, isFalse); + }); + + test('実況中でなければ live だけ', () { + final live = MulukhiyaLiveDecoration.fromJson({'live': false}); + expect(live.live, isFalse); + expect(live.restorable, isFalse); + }); + + test('読めない時刻は null(帯の文面から外す)', () { + final live = MulukhiyaLiveDecoration.fromJson({ + 'live': true, + 'restore_at': 'not a date', + }); + expect(live.restoreAt, isNull); + }); + }); + + group('帯の文面', () { + test('名前・番組・時刻が揃っていれば全部出す', () { + final text = liveDecorationBannerText( + MulukhiyaLiveDecoration( + live: true, + id: 'x', + name: '実況中 ゴメちゃん', + program: 'ダイの大冒険', + restoreAt: DateTime(2026, 11, 22, 10, 7), + ), + ); + expect(text, '「実況中 ゴメちゃん」は実況中のデコです(ダイの大冒険)。10:07ごろ、番組の終わりに外れます。'); + }); + + test('分からないものは省く', () { + expect( + liveDecorationBannerText(const MulukhiyaLiveDecoration(live: true)), + '実況中のデコが付いています。番組の終わりに外れます。', + ); + }); + }); + + group('デコの画面', () { + late _Adapter adapter; + late _Mulukhiya mulukhiya; + + Account account({List decorations = const []}) => Account( + key: const AccountKey( + type: BackendType.misskey, + host: 'misskey.example', + username: 'me', + ), + adapter: adapter, + user: User(id: 'me', username: 'me', avatarDecorations: decorations), + userSecret: const UserSecret(accessToken: 'token'), + mulukhiya: mulukhiya, + ); + + setUp(() { + adapter = _Adapter(); + mulukhiya = _Mulukhiya(); + when( + () => adapter.getAvatarDecorationOptions(), + ).thenAnswer((_) async => [_live, _other]); + when(() => adapter.getAvatarDecorationLimit()).thenAnswer((_) async => 3); + }); + + Future pump(WidgetTester tester, Account current) async { + final container = ProviderContainer( + overrides: [ + accountManagerProvider.overrideWith(() => _AccountNotifier(current)), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const MaterialApp(home: AvatarDecorationScreen()), + ), + ); + await tester.pumpAndSettle(); + return container; + } + + final banner = find.byKey(const ValueKey('live-decoration-banner')); + final restore = find.byKey(const ValueKey('live-decoration-restore')); + + testWidgets('⚠⚠ 実況中なら帯を出し、外すデコの行にも示す', (tester) async { + when( + () => + mulukhiya.getLiveDecoration(accessToken: any(named: 'accessToken')), + ).thenAnswer( + (_) async => const MulukhiyaLiveDecoration( + live: true, + id: 'live-1', + name: '実況中 ゴメちゃん', + ), + ); + await pump( + tester, + account( + decorations: const [ + AvatarDecoration(id: 'live-1', url: 'https://example.invalid/l'), + ], + ), + ); + + expect(banner, findsOneWidget); + expect(restore, findsOneWidget); + expect(find.text('実況中(番組の終わりに外れます)'), findsOneWidget); + }); + + testWidgets('「いま外す」で外し、自分を引き直して帯を消す', (tester) async { + var live = true; + when( + () => + mulukhiya.getLiveDecoration(accessToken: any(named: 'accessToken')), + ).thenAnswer( + (_) async => live + ? const MulukhiyaLiveDecoration(live: true, id: 'live-1') + : const MulukhiyaLiveDecoration(live: false), + ); + when( + () => mulukhiya.restoreLiveDecoration( + accessToken: any(named: 'accessToken'), + ), + ).thenAnswer((_) async => live = false); + when( + () => adapter.getMyself(), + ).thenAnswer((_) async => const User(id: 'me', username: 'me')); + final container = await pump( + tester, + account( + decorations: const [ + AvatarDecoration(id: 'live-1', url: 'https://example.invalid/l'), + ], + ), + ); + + await tester.tap(restore); + await tester.pumpAndSettle(); + + verify( + () => mulukhiya.restoreLiveDecoration(accessToken: 'token'), + ).called(1); + expect(banner, findsNothing); + expect( + container.read(currentAccountProvider)!.user.avatarDecorations, + isEmpty, + reason: '引き直した自分をアカウントへ反映する', + ); + }); + + testWidgets('⚠ 外す相手が分からなければ、帯だけ出して「外す」は出さない', (tester) async { + when( + () => + mulukhiya.getLiveDecoration(accessToken: any(named: 'accessToken')), + ).thenAnswer((_) async => const MulukhiyaLiveDecoration(live: true)); + await pump(tester, account()); + + expect(banner, findsOneWidget); + expect(restore, findsNothing); + }); + + testWidgets('⚠ 口が無い(404 で null)・読めないときは何も出さない', (tester) async { + when( + () => + mulukhiya.getLiveDecoration(accessToken: any(named: 'accessToken')), + ).thenThrow(Exception('boom')); + await pump(tester, account()); + + expect(banner, findsNothing); + expect(find.text('かぼちゃ'), findsOneWidget, reason: '画面そのものは使える'); + }); + }); +} diff --git a/packages/capsicum/test/logout_token_revoke_test.dart b/packages/capsicum/test/logout_token_revoke_test.dart index 0ea5b09a2..cc02f224b 100644 --- a/packages/capsicum/test/logout_token_revoke_test.dart +++ b/packages/capsicum/test/logout_token_revoke_test.dart @@ -6,6 +6,7 @@ import 'package:capsicum/src/model/account_key.dart'; import 'package:capsicum/src/provider/account_manager_provider.dart'; import 'package:capsicum_backends/capsicum_backends.dart'; import 'package:capsicum_core/capsicum_core.dart'; +import 'package:dio/dio.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; @@ -13,6 +14,8 @@ import 'support/dart_source.dart'; class _PlainAdapter extends Mock implements DecentralizedBackendAdapter {} +class _MastodonAdapter extends Mock implements MastodonAdapter {} + class _RevokingAdapter extends Mock implements DecentralizedBackendAdapter, TokenRevokeSupport {} @@ -119,6 +122,71 @@ void main() { }); }); + // #1420: 取り消しが仕組みとして通っているかを現場で見られるようにする。 + group('取り消しの失敗を Sentry へ送るか', () { + DioException response(int status) { + final options = RequestOptions(path: '/oauth/revoke'); + return DioException( + requestOptions: options, + response: Response(requestOptions: options, statusCode: status), + type: DioExceptionType.badResponse, + ); + } + + final mastodon = _MastodonAdapter(); + final misskey = _RevokingAdapter(); + + test('⚠⚠ Mastodon 系でサーバーが応答した失敗は送る', () { + expect( + AccountManagerNotifier.shouldReportRevokeFailure( + mastodon, + response(403), + ), + isTrue, + ); + expect( + AccountManagerNotifier.shouldReportRevokeFailure( + mastodon, + response(500), + ), + isTrue, + ); + }); + + test('401(もう失効している)は送らない', () { + expect( + AccountManagerNotifier.shouldReportRevokeFailure( + mastodon, + response(401), + ), + isFalse, + ); + }); + + test('回線の失敗は送らない', () { + expect( + AccountManagerNotifier.shouldReportRevokeFailure( + mastodon, + DioException( + requestOptions: RequestOptions(path: '/oauth/revoke'), + type: DioExceptionType.connectionError, + ), + ), + isFalse, + ); + }); + + test('Mastodon 系でなければ送らない(古い Misskey のエラーは今のまま)', () { + expect( + AccountManagerNotifier.shouldReportRevokeFailure( + misskey, + response(404), + ), + isFalse, + ); + }); + }); + // ⚠ 順番は「プッシュの登録解除 → 取り消し」。解除は同じトークンで叩くので、 // 先に取り消すと 401 で落ちて購読が残る。⚠ 取り消す直前に、同じアカウントが // 入り直していないかを見る(Mastodon は同じトークンを返す・リリース前レビュー)。 diff --git a/packages/capsicum/test/mastodon_push_refetch_test.dart b/packages/capsicum/test/mastodon_push_refetch_test.dart new file mode 100644 index 000000000..326b1b611 --- /dev/null +++ b/packages/capsicum/test/mastodon_push_refetch_test.dart @@ -0,0 +1,238 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:capsicum/src/service/mastodon_push_refetch.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// #1426: 上流に古い購読が残っていて、古い鍵の 1 通が届いたときの引き直し。 + +final _now = DateTime.utc(2026, 11, 25, 12, 0, 0); + +Map _mention({ + String id = '100', + DateTime? createdAt, + String content = '

こんにちは
また明日

', + String spoiler = '', +}) => { + 'id': id, + 'type': 'mention', + 'created_at': (createdAt ?? _now.subtract(const Duration(seconds: 5))) + .toIso8601String(), + 'account': {'acct': 'alice@example.com', 'display_name': 'アリス'}, + 'status': {'content': content, 'spoiler_text': spoiler}, +}; + +void main() { + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + tearDown(() { + MastodonPushRefetch.dioFactory = Dio.new; + MastodonPushRefetch.tokenReader = (_) async => null; + }); + + group('contentFromNotification', () { + test('投稿のある通知は本文を平文にする', () { + final content = MastodonPushRefetch.contentFromNotification(_mention()); + expect(content.type, 'mention'); + expect(content.body, 'こんにちは\nまた明日'); + expect(content.notificationId, '100'); + // 見出しは呼び出し側が type から作る。 + expect(content.title, isNull); + }); + + test('CW があれば CW の見出しだけを出し、本文は出さない', () { + final content = MastodonPushRefetch.contentFromNotification( + _mention(spoiler: 'ネタバレ', content: '

犯人は

'), + ); + expect(content.body, 'ネタバレ'); + }); + + test('投稿の無い通知は相手の表示名、空なら @acct', () { + final follow = MastodonPushRefetch.contentFromNotification({ + 'id': '1', + 'type': 'follow', + 'account': {'acct': 'bob', 'display_name': 'ボブ'}, + }); + expect(follow.body, 'ボブ'); + + final noName = MastodonPushRefetch.contentFromNotification({ + 'id': '2', + 'type': 'follow', + 'account': {'acct': 'bob', 'display_name': ' '}, + }); + expect(noName.body, '@bob'); + }); + }); + + group('isFresh', () { + test('60 秒以内なら採る・過ぎたら採らない', () { + expect( + MastodonPushRefetch.isFresh( + _mention(createdAt: _now.subtract(const Duration(seconds: 60))), + _now, + ), + isTrue, + ); + expect( + MastodonPushRefetch.isFresh( + _mention(createdAt: _now.subtract(const Duration(seconds: 61))), + _now, + ), + isFalse, + ); + }); + + test('日時が読めなければ採らない', () { + expect(MastodonPushRefetch.isFresh({'created_at': 'きのう'}, _now), isFalse); + expect(MastodonPushRefetch.isFresh({}, _now), isFalse); + }); + }); + + group('accept', () { + test('同じ通知は二度出さない', () async { + final first = await MastodonPushRefetch.accept( + _mention(), + account: 'konchie@fedibird.com', + now: _now, + ); + final second = await MastodonPushRefetch.accept( + _mention(), + account: 'konchie@fedibird.com', + now: _now, + ); + expect(first, isNotNull); + expect(second, isNull); + }); + + test('復号できて出した通知(noteShown 済み)は引き直しで出さない', () async { + await MastodonPushRefetch.noteShown('100', 'konchie@fedibird.com'); + final result = await MastodonPushRefetch.accept( + _mention(), + account: 'konchie@fedibird.com', + now: _now, + ); + expect(result, isNull); + }); + + test('控えはアカウントごと', () async { + await MastodonPushRefetch.noteShown('100', 'konchie@pawoo.net'); + final result = await MastodonPushRefetch.accept( + _mention(), + account: 'konchie@fedibird.com', + now: _now, + ); + expect(result, isNotNull); + }); + + test('控えは直近 8 件だけ残す', () async { + for (var i = 0; i < 10; i++) { + await MastodonPushRefetch.noteShown('$i', 'a@example.com'); + } + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getStringList('capsicum_push_shown_ids_a@example.com'), [ + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + ]); + }); + }); + + group('fetchLatest', () { + test('Mastodon 系のトークンが無ければ API を叩かない', () async { + final adapter = _Adapter(200, '[]'); + MastodonPushRefetch.dioFactory = () => Dio()..httpClientAdapter = adapter; + MastodonPushRefetch.tokenReader = (_) async => null; + + final result = await MastodonPushRefetch.fetchLatest( + 'someone@misskey.example', + now: () => _now, + ); + expect(result, isNull); + expect(adapter.calls, 0); + }); + + test('最新の 1 件を Bearer で引き、中身を返す', () async { + final adapter = _Adapter(200, jsonEncode([_mention()])); + MastodonPushRefetch.dioFactory = () => Dio()..httpClientAdapter = adapter; + String? readKey; + MastodonPushRefetch.tokenReader = (key) async { + readKey = key; + return 'tok'; + }; + + final result = await MastodonPushRefetch.fetchLatest( + 'konchie@fedibird.com', + now: () => _now, + ); + expect(readKey, 'mastodon://konchie@fedibird.com'); + expect( + adapter.lastUri.toString(), + 'https://fedibird.com/api/v1/notifications?limit=1', + ); + expect(adapter.lastAuth, 'Bearer tok'); + expect(result?.body, 'こんにちは\nまた明日'); + }); + + test('HTTP の失敗・0 件・古い通知では null', () async { + MastodonPushRefetch.tokenReader = (_) async => 'tok'; + for (final adapter in [ + _Adapter(401, '{"error":"x"}'), + _Adapter(200, '[]'), + _Adapter( + 200, + jsonEncode([ + _mention(createdAt: _now.subtract(const Duration(minutes: 5))), + ]), + ), + ]) { + MastodonPushRefetch.dioFactory = () => + Dio()..httpClientAdapter = adapter; + final result = await MastodonPushRefetch.fetchLatest( + 'konchie@fedibird.com', + now: () => _now, + ); + expect(result, isNull); + } + }); + }); +} + +class _Adapter implements HttpClientAdapter { + _Adapter(this.status, this.body); + + final int status; + final String body; + int calls = 0; + Uri? lastUri; + String? lastAuth; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + calls++; + lastUri = options.uri; + lastAuth = options.headers['Authorization'] as String?; + return ResponseBody.fromString( + body, + status, + headers: { + Headers.contentTypeHeader: [Headers.jsonContentType], + }, + ); + } + + @override + void close({bool force = false}) {} +} diff --git a/packages/capsicum/test/mulukhiya_handlers_screen_test.dart b/packages/capsicum/test/mulukhiya_handlers_screen_test.dart index cfd721651..77420c06d 100644 --- a/packages/capsicum/test/mulukhiya_handlers_screen_test.dart +++ b/packages/capsicum/test/mulukhiya_handlers_screen_test.dart @@ -196,4 +196,60 @@ void main() { ); expect(find.text('切り替えられる処理はありません。'), findsOneWidget); }); + + // #1420: 上書きはハンドラー名だけをキーにしていたので、画面を開いたまま + // アカウントを切り替えると、前のアカウントの上書きが残っていた。 + testWidgets('⚠⚠ アカウントを切り替えると、前のアカウントの上書きを持ち込まない', (tester) async { + when( + () => mulukhiya.setUserHandlerDisabled( + accessToken: any(named: 'accessToken'), + handler: any(named: 'handler'), + disabled: any(named: 'disabled'), + ), + ).thenAnswer((_) async => true); + final other = _Mulukhiya(); + when(() => other.userHandlerConfigEnabled).thenReturn(true); + when( + () => other.getUserHandlers(accessToken: any(named: 'accessToken')), + ).thenAnswer((_) async => [_tagHandler, _urlHandler, _spotifyHandler]); + final otherAccount = Account( + key: const AccountKey( + type: BackendType.mastodon, + host: 'other.example', + username: 'me', + ), + adapter: _Adapter(), + user: const User(id: '2', username: 'me'), + userSecret: const UserSecret(accessToken: 'tok2'), + mulukhiya: other, + ); + final holder = StateProvider((_) => _account(mulukhiya)); + await tester.pumpWidget( + ProviderScope( + overrides: [ + currentAccountProvider.overrideWith((ref) => ref.watch(holder)), + ], + child: const MaterialApp(home: MulukhiyaHandlersScreen()), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap( + find.byKey(const ValueKey('mulukhiya-handler-url_normalize')), + ); + await tester.pumpAndSettle(); + expect(tile(tester, 'url_normalize').value, isFalse); + + final container = ProviderScope.containerOf( + tester.element(find.byType(MulukhiyaHandlersScreen)), + ); + container.read(holder.notifier).state = otherAccount; + await tester.pumpAndSettle(); + + expect( + tile(tester, 'url_normalize').value, + isTrue, + reason: '切り替え先のサーバーの値(オン)で出る', + ); + }); } diff --git a/packages/capsicum/test/push_disabled_accounts_test.dart b/packages/capsicum/test/push_disabled_accounts_test.dart index d2ab84184..1d29e8d94 100644 --- a/packages/capsicum/test/push_disabled_accounts_test.dart +++ b/packages/capsicum/test/push_disabled_accounts_test.dart @@ -64,6 +64,35 @@ void main() { }); group('登録状況の表示', () { + // #1420: オフにする途中で relay への登録が落ちた回。 + test('⚠⚠ オフの印があって失敗なら「オフ」を先に言い、再試行は残す', () { + final (text, _, _) = describePushRegistrationStatus( + ThemeData(), + PushRegistrationState.failed, + true, + null, + disabledByUser: true, + ); + expect(text, startsWith('オフ')); + expect( + isPushRegistrationRetryable( + PushRegistrationState.failed, + eligible: true, + ), + isTrue, + ); + }); + + test('オフの印が無ければ、失敗は失敗のまま', () { + final (text, _, _) = describePushRegistrationStatus( + ThemeData(), + PushRegistrationState.failed, + true, + null, + ); + expect(text, '登録に失敗しました'); + }); + test('「オフ」と出し、再試行は出さない(失敗ではない)', () { final (text, _, _) = describePushRegistrationStatus( ThemeData(), diff --git a/packages/capsicum/test/push_muted_alerts_test.dart b/packages/capsicum/test/push_muted_alerts_test.dart new file mode 100644 index 000000000..2029762e5 --- /dev/null +++ b/packages/capsicum/test/push_muted_alerts_test.dart @@ -0,0 +1,134 @@ +// #1411: 通知の種類ごとにプッシュ通知をオン / オフする(Mastodon 系だけ)。 +import 'package:capsicum/src/service/push_muted_alerts.dart'; +import 'package:capsicum/src/ui/screen/settings/push_notification_settings_screen.dart'; +import 'package:capsicum/src/ui/util/notification_type_display.dart'; +import 'package:capsicum/src/util/shared_preferences_cache.dart'; +import 'package:capsicum_core/capsicum_core.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const a = 'mastodon://a@x.example'; + const b = 'mastodon://b@y.example'; + + group('PushMutedAlerts', () { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + initSharedPreferencesCache(await SharedPreferences.getInstance()); + }); + tearDown(() => debugSetSharedPreferencesCache(null)); + + test('既定は空(全部受け取る)', () { + expect(PushMutedAlerts.mutedFor(a), isEmpty); + }); + + test('アカウントごとに持つ', () async { + await PushMutedAlerts.setMuted(a, {PushAlertCategory.favourite}); + + expect(PushMutedAlerts.mutedFor(a), {PushAlertCategory.favourite}); + expect(PushMutedAlerts.mutedFor(b), isEmpty); + }); + + test('空に戻すと消え、全員が空ならキーごと消す', () async { + await PushMutedAlerts.setMuted(a, {PushAlertCategory.reblog}); + await PushMutedAlerts.setMuted(a, const {}); + + expect(PushMutedAlerts.mutedFor(a), isEmpty); + expect(sharedPrefsOrThrow.containsKey(PushMutedAlerts.prefsKey), isFalse); + }); + + test('⚠ 知らない分類の名前は読み飛ばす(版を戻したとき)', () async { + await sharedPrefsOrThrow.setString( + PushMutedAlerts.prefsKey, + '{"$a": ["favourite", "future_kind"]}', + ); + + expect(PushMutedAlerts.mutedFor(a), {PushAlertCategory.favourite}); + }); + + test('⚠ 読めなければ空(黙って通知を止めない)', () { + debugSetSharedPreferencesCache(null); + expect(PushMutedAlerts.mutedFor(a), isEmpty); + }); + + test('削除で捨てる。⚠ 投げない', () async { + await PushMutedAlerts.setMuted(a, {PushAlertCategory.poll}); + await PushMutedAlerts.forget(a); + expect(PushMutedAlerts.mutedFor(a), isEmpty); + + debugSetSharedPreferencesCache(null); + await PushMutedAlerts.forget(a); + }); + }); + + test('分類の名前は通知の一覧と同じ', () { + expect(pushAlertCategoryLabel(PushAlertCategory.mention), 'メンション'); + expect(pushAlertCategoryLabel(PushAlertCategory.favourite), 'お気に入り'); + expect(pushAlertCategoryLabel(PushAlertCategory.follow), 'フォロー・フォローリクエスト'); + }); + + group('種類のシート', () { + Future?> openAndPop( + WidgetTester tester, + Set initial, + Future Function() act, + ) async { + Set? result; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () async { + result = await showModalBottomSheet>( + context: context, + isScrollControlled: true, + builder: (_) => PushAlertTypesSheet(initialMuted: initial), + ); + }, + child: const Text('open'), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + await act(); + return result; + } + + testWidgets('切ったものを「完了」で返す', (tester) async { + final result = await openAndPop(tester, const {}, () async { + await tester.tap(find.byKey(const ValueKey('push-alert-favourite'))); + await tester.pumpAndSettle(); + await tester.ensureVisible( + find.byKey(const ValueKey('push-alert-types-done')), + ); + await tester.tap(find.byKey(const ValueKey('push-alert-types-done'))); + await tester.pumpAndSettle(); + }); + + expect(result, {PushAlertCategory.favourite}); + }); + + testWidgets('切ってあったものを戻せる', (tester) async { + final result = await openAndPop( + tester, + {PushAlertCategory.reblog}, + () async { + await tester.tap(find.byKey(const ValueKey('push-alert-reblog'))); + await tester.pumpAndSettle(); + await tester.ensureVisible( + find.byKey(const ValueKey('push-alert-types-done')), + ); + await tester.tap(find.byKey(const ValueKey('push-alert-types-done'))); + await tester.pumpAndSettle(); + }, + ); + + expect(result, isEmpty); + }); + }); +} diff --git a/packages/capsicum/test/push_title_recipient_test.dart b/packages/capsicum/test/push_title_recipient_test.dart index 12184107c..78e041d2e 100644 --- a/packages/capsicum/test/push_title_recipient_test.dart +++ b/packages/capsicum/test/push_title_recipient_test.dart @@ -12,6 +12,7 @@ import 'package:capsicum/src/provider/account_manager_provider.dart'; import 'package:capsicum/src/service/notification_label_cache.dart'; import 'package:capsicum_backends/capsicum_backends.dart'; import 'package:capsicum_core/capsicum_core.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; @@ -132,6 +133,19 @@ void main() { expect(await NotificationLabelCache.readMultiAccount(), isFalse); }); + // #1420: 起動直後の空の状態で「単数」を書くと、復元が済むまでに届いた + // バックグラウンドのプッシュに宛先が付かない。 + test('⚠⚠ 最初の build(空の状態)では、前回の写しを上書きしない', () async { + await NotificationLabelCache.saveMultiAccount(true); + final container = ProviderContainer(); + addTearDown(container.dispose); + + expect(container.read(accountManagerProvider).accounts, isEmpty); + await pumpEventQueue(); + + expect(await NotificationLabelCache.readMultiAccount(), isTrue); + }); + test('プラットフォームが無くても同期で投げない(呼び出し側の catchError で受けられる)', () async { SharedPreferencesAsyncPlatform.instance = null; final future = NotificationLabelCache.saveMultiAccount(true); diff --git a/packages/capsicum/test/timeline_type_label_guard_test.dart b/packages/capsicum/test/timeline_type_label_guard_test.dart index 1c38c4c90..2cbf9cb28 100644 --- a/packages/capsicum/test/timeline_type_label_guard_test.dart +++ b/packages/capsicum/test/timeline_type_label_guard_test.dart @@ -55,9 +55,11 @@ void main() { expect(offenders, isEmpty); }); + // ⚠ タブの見出し(`tabLabel`)は #1420 で home_menu.dart から deck_tabs.dart へ + // 移した。上の「修正前」は当時の置き場のままでよい(git の過去の版を見る)。 test('2 画面とも正本へ委譲している', () { for (final path in [ - 'lib/src/ui/widget/home_menu.dart', + 'lib/src/ui/util/deck_tabs.dart', 'lib/src/ui/widget/tab_management_sheet.dart', ]) { expect( diff --git a/packages/capsicum_backends/lib/src/mastodon/adapter.dart b/packages/capsicum_backends/lib/src/mastodon/adapter.dart index 6522e051d..eb55404df 100644 --- a/packages/capsicum_backends/lib/src/mastodon/adapter.dart +++ b/packages/capsicum_backends/lib/src/mastodon/adapter.dart @@ -2301,10 +2301,24 @@ class MastodonAdapter extends DecentralizedBackendAdapter required String endpoint, required String p256dh, required String auth, + Set mutedCategories = const {}, }) async { - return client.subscribePush(endpoint: endpoint, p256dh: p256dh, auth: auth); + return client.subscribePush( + endpoint: endpoint, + p256dh: p256dh, + auth: auth, + mutedTypes: mastodonMutedAlertTypes(mutedCategories), + ); } + /// `data[alerts]` で絞れる (#1411)。 + /// + /// ⚠ Akkoma も同じアダプターで通るが、`data[alerts]` を Mastodon と同じに読むかは + /// **未確認**(手元にソースが無い・#1411 の着手時)。読まなければ絞りが効かない + /// だけで、今どおり全部届く(壊れはしない)。 + @override + bool get supportsPushAlertFilter => true; + @override Future unsubscribePush({ String? endpoint, diff --git a/packages/capsicum_backends/lib/src/mastodon/client.dart b/packages/capsicum_backends/lib/src/mastodon/client.dart index 8fccd3d57..36da92685 100644 --- a/packages/capsicum_backends/lib/src/mastodon/client.dart +++ b/packages/capsicum_backends/lib/src/mastodon/client.dart @@ -159,6 +159,27 @@ const pushAlertTypes = [ 'collection_update', ]; +/// 利用者の分類 → Mastodon の `data[alerts]` の種別 (#1411)。 +/// +/// ⚠ ここに無い種別([pushAlertTypes] の残り)は絞らず、常に受け取る。 +/// ⚠⚠ **ここの値はすべて [pushAlertTypes] に含まれていること**(表に無い種別を +/// 絞っても、購読の本文に載らないので効かない)。テストで固定している。 +const mastodonAlertTypesByCategory = >{ + PushAlertCategory.mention: ['mention'], + PushAlertCategory.favourite: ['favourite'], + PushAlertCategory.reblog: ['reblog'], + PushAlertCategory.follow: ['follow', 'follow_request'], + PushAlertCategory.poll: ['poll'], + PushAlertCategory.status: ['status'], + PushAlertCategory.update: ['update', 'quoted_update'], + PushAlertCategory.quote: ['quote'], +}; + +/// [muted] の分類を、送らなくさせる Mastodon の種別にする (#1411)。 +Set mastodonMutedAlertTypes(Set muted) => { + for (final category in muted) ...?mastodonAlertTypesByCategory[category], +}; + class MastodonClient { final Dio dio; final String host; @@ -1875,10 +1896,15 @@ class MastodonClient { /// これらヘッダを転送していないため、legacy 経路ではクライアント側復号 /// (#336)が不可能。modern 経路ならペイロード本体に salt / keyid が /// 含まれるので Base64 の body 単体で復号できる。 + /// + /// [mutedTypes] は送らなくさせる種別 (#1411・[mastodonMutedAlertTypes])。 + /// ⚠ **`false` を明示して送る。**省くとサーバーの既定(`false`)と同じだが、 + /// 送る種別の表が 1 本のままになるので、どれを絞ったかが本文で読める。 Future> subscribePush({ required String endpoint, required String p256dh, required String auth, + Set mutedTypes = const {}, }) async { final response = await dio.post( '/api/v1/push/subscription', @@ -1887,7 +1913,8 @@ class MastodonClient { 'subscription[standard]': 'true', 'subscription[keys][p256dh]': p256dh, 'subscription[keys][auth]': auth, - for (final type in pushAlertTypes) 'data[alerts][$type]': 'true', + for (final type in pushAlertTypes) + 'data[alerts][$type]': mutedTypes.contains(type) ? 'false' : 'true', }), ); return response.data as Map; diff --git a/packages/capsicum_backends/lib/src/misskey/adapter.dart b/packages/capsicum_backends/lib/src/misskey/adapter.dart index fa5837ffb..0dd5c4f08 100644 --- a/packages/capsicum_backends/lib/src/misskey/adapter.dart +++ b/packages/capsicum_backends/lib/src/misskey/adapter.dart @@ -165,6 +165,7 @@ class MisskeyAdapter extends DecentralizedBackendAdapter ChannelManagementSupport, ClipSupport, ClipManagementSupport, + ClipFavoriteSupport, FlashSupport, GallerySupport, AntennaSupport, @@ -260,6 +261,10 @@ class MisskeyAdapter extends DecentralizedBackendAdapter // ギャラリーのいいね / 取り消し (#1053)。旧トークンは 403 で、再ログインを // 案内する(Play のいいねと同じ)。 'write:gallery-likes', + // ほかの人のクリップのお気に入りと、その一覧 (#1377)。旧トークンは 403 で、 + // 再ログインを案内する(ギャラリーのいいねと同じ)。 + 'read:clip-favorite', + 'write:clip-favorite', 'read:reactions', 'write:reactions', 'write:report-abuse', @@ -2481,6 +2486,52 @@ class MisskeyAdapter extends DecentralizedBackendAdapter Future removeNoteFromClip(String clipId, String noteId) => _clipWrite(() => client.removeNoteFromClip(clipId, noteId)); + // ClipFavoriteSupport (#1377) + + @override + Future> getUserClips( + String userId, { + TimelineQuery? query, + }) async { + final data = await client.getUserClips( + userId, + untilId: query?.maxId, + limit: query?.limit, + ); + return data.map(misskeyClipFromJson).toList(); + } + + @override + Future getClip(String clipId) => _clipWrite( + () async => misskeyClipFromJson(await client.showClip(clipId)), + ); + + @override + Future> getFavoriteClips() async { + final data = await client.getFavoriteClips(); + return data.map(misskeyClipFromJson).toList(); + } + + @override + Future favoriteClip(String clipId) async { + try { + await _clipWrite(() => client.favoriteClip(clipId)); + } on DioException catch (e) { + // 既に入っていた(Web など)。入れるという目的は果たしている。 + if (!_hasErrorCode(e, 'ALREADY_FAVORITED')) rethrow; + } + } + + @override + Future unfavoriteClip(String clipId) async { + try { + await _clipWrite(() => client.unfavoriteClip(clipId)); + } on DioException catch (e) { + // もう外れていた。外すという目的は果たしている。 + if (!_hasErrorCode(e, 'NOT_FAVORITED')) rethrow; + } + } + @override Future> getPublicClipIdsContaining(String noteId) async { final data = await client.getClipsContainingNote(noteId); @@ -2886,6 +2937,8 @@ class MisskeyAdapter extends DecentralizedBackendAdapter required String endpoint, required String p256dh, required String auth, + // ⚠ Misskey には種類で絞る口が無い([supportsPushAlertFilter] は false)。 + Set mutedCategories = const {}, }) async { try { return await client.subscribePush( diff --git a/packages/capsicum_backends/lib/src/misskey/client.dart b/packages/capsicum_backends/lib/src/misskey/client.dart index d2cc50f10..bfc62de71 100644 --- a/packages/capsicum_backends/lib/src/misskey/client.dart +++ b/packages/capsicum_backends/lib/src/misskey/client.dart @@ -1722,6 +1722,54 @@ class MisskeyClient { ); } + /// POST /api/users/clips (#1377)。その人の公開のクリップ。 + Future>> getUserClips( + String userId, { + String? untilId, + int? limit, + }) async { + final response = await dio.post( + '/api/users/clips', + data: createBody({ + 'userId': userId, + 'untilId': ?untilId, + 'limit': ?limit, + }), + ); + return (response.data as List).cast>(); + } + + /// POST /api/clips/show (#1377) + Future> showClip(String clipId) async { + final response = await dio.post( + '/api/clips/show', + data: createBody({'clipId': clipId}), + ); + return response.data as Map; + } + + /// POST /api/clips/my-favorites (#1377) + Future>> getFavoriteClips() async { + final response = await dio.post( + '/api/clips/my-favorites', + data: createBody({}), + ); + return (response.data as List).cast>(); + } + + /// POST /api/clips/favorite (#1377) + Future favoriteClip(String clipId) async { + await dio.post('/api/clips/favorite', data: createBody({'clipId': clipId})); + } + + /// POST /api/clips/unfavorite (#1377) + Future unfavoriteClip(String clipId) async { + await dio.post( + '/api/clips/unfavorite', + data: createBody({'clipId': clipId}), + ); + } + /// POST /api/notes/clips (#1050)。⚠ 公開のクリップしか返らない(ほかの人の /// ものも含む)。 Future>> getClipsContainingNote( diff --git a/packages/capsicum_backends/lib/src/misskey/clip_mapping.dart b/packages/capsicum_backends/lib/src/misskey/clip_mapping.dart index 043348f19..6ecebffdb 100644 --- a/packages/capsicum_backends/lib/src/misskey/clip_mapping.dart +++ b/packages/capsicum_backends/lib/src/misskey/clip_mapping.dart @@ -3,13 +3,28 @@ import 'package:capsicum_core/capsicum_core.dart'; /// `clips/list` などの 1 件を [NoteClip] にする (#1050)。 /// /// ⚠ 欠けている項目は既定で埋める(古い版のサーバー・フォーク)。 -NoteClip misskeyClipFromJson(Map json) => NoteClip( - id: json['id'] as String, - name: json['name'] as String? ?? '', - description: json['description'] as String?, - isPublic: json['isPublic'] as bool? ?? false, - userId: json['userId'] as String?, -); +NoteClip misskeyClipFromJson(Map json) { + // 持ち主(UserLite)。表示名が空なら username で代える (#1377)。 + final user = json['user']; + String? ownerName; + if (user is Map) { + final name = user['name']; + final username = user['username']; + ownerName = name is String && name.isNotEmpty + ? name + : (username is String && username.isNotEmpty ? username : null); + } + final isFavorited = json['isFavorited']; + return NoteClip( + id: json['id'] as String, + name: json['name'] as String? ?? '', + description: json['description'] as String?, + isPublic: json['isPublic'] as bool? ?? false, + userId: json['userId'] as String?, + ownerName: ownerName, + isFavorited: isFavorited is bool ? isFavorited : null, + ); +} /// `clips/create` / `clips/update` の引数 (#1050)。 /// diff --git a/packages/capsicum_backends/lib/src/mulukhiya/service.dart b/packages/capsicum_backends/lib/src/mulukhiya/service.dart index dcabed9c2..a39931182 100644 --- a/packages/capsicum_backends/lib/src/mulukhiya/service.dart +++ b/packages/capsicum_backends/lib/src/mulukhiya/service.dart @@ -1437,6 +1437,47 @@ class MulukhiyaService { return data is Map ? data['disabled'] == true : disabled; } + /// 実況のために付けたアイコンデコの状態 (capsicum#1409・mulukhiya#4912)。 + /// GET /mulukhiya/api/decoration/live + /// + /// ⚠ **404 は null**(「出さない」)。デコに対応していない SNS(Misskey 以外)と、 + /// この口を持たない 5.48.0 より前のモロヘイヤの両方が 404 を返す。`features` に + /// 印は無いので、見分けは 404 で行う(着手時の判断・#1409)。 + Future getLiveDecoration({ + required String accessToken, + }) async { + try { + final response = await _dio.get( + '$baseUrl/decoration/live', + options: _bearerOptions(accessToken), + ); + final data = response.data; + return data is Map + ? MulukhiyaLiveDecoration.fromJson(data) + : null; + } on DioException catch (e) { + if (e.response?.statusCode == 404) return null; + rethrow; + } + } + + /// 実況のために付けたデコを、番組の終わりを待たずに外す + /// (capsicum#1409・mulukhiya#4912)。POST /mulukhiya/api/decoration/restore + /// + /// 外すのは付けた 1 つだけ。通知は送られない(利用者が自分で戻したため)。 + /// ⚠ 実況中でなければ 404(もう外れている)—— 呼ぶ側は成功と同じに扱ってよい。 + Future restoreLiveDecoration({required String accessToken}) async { + try { + await _dio.post( + '$baseUrl/decoration/restore', + options: _bearerOptions(accessToken), + ); + } on DioException catch (e) { + if (e.response?.statusCode == 404) return; + rethrow; + } + } + /// 投稿テンプレート一覧を取得する (#767)。 /// GET /mulukhiya/api/compose/templates Future> getComposeTemplates({ diff --git a/packages/capsicum_backends/test/mastodon_push_alert_types_test.dart b/packages/capsicum_backends/test/mastodon_push_alert_types_test.dart index aa7323487..393a546d6 100644 --- a/packages/capsicum_backends/test/mastodon_push_alert_types_test.dart +++ b/packages/capsicum_backends/test/mastodon_push_alert_types_test.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'package:capsicum_backends/capsicum_backends.dart'; +import 'package:capsicum_core/capsicum_core.dart'; import 'package:dio/dio.dart'; import 'package:test/test.dart'; @@ -151,4 +152,66 @@ void main() { expect(capture.fields.containsKey('data[policy]'), isFalse); }); }); + + // #1411: 通知の種類ごとにプッシュ通知をオン / オフする。 + group('通知の分類で絞る (#1411)', () { + test('⚠⚠ 分類が指す種別は、すべて送っている種別に含まれる', () { + // 表に無い種別を絞っても、購読の本文に載らないので効かない。 + for (final types in mastodonAlertTypesByCategory.values) { + for (final type in types) { + expect(pushAlertTypes, contains(type)); + } + } + }); + + test('すべての分類に行き先がある', () { + expect( + mastodonAlertTypesByCategory.keys.toSet(), + PushAlertCategory.values.toSet(), + ); + }); + + test('⚠ 分類に入らない種別(警告・通報など)は絞れない', () { + final filterable = mastodonMutedAlertTypes( + PushAlertCategory.values.toSet(), + ); + expect(filterable, isNot(contains('moderation_warning'))); + expect(filterable, isNot(contains('admin.report'))); + expect(filterable, isNot(contains('severed_relationships'))); + }); + + test('切った分類だけ false で送り、ほかは true のまま', () async { + final adapter = await MastodonAdapter.create('mastodon.example'); + final capture = _CapturingAdapter(); + adapter.client.dio.httpClientAdapter = capture; + + await adapter.subscribePush( + endpoint: 'https://relay.example/push/abc', + p256dh: 'p256dh-dummy', + auth: 'auth-dummy', + mutedCategories: { + PushAlertCategory.favourite, + PushAlertCategory.follow, + }, + ); + + expect(capture.fields['data[alerts][favourite]'], 'false'); + expect(capture.fields['data[alerts][follow]'], 'false'); + expect(capture.fields['data[alerts][follow_request]'], 'false'); + expect(capture.fields['data[alerts][mention]'], 'true'); + expect(capture.fields['data[alerts][reblog]'], 'true'); + expect(capture.fields['data[alerts][moderation_warning]'], 'true'); + }); + + test('Mastodon は絞れる・Misskey は絞れない', () async { + expect( + (await MastodonAdapter.create('m.example')).supportsPushAlertFilter, + isTrue, + ); + expect( + (await MisskeyAdapter.create('k.example')).supportsPushAlertFilter, + isFalse, + ); + }); + }); } diff --git a/packages/capsicum_backends/test/misskey_clip_test.dart b/packages/capsicum_backends/test/misskey_clip_test.dart index d9c80456e..8492cd7d7 100644 --- a/packages/capsicum_backends/test/misskey_clip_test.dart +++ b/packages/capsicum_backends/test/misskey_clip_test.dart @@ -230,4 +230,100 @@ void main() { expect(server.calls['/api/notes/clips'], containsPair('noteId', 'n1')); }); }); + + // #1377: ほかの人のクリップを見る・お気に入りに入れる。 + group('ほかの人のクリップ', () { + test('users/clips は userId を送り、持ち主の名前とお気に入りの状態を読む', () async { + final server = await install( + _Server( + responses: { + '/api/users/clips': [ + { + 'id': 'c1', + 'name': '名場面', + 'userId': 'u1', + 'isPublic': true, + 'isFavorited': true, + 'user': {'username': 'alice', 'name': 'アリス'}, + }, + { + 'id': 'c2', + 'name': '名前の無い人', + 'user': {'username': 'bob', 'name': ''}, + }, + ], + }, + ), + ); + + final clips = await adapter.getUserClips( + 'u1', + query: const TimelineQuery(limit: 20, maxId: 'c0'), + ); + + expect(server.calls['/api/users/clips'], containsPair('userId', 'u1')); + expect(server.calls['/api/users/clips'], containsPair('untilId', 'c0')); + expect(clips.first.ownerName, 'アリス'); + expect(clips.first.isFavorited, isTrue); + expect(clips.last.ownerName, 'bob', reason: '表示名が空なら username'); + expect(clips.last.isFavorited, isNull, reason: '分からなければ null'); + }); + + test('お気に入りに入れる・外すは clipId を送る', () async { + final server = await install(_Server()); + + await adapter.favoriteClip('c1'); + await adapter.unfavoriteClip('c1'); + + expect(server.calls['/api/clips/favorite'], containsPair('clipId', 'c1')); + expect( + server.calls['/api/clips/unfavorite'], + containsPair('clipId', 'c1'), + ); + }); + + test('⚠ 既に入っていた / もう外れていたは成功として扱う', () async { + await install( + _Server( + errors: { + '/api/clips/favorite': 'ALREADY_FAVORITED', + '/api/clips/unfavorite': 'NOT_FAVORITED', + }, + ), + ); + + await adapter.favoriteClip('c1'); + await adapter.unfavoriteClip('c1'); + }); + + test('消えたクリップ(NO_SUCH_CLIP)は ClipNotFound', () async { + await install( + _Server( + errors: { + '/api/clips/favorite': 'NO_SUCH_CLIP', + '/api/clips/show': 'NO_SUCH_CLIP', + }, + ), + ); + + expect(adapter.favoriteClip('gone'), throwsA(isA())); + expect(adapter.getClip('gone'), throwsA(isA())); + }); + + test('お気に入りの一覧を引く', () async { + await install( + _Server( + responses: { + '/api/clips/my-favorites': [ + {'id': 'c9', 'name': 'お気に入り', 'userId': 'u2'}, + ], + }, + ), + ); + + final clips = await adapter.getFavoriteClips(); + + expect(clips.single.id, 'c9'); + }); + }); } diff --git a/packages/capsicum_backends/test/mulukhiya_live_decoration_test.dart b/packages/capsicum_backends/test/mulukhiya_live_decoration_test.dart new file mode 100644 index 000000000..9f943f4af --- /dev/null +++ b/packages/capsicum_backends/test/mulukhiya_live_decoration_test.dart @@ -0,0 +1,113 @@ +import 'dart:convert'; + +import 'package:capsicum_backends/capsicum_backends.dart'; +import 'package:dio/dio.dart'; +import 'package:test/test.dart'; + +/// #1409: 実況のためにモロヘイヤが付けたデコ(mulukhiya#4912・5.48.0)。 +/// +/// ⚠ `features` に印は無いので、口が無いこと(Misskey 以外・5.48.0 より前)は +/// 404 で見分ける。 +class _Adapter implements HttpClientAdapter { + _Adapter({this.liveStatus = 200, this.restoreStatus = 200, this.live}); + + final int liveStatus; + final int restoreStatus; + final Map? live; + + RequestOptions? liveRequest; + RequestOptions? restoreRequest; + + @override + Future fetch( + RequestOptions options, + Stream>? requestStream, + Future? cancelFuture, + ) async { + final path = options.uri.path; + if (path.endsWith('/decoration/live')) { + liveRequest = options; + return _json(live ?? {'live': false}, liveStatus); + } + if (path.endsWith('/decoration/restore')) { + restoreRequest = options; + return _json({'config': {}}, restoreStatus); + } + return _json({ + 'package': {'version': '5.48.0'}, + 'config': {'controller': 'misskey', 'features': {}}, + }, 200); + } + + ResponseBody _json(Object body, int status) => ResponseBody.fromString( + jsonEncode(body), + status, + headers: { + Headers.contentTypeHeader: ['application/json'], + }, + ); + + @override + void close({bool force = false}) {} +} + +Future<({MulukhiyaService service, _Adapter http})> _build({ + int liveStatus = 200, + int restoreStatus = 200, + Map? live, +}) async { + final http = _Adapter( + liveStatus: liveStatus, + restoreStatus: restoreStatus, + live: live, + ); + final dio = Dio()..httpClientAdapter = http; + final service = await MulukhiyaService.detect(dio, 'h.example'); + return (service: service!, http: http); +} + +void main() { + group('getLiveDecoration', () { + test('bearer を付けて引き、応答を読む', () async { + final built = await _build( + live: {'live': true, 'id': 'd1', 'name': '実況中'}, + ); + final live = await built.service.getLiveDecoration(accessToken: 'tok'); + + expect(built.http.liveRequest?.headers['Authorization'], 'Bearer tok'); + expect(live?.live, isTrue); + expect(live?.id, 'd1'); + }); + + test('⚠⚠ 404(口が無い)は null(出さない)', () async { + final built = await _build(liveStatus: 404); + expect(await built.service.getLiveDecoration(accessToken: 'tok'), isNull); + }); + + test('⚠ 404 以外の失敗は投げる(呼ぶ側が一過性として握る)', () async { + final built = await _build(liveStatus: 500); + await expectLater( + built.service.getLiveDecoration(accessToken: 'tok'), + throwsA(isA()), + ); + }); + }); + + group('restoreLiveDecoration', () { + test('POST で外す', () async { + final built = await _build(); + await built.service.restoreLiveDecoration(accessToken: 'tok'); + + expect(built.http.restoreRequest?.method, 'POST'); + expect(built.http.restoreRequest?.headers['Authorization'], 'Bearer tok'); + }); + + test('⚠ 404(もう外れている)は成功と同じに扱う', () async { + final built = await _build(restoreStatus: 404); + await expectLater( + built.service.restoreLiveDecoration(accessToken: 'tok'), + completes, + ); + }); + }); +} diff --git a/packages/capsicum_core/lib/capsicum_core.dart b/packages/capsicum_core/lib/capsicum_core.dart index 12932fbf3..e28a9f1fa 100644 --- a/packages/capsicum_core/lib/capsicum_core.dart +++ b/packages/capsicum_core/lib/capsicum_core.dart @@ -23,6 +23,7 @@ export 'src/model/flash.dart'; export 'src/model/gallery_post.dart'; export 'src/model/hashtag_spec.dart'; export 'src/model/instance.dart'; +export 'src/model/mulukhiya_live_decoration.dart'; export 'src/model/mulukhiya_user_handler.dart'; export 'src/model/notification.dart'; export 'src/model/notification_query.dart'; diff --git a/packages/capsicum_core/lib/src/model/clip.dart b/packages/capsicum_core/lib/src/model/clip.dart index f3b6f88f0..fd21efb3f 100644 --- a/packages/capsicum_core/lib/src/model/clip.dart +++ b/packages/capsicum_core/lib/src/model/clip.dart @@ -10,12 +10,22 @@ class NoteClip { /// 自分のものを選ぶのに使う。読めなければ null。 final String? userId; + /// 作った人の表示名 (#1377)。お気に入りのクリップの一覧で、誰のクリップかを + /// 出すのに使う。読めなければ null。 + final String? ownerName; + + /// 自分がお気に入りに入れているか (#1377)。Misskey は認証付きで引いたときだけ + /// 返す。分からなければ null(「入れていない」とは読まない)。 + final bool? isFavorited; + const NoteClip({ required this.id, required this.name, this.description, this.isPublic = false, this.userId, + this.ownerName, + this.isFavorited, }); } diff --git a/packages/capsicum_core/lib/src/model/mulukhiya_live_decoration.dart b/packages/capsicum_core/lib/src/model/mulukhiya_live_decoration.dart new file mode 100644 index 000000000..c5964dc49 --- /dev/null +++ b/packages/capsicum_core/lib/src/model/mulukhiya_live_decoration.dart @@ -0,0 +1,47 @@ +/// 実況のためにモロヘイヤが付けたアイコンデコの状態 (#1409)。 +/// +/// `GET /mulukhiya/api/decoration/live`(モロヘイヤ 5.48.0・#4912)の応答。 +/// 実況中でなければ `{"live": false}` だけが返る。 +class MulukhiyaLiveDecoration { + /// 実況中か。 + final bool live; + + /// 番組の終わりに外すデコの id。 + /// + /// ⚠ **実況を始めたとき既に同じデコを付けていた人には返らない**([live] は + /// true)。利用者のデコなのでモロヘイヤは外さない = capsicum も「外す」を + /// 出さない。 + final String? id; + + /// デコの名前。分からなければ null。 + final String? name; + + /// 番組名。分からなければ null。 + final String? program; + + /// 外れる予定の時刻。分からなければ null。 + final DateTime? restoreAt; + + const MulukhiyaLiveDecoration({ + required this.live, + this.id, + this.name, + this.program, + this.restoreAt, + }); + + /// 番組の終わりを待たずに外せるか([live] で、外す相手が分かっている)。 + bool get restorable => live && id != null; + + factory MulukhiyaLiveDecoration.fromJson(Map json) { + String? text(Object? v) => v is String && v.isNotEmpty ? v : null; + final restoreAt = text(json['restore_at']); + return MulukhiyaLiveDecoration( + live: json['live'] == true, + id: text(json['id']), + name: text(json['name']), + program: text(json['program']), + restoreAt: restoreAt == null ? null : DateTime.tryParse(restoreAt), + ); + } +} diff --git a/packages/capsicum_core/lib/src/social/interfaces/clip_support.dart b/packages/capsicum_core/lib/src/social/interfaces/clip_support.dart index a91068e28..fcb465fac 100644 --- a/packages/capsicum_core/lib/src/social/interfaces/clip_support.dart +++ b/packages/capsicum_core/lib/src/social/interfaces/clip_support.dart @@ -29,6 +29,30 @@ abstract mixin class ClipManagementSupport { Future> getPublicClipIdsContaining(String noteId); } +/// ほかの人のクリップを見る・お気に入りに入れる (#1377)。 +/// +/// ⚠ お気に入りに入れられるのは**ほかの人の公開のクリップ**と自分のクリップ +/// (Misskey の `clips/favorite` は非公開のほかの人のものを `NO_SUCH_CLIP` で断る)。 +/// 画面が出すのはほかの人のクリップだけ。 +abstract mixin class ClipFavoriteSupport { + /// [userId] の公開のクリップ(Misskey の `users/clips`)。 + Future> getUserClips(String userId, {TimelineQuery? query}); + + /// クリップ 1 つ(`clips/show`)。お気に入りの状態と持ち主を見るのに使う。 + /// 消えていたら [ClipNotFound]。 + Future getClip(String clipId); + + /// お気に入りに入れたクリップ(`clips/my-favorites`)。 + Future> getFavoriteClips(); + + /// お気に入りに入れる。⚠ 既に入っていても成功として扱う(目的は果たしている)。 + /// 消えていたら [ClipNotFound]。 + Future favoriteClip(String clipId); + + /// お気に入りから外す。⚠ もう外れていても成功として扱う。 + Future unfavoriteClip(String clipId); +} + /// これ以上クリップを作れない (#1050)。ロールの `clipLimit` に当たった。 class ClipLimitReached implements Exception { const ClipLimitReached(); diff --git a/packages/capsicum_core/lib/src/social/interfaces/gallery_support.dart b/packages/capsicum_core/lib/src/social/interfaces/gallery_support.dart index 4ab493274..b913b04d6 100644 --- a/packages/capsicum_core/lib/src/social/interfaces/gallery_support.dart +++ b/packages/capsicum_core/lib/src/social/interfaces/gallery_support.dart @@ -22,8 +22,12 @@ abstract mixin class GallerySupport { /// いいねする (#1053)。`write:gallery-likes` スコープが要る(旧トークンは /// 再ログインまで 403)。自分の投稿は `YOUR_POST`、いいね済みは /// `ALREADY_LIKED` で断られる。 - Future likeGalleryPost(String postId) async {} + /// + /// ⚠ **既定の実装を持たせない**(#1420)。空の既定があると、`GallerySupport` を + /// 名乗った新しいアダプターが上書きを忘れても通り、画面の楽観更新だけが + /// 成功に見える。 + Future likeGalleryPost(String postId); /// いいねを取り消す (#1053)。いいねしていなければ `NOT_LIKED`。 - Future unlikeGalleryPost(String postId) async {} + Future unlikeGalleryPost(String postId); } diff --git a/packages/capsicum_core/lib/src/social/interfaces/push_subscription_support.dart b/packages/capsicum_core/lib/src/social/interfaces/push_subscription_support.dart index eb39970cc..f2ceb28a3 100644 --- a/packages/capsicum_core/lib/src/social/interfaces/push_subscription_support.dart +++ b/packages/capsicum_core/lib/src/social/interfaces/push_subscription_support.dart @@ -16,6 +16,23 @@ class PushRegistrationNotSupportedException implements Exception { String toString() => 'PushRegistrationNotSupportedException: $message'; } +/// 利用者が種類ごとにプッシュ通知をオン / オフできる通知の分類 (#1411)。 +/// +/// ⚠ サーバーの通知の種類そのものではなく、**利用者に見せる分類**。Mastodon の +/// `data[alerts][]` へはアダプターが写す(例: [follow] は `follow` と +/// `follow_request`、[update] は `update` と `quoted_update`)。ここに無い種類 +/// (管理者からの警告・関係が失われた・新規登録・通報など)は常に受け取る。 +enum PushAlertCategory { + mention, + favourite, + reblog, + follow, + poll, + status, + update, + quote, +} + /// Web Push サブスクリプションの登録・解除を行う Feature インターフェース。 /// /// Mastodon: POST /api/v1/push/subscription, DELETE /api/v1/push/subscription @@ -34,12 +51,25 @@ abstract mixin class PushSubscriptionSupport { /// [auth] 認証シークレット(Base64URL エンコード) /// /// 戻り値: サーバーから返されたサブスクリプション情報(サーバー依存)。 + /// + /// [mutedCategories] 利用者が切った通知の分類 (#1411)。サーバー側で送らなく + /// させる。⚠ **絞る口を持たないサーバー(Misskey)は無視する** + /// ([supportsPushAlertFilter] が false)。 Future> subscribePush({ required String endpoint, required String p256dh, required String auth, + Set mutedCategories = const {}, }); + /// 通知の種類ごとに、サーバー側で送る / 送らないを絞れるか (#1411)。 + /// + /// ⚠ Misskey の `sw/register` には絞る口が無く、payload は暗号化されていて + /// relay も種類を見られない。端末で捨てるには iOS の NSE に特別な entitlement + /// (`com.apple.developer.usernotifications.filtering`)が要るので、Misskey は + /// 対象外にした(#1411 の着手時の判断)。 + bool get supportsPushAlertFilter => false; + /// Web Push サブスクリプションを解除する。 /// /// [endpoint] Misskey の `/api/sw/unregister` は endpoint 必須のため呼び出し diff --git a/pubspec.lock b/pubspec.lock index 5bbf58dd9..373d035f9 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -126,10 +126,10 @@ packages: dependency: transitive description: name: built_value - sha256: f87ea98192116f7093cb214551ce1929caae0681fdba282b3d8b4462adee7bb7 + sha256: c909bcf7b192256e8dc710efb11df369fdf069aa4f0615f49371d00eb0d7679f url: "https://pub.dev" source: hosted - version: "8.13.0" + version: "8.13.1" characters: dependency: transitive description: @@ -1314,10 +1314,10 @@ packages: dependency: transitive description: name: screen_brightness_android - sha256: "2008ad8e9527cc968f7a4de1ec58b476d495b3c612a149dbd6550c4f046da147" + sha256: "84438a78e3c794159b2ec350a1a7dec51c2115fc55884350f323f3caf40ed2f4" url: "https://pub.dev" source: hosted - version: "2.1.6" + version: "2.1.7" screen_brightness_platform_interface: dependency: transitive description: