diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 8e2cb565..f486f736 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -23,7 +23,7 @@ body: attributes: label: Atrium version description: Settings, then About. - placeholder: "1.11.0" + placeholder: "1.12.0" validations: required: true diff --git a/README.md b/README.md index af8cdb05..c5175364 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ the home Wi-Fi or out in the world. **[Website][site]** - screenshots and a tour, no install needed. -> **Status:** v1.11.0. Install from [F-Droid][fdroid], or grab a signed APK +> **Status:** v1.12.0. Install from [F-Droid][fdroid], or grab a signed APK > from the [releases page][releases]. ## Why @@ -63,7 +63,7 @@ each one covers: | Sonarr | 7 tabs incl. full Settings editor, sort/filter with the server's custom filters, calendar | | Radarr | same depth as Sonarr, movie flavored, with collection monitoring | | Lidarr | artists, albums and tracks, wanted, activity, settings, log reader | -| Prowlarr | indexers, search + grab, history, settings, system | +| Prowlarr | indexers, search by type with indexer and category filters + grab, history, settings, system | | Bazarr | series/movies, wanted, manual subtitle search, system | | Seerr | discover, search, requests management filtered by status, sign in as a Seerr, Jellyfin or Emby user | | Ombi | requests with approve/deny/delete, search, discover | @@ -73,7 +73,7 @@ each one covers: | Emby | same depth as Jellyfin | | Plex | libraries, detail, seasons, music, genres, now-playing controller, plex.tv sign-in | | Navidrome | artists, albums and tracks, playlists, ratings and favorites, search | -| qBittorrent | realtime list, add/manage, torrent detail, tracker editing, private/public badges, queue reorder, full settings, execution log, external IP | +| qBittorrent | realtime list, add/manage, torrent detail, category and tracker editing, session totals, private/public badges, queue reorder, full settings, execution log, external IP | | Deluge | torrent list with a filter drawer, add/manage, queue moves, speed limits, torrent detail (beta) | | Transmission | the web UI's filters in a drawer, actions and inspector, full settings, turtle mode | | rTorrent | torrent list, add/manage, priorities, speed limits, torrent detail (beta) | diff --git a/SECURITY.md b/SECURITY.md index 492d3dac..8839d51c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,15 +2,17 @@ ## Supported versions -Atrium is pre-1.0. Only the latest commit on `main` is supported. +Only the latest release is supported. Please check that an issue still +happens on it before reporting. ## Reporting a vulnerability Please report security issues privately - do **not** open a public issue. -- Email: see the maintainer's GitHub profile. -- Or use GitHub's "Report a vulnerability" private disclosure flow on the - repository. +Use GitHub's private reporting form: +[Report a vulnerability](https://github.com/retransmit/Atrium/security/advisories/new) +(also under the repository's **Security** tab). Only the maintainers can +see what you send there. Please include: diff --git a/STATUS.md b/STATUS.md index 2615b9b1..3575200b 100644 --- a/STATUS.md +++ b/STATUS.md @@ -1,6 +1,6 @@ # Atrium - Status -> Snapshot of what genuinely works and what is left, as of 2026-11-18. +> Snapshot of what genuinely works and what is left, as of 2026-11-24. > Atrium is published on F-Droid and on the GitHub releases page. It is > still in early development and every module is work in progress; nothing > here is a release promise. @@ -32,7 +32,9 @@ Atrium is a **controller** app. Video playback was removed by design airings/releases with status dots (downloaded in the theme's tertiary colour since PR #213, upcoming in primary, missing in error), or a list; the view picked is kept - across launches (Bhavyashah94, PR #205, #203) + across launches (Bhavyashah94, PR #205, #203). The list opens at today, + or at the next day with releases (the latest one when the whole month is + past), and builds only the rows near the screen (PR #254, #203) - **Dashboard widgets**, reorderable from Customize dashboard: Active downloads, Now streaming, Upcoming releases, Recently added, Recently downloaded, Requests (Seerr and Ombi), Glances, Dashdot, Speedtest @@ -61,7 +63,10 @@ Atrium is a **controller** app. Video playback was removed by design instance that allows a self-signed certificate has it accepted for its artwork too, not only its API (per host, 2026-10-19, #189); the instance form needs one valid URL and rejects a malformed one in either - field (PR #213) + field (PR #213); artwork from Radarr, Sonarr, Lidarr, Plex, Jellyfin and + Emby carries the instance's key or session token as a header, never in + the URL, and only to the instance the image belongs to (PR #262, reported + privately through #258) - **qBittorrent**: cookie login (qBit 5.x 204 fix), realtime polling of only what changed (per-instance interval, default 5s), add magnet/file (with skip hash check), categories, tag and tracker @@ -80,7 +85,13 @@ Atrium is a **controller** app. Video playback was removed by design server says which: in the list from qBittorrent 5.0, on a torrent's own screen from 4.5.1, and nowhere while a magnet has no metadata. Settings > System shows the external IPv4 and IPv6 address qBittorrent reports, from - 5.0 (PR #210, #204) + 5.0 (PR #210, #204). Session totals (what a torrent moved since + qBittorrent started) sit beside the all-time ones on its screen, and on + the cards while sorted by session upload or download (PR #256, #250); the + card's bottom row wraps rather than overflowing on narrow phones and large + text (PR #257). A torrent's category is changed from its Overview tab, + in the same picker as the list's hold menu and multi-select, which ticks + the current one (PR #263, #259) - **Sonarr** (the canonical *arr module): poster/banner grid with client-side sort & filter (status, network, airing, added, size on disk) and per-series disk sizes, the custom filters saved on the @@ -105,7 +116,9 @@ Atrium is a **controller** app. Video playback was removed by design (missing and cutoff unmet), queue/history/blocklist, the full settings tree (profiles, download clients, indexers, import lists, notifications, metadata, media management, quality definitions), system diagnostics and - an in-app log viewer with level filtering and search. Album releases also + an in-app log viewer with level filtering and search, whose download saves + the file through the API rather than opening the browser on a keyed URL + (PR #262). Album releases also appear in the shared calendar. The add sheet remembers the last choices per instance; until the first add, the root folder's own defaults apply (#234). Artwork loads through `api/v1/mediacover` @@ -113,7 +126,10 @@ Atrium is a **controller** app. Video playback was removed by design behind a sign-in portal that only lets `/api` through (#222) - **Prowlarr**: indexers (add/edit/test from schema), manual search across indexers with grab-to-client, history, full settings menu, - system + system. Search takes a filter sheet: indexers (single ones, or all torrent + or all Usenet), categories with their subcategories (PR #252, #248), and a + search type (TV, Movie, Audio, Book) whose parameters come as chips that + insert `{ImdbId:}`-style tokens (PR #253, #249) - **Bazarr**: series/movies with per-episode subtitle status, manual provider search/download/delete, wanted, history, blacklist, system - **Seerr** (Jellyseerr / Overseerr): discover (trending/upcoming/genres), @@ -345,7 +361,11 @@ Atrium is a **controller** app. Video playback was removed by design asked to load an http(s) `.torrent` by URL, over both http and https, so the app downloads the file itself and sends the bytes, which does work. That fetch deliberately uses a bare Dio rather than the instance one, so an - instance's credentials are never sent to whatever host a pasted link names + instance's credentials are never sent to whatever host a pasted link names. + Test connection looks beneath the given address for ruTorrent's httprpc + plugin and `RPC2`, and offers "Use this address" when rTorrent answers + there; httprpc requests go to the address itself, without the trailing + slash nginx answers with a 404 (PR #246, #247) - **aria2** (beta; contributed by Bhavyashah94 in PR #202, #167; added 2026-10-21, modernized 2026-10-22, live-verified against 1.37.0): the client that speaks its own protocol rather than a REST API - JSON-RPC over diff --git a/app/lib/src/connection_test/connection_test_result.dart b/app/lib/src/connection_test/connection_test_result.dart index 8ee94160..4223c50f 100644 --- a/app/lib/src/connection_test/connection_test_result.dart +++ b/app/lib/src/connection_test/connection_test_result.dart @@ -7,10 +7,14 @@ enum ConnectionOutcome { connected, authFailed, unreachable } /// One URL test result: an [outcome] and a short human message. class ConnectionTestResult { - const ConnectionTestResult(this.outcome, this.message); + const ConnectionTestResult(this.outcome, this.message, {this.suggestedUrl}); final ConnectionOutcome outcome; final String message; + + /// An address the service did answer at, when the one tested was close but + /// not it. The form offers to switch to it. + final String? suggestedUrl; } /// Maps a [Health] verdict from a lightweight probe to a [ConnectionTestResult]. diff --git a/app/lib/src/connection_test/connection_tester.dart b/app/lib/src/connection_test/connection_tester.dart index bcdfd16c..c0ff04ff 100644 --- a/app/lib/src/connection_test/connection_tester.dart +++ b/app/lib/src/connection_test/connection_tester.dart @@ -8,6 +8,7 @@ import 'package:service_emby/service_emby.dart'; import 'package:service_jellyfin/service_jellyfin.dart'; import 'package:service_plex/service_plex.dart'; import 'package:service_qbittorrent/service_qbittorrent.dart'; +import 'package:service_rtorrent/service_rtorrent.dart'; import 'package:service_seerr/service_seerr.dart'; import 'connection_test_result.dart'; @@ -114,6 +115,8 @@ class ConnectionTester { return _testSlskd(forced); case ServiceKind.seerr: return _testSeerr(forced); + case ServiceKind.rtorrent: + return _testRtorrent(forced); default: final HealthProbe probe = HealthProbe(dioFactory: _ref.read(dioFactoryProvider)); @@ -245,6 +248,72 @@ class ConnectionTester { } } + /// Verifies an rTorrent candidate, and looks for its XML-RPC nearby when + /// the address answers with something else. + /// + /// People mostly have the ruTorrent page to hand, and on a seedbox rTorrent + /// is only reachable through ruTorrent's httprpc plugin beneath it. That + /// page answers fine, so without looking further the test could only say + /// the check did not pass. + Future _testRtorrent(Instance forced) async { + switch (await _rtorrentAnswer(forced)) { + case RtorrentEndpointAnswer.xmlRpc: + return const ConnectionTestResult( + ConnectionOutcome.connected, + 'Connected', + ); + case RtorrentEndpointAnswer.refused: + return const ConnectionTestResult( + ConnectionOutcome.authFailed, + 'Reachable, but the credentials were rejected', + ); + case RtorrentEndpointAnswer.unreachable: + return const ConnectionTestResult( + ConnectionOutcome.unreachable, + 'Could not reach the server', + ); + case RtorrentEndpointAnswer.notXmlRpc: + break; + } + final bool external = forced.urlMode == UrlMode.forceExternal; + final String url = external ? forced.externalUrl : forced.localUrl; + for (final String path in rtorrentEndpointGuesses) { + final String? guess = rtorrentGuessUrl(url, path); + if (guess == null) { + break; + } + final Instance there = external + ? forced.copyWith(externalUrl: guess) + : forced.copyWith(localUrl: guess); + if (await _rtorrentAnswer(there) == RtorrentEndpointAnswer.xmlRpc) { + return ConnectionTestResult( + ConnectionOutcome.authFailed, + 'Reachable, but rTorrent is not at this address. It answers at ' + '$guess', + suggestedUrl: guess, + ); + } + } + return const ConnectionTestResult( + ConnectionOutcome.authFailed, + 'Reachable, but rTorrent did not answer here. Behind ruTorrent, as on ' + 'most seedboxes, the address ends in /plugins/httprpc/action.php. ' + 'Otherwise rTorrent is usually at /RPC2 or on port 8000', + ); + } + + Future _rtorrentAnswer(Instance instance) async { + Dio? dio; + try { + dio = await _ref.read(dioFactoryProvider).create(instance); + return await checkRtorrentEndpoint(dio); + } on Object { + return RtorrentEndpointAnswer.unreachable; + } finally { + dio?.close(force: true); + } + } + Future _testSeerr(Instance forced) async { Dio? dio; try { diff --git a/app/lib/src/screens/calendar_screen.dart b/app/lib/src/screens/calendar_screen.dart index caf4c314..983ab382 100644 --- a/app/lib/src/screens/calendar_screen.dart +++ b/app/lib/src/screens/calendar_screen.dart @@ -1,3 +1,4 @@ +import 'package:clock/clock.dart'; import 'package:collection/collection.dart'; import 'package:core_models/core_models.dart'; import 'package:core_router/core_router.dart'; @@ -72,7 +73,7 @@ class RadarrCalendarEvent extends CalendarEvent { if (general != null && general.isAfter(start) && general.isBefore(end)) { return general; } - return cinemas ?? digital ?? physical ?? general ?? DateTime.now(); + return cinemas ?? digital ?? physical ?? general ?? clock.now(); } @override @@ -110,9 +111,9 @@ class SonarrCalendarEvent extends CalendarEvent { @override DateTime get date { if (episode.airDateUtc == null || episode.airDateUtc!.isEmpty) { - return DateTime.now(); + return clock.now(); } - return (DateTime.tryParse(episode.airDateUtc!) ?? DateTime.now()).toLocal(); + return (DateTime.tryParse(episode.airDateUtc!) ?? clock.now()).toLocal(); } @override @@ -154,9 +155,9 @@ class LidarrCalendarEvent extends CalendarEvent { @override DateTime get date { if (album.releaseDate == null || album.releaseDate!.isEmpty) { - return DateTime.now(); + return clock.now(); } - return (DateTime.tryParse(album.releaseDate!) ?? DateTime.now()).toLocal(); + return (DateTime.tryParse(album.releaseDate!) ?? clock.now()).toLocal(); } @override @@ -296,10 +297,32 @@ class _CalendarScreenState extends ConsumerState { late DateTime _visibleMonth; late DateTime _selectedDay; + // List view opens at today: the first day from today with releases, or the + // last one when they are all past. That day is the list's centre, so + // offset zero puts it at the top. These track when to jump back there. + static const Key _laterKey = ValueKey('calendar-list-later'); + final ScrollController _listScroll = ScrollController(); + bool _anchorPending = true; + DateTime? _listMonth; + + @override + void dispose() { + _listScroll.dispose(); + super.dispose(); + } + + /// Puts the anchored day at the top, or the top of the list when this + /// month has none. + void _scrollToAnchor() { + if (mounted && _listScroll.hasClients) { + _listScroll.jumpTo(0); + } + } + @override void initState() { super.initState(); - final DateTime now = DateTime.now(); + final DateTime now = clock.now(); _visibleMonth = DateTime(now.year, now.month); _selectedDay = DateTime(now.year, now.month, now.day); } @@ -349,10 +372,11 @@ class _CalendarScreenState extends ConsumerState { } void _goToToday() { - final DateTime now = DateTime.now(); + final DateTime now = clock.now(); setState(() { _visibleMonth = DateTime(now.year, now.month); _selectedDay = DateTime(now.year, now.month, now.day); + _anchorPending = true; }); } @@ -584,9 +608,14 @@ class _CalendarScreenState extends ConsumerState { ), tooltip: showListView ? 'Switch to grid view' : 'Switch to list view', - onPressed: () => ref - .read(preferencesProvider.notifier) - .setCalendarListView(!showListView), + onPressed: () { + if (!showListView) { + _anchorPending = true; + } + ref + .read(preferencesProvider.notifier) + .setCalendarListView(!showListView); + }, ), const SizedBox(width: 8), ], @@ -604,13 +633,50 @@ class _CalendarScreenState extends ConsumerState { } final ThemeData theme = Theme.of(context); - final DateTime now = DateTime.now(); + final DateTime now = clock.now(); final Widget content; if (showListView) { final List eventDates = entriesMap.keys.toList() ..sort((a, b) => a.compareTo(b)); + final DateTime today = DateTime(now.year, now.month, now.day); + final bool thisMonth = _visibleMonth.year == now.year && + _visibleMonth.month == now.month; + final DateTime? anchor = thisMonth && eventDates.isNotEmpty + ? eventDates.firstWhere( + (DateTime d) => !d.isBefore(today), + orElse: () => eventDates.last, + ) + : null; + // Rows from the anchor day on, and the rows before it. + final List later = []; + final List earlier = []; + for (final DateTime date in eventDates) { + final List rows = + anchor != null && date.isBefore(anchor) ? earlier : later; + rows.add( + Padding( + padding: const EdgeInsets.only( + top: Insets.md, + bottom: Insets.xs, + ), + child: _DateHeader(date: date), + ), + ); + for (final CalendarEvent event in entriesMap[date]! + ..sort((a, b) => a.date.compareTo(b.date))) { + rows.add(_EventTile(event: event)); + } + } + + if (_anchorPending || _listMonth != _visibleMonth) { + _anchorPending = false; + _listMonth = _visibleMonth; + WidgetsBinding.instance + .addPostFrameCallback((_) => _scrollToAnchor()); + } + content = GestureDetector( onHorizontalDragEnd: (DragEndDetails details) { if (details.primaryVelocity == null) return; @@ -621,129 +687,155 @@ class _CalendarScreenState extends ConsumerState { } }, behavior: HitTestBehavior.translucent, - child: ListView( - physics: const AlwaysScrollableScrollPhysics(), - padding: Insets.page, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Row( - children: [ - Expanded( - child: InkWell( - onTap: () => _showMonthYearPicker(context), - borderRadius: BorderRadius.circular(8), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: Insets.xs, - vertical: 4, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - DateFormat('yyyy').format(_visibleMonth), - style: theme.textTheme.labelSmall?.copyWith( - color: theme.colorScheme.outline, - fontWeight: FontWeight.bold, - letterSpacing: 1.2, + // The month and its controls stay put while the days + // scroll, since the list opens part way down. + Padding( + padding: const EdgeInsets.fromLTRB( + Insets.lg, + Insets.lg, + Insets.lg, + Insets.xs, + ), + child: Row( + children: [ + Expanded( + child: InkWell( + onTap: () => _showMonthYearPicker(context), + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: Insets.xs, + vertical: 4, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + DateFormat('yyyy').format(_visibleMonth), + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.outline, + fontWeight: FontWeight.bold, + letterSpacing: 1.2, + ), ), - ), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - Flexible( - child: Text( - DateFormat('MMMM') - .format(_visibleMonth), - style: theme.textTheme.titleLarge - ?.copyWith( - fontWeight: FontWeight.bold, + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + DateFormat('MMMM') + .format(_visibleMonth), + style: theme.textTheme.titleLarge + ?.copyWith( + fontWeight: FontWeight.bold, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, ), - maxLines: 1, - overflow: TextOverflow.ellipsis, ), - ), - const SizedBox(width: 2), - Icon( - Icons.arrow_drop_down, - size: 20, - color: - theme.colorScheme.onSurfaceVariant, - ), - ], - ), - ], + const SizedBox(width: 2), + Icon( + Icons.arrow_drop_down, + size: 20, + color: + theme.colorScheme.onSurfaceVariant, + ), + ], + ), + ], + ), ), ), ), - ), - const SizedBox(width: Insets.xs), - TextButton.icon( - onPressed: _goToToday, - style: TextButton.styleFrom( + const SizedBox(width: Insets.xs), + TextButton.icon( + onPressed: _goToToday, + style: TextButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric( + horizontal: Insets.sm), + ), + icon: const Icon(Icons.today, size: 16), + label: const Text('Today'), + ), + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _prevMonth, visualDensity: VisualDensity.compact, - padding: const EdgeInsets.symmetric( - horizontal: Insets.sm), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), ), - icon: const Icon(Icons.today, size: 16), - label: const Text('Today'), - ), - IconButton( - icon: const Icon(Icons.chevron_left), - onPressed: _prevMonth, - visualDensity: VisualDensity.compact, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(), - ), - const SizedBox(width: Insets.xs), - IconButton( - icon: const Icon(Icons.chevron_right), - onPressed: _nextMonth, - visualDensity: VisualDensity.compact, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(), - ), - ], + const SizedBox(width: Insets.xs), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _nextMonth, + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], + ), ), - const SizedBox(height: Insets.md), - if (eventDates.isEmpty) - Center( - child: Padding( - padding: - const EdgeInsets.symmetric(vertical: Insets.xxl), - child: Column( - children: [ - Icon( - Icons.calendar_today_outlined, - size: 48, - color: theme.colorScheme.outline - .withValues(alpha: 0.5), - ), - const SizedBox(height: Insets.md), - Text( - 'No releases scheduled this month', - style: theme.textTheme.titleMedium?.copyWith( - color: theme.colorScheme.outline, - ), - ), - ], + Expanded( + // The anchor day is the centre: days before it grow + // upwards above it. Both lists build lazily, since + // every row loads a poster. + child: CustomScrollView( + controller: _listScroll, + physics: const AlwaysScrollableScrollPhysics(), + center: _laterKey, + slivers: [ + SliverPadding( + padding: const EdgeInsets.symmetric( + horizontal: Insets.lg, + ), + sliver: SliverList.list( + children: earlier.reversed.toList(), + ), ), - ), - ) - else - for (final DateTime date in eventDates) ...[ - Padding( - padding: const EdgeInsets.only( - top: Insets.md, - bottom: Insets.xs, + SliverPadding( + key: _laterKey, + padding: const EdgeInsets.fromLTRB( + Insets.lg, + 0, + Insets.lg, + Insets.lg, + ), + sliver: eventDates.isEmpty + ? SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: Insets.xxl, + ), + child: Column( + children: [ + Icon( + Icons.calendar_today_outlined, + size: 48, + color: theme.colorScheme.outline + .withValues(alpha: 0.5), + ), + const SizedBox(height: Insets.md), + Text( + 'No releases scheduled this month', + style: theme.textTheme.titleMedium + ?.copyWith( + color: theme.colorScheme.outline, + ), + ), + ], + ), + ), + ) + : SliverList.list(children: later), ), - child: _DateHeader(date: date), - ), - for (final CalendarEvent event - in entriesMap[date]! - ..sort((a, b) => a.date.compareTo(b.date))) - _EventTile(event: event), - ], + ], + ), + ), ], ), ); @@ -1068,7 +1160,7 @@ class _DateHeader extends StatelessWidget { } String _formatDate(DateTime date) { - final DateTime now = DateTime.now(); + final DateTime now = clock.now(); final DateTime today = DateTime(now.year, now.month, now.day); final DateTime tomorrow = today.add(const Duration(days: 1)); final DateTime yesterday = today.subtract(const Duration(days: 1)); @@ -1176,7 +1268,7 @@ class _EventTile extends ConsumerWidget { posterWidget = _Poster(imageUrl: imageUrl, icon: Icons.album_outlined); } - final bool isFuture = event.date.isAfter(DateTime.now()); + final bool isFuture = event.date.isAfter(clock.now()); final (String label, Color bg, Color fg, Color accentColor) = event.hasFile ? ( 'Downloaded', diff --git a/app/lib/src/screens/changelog/release_notes.dart b/app/lib/src/screens/changelog/release_notes.dart index 54939cc3..29cb72c6 100644 --- a/app/lib/src/screens/changelog/release_notes.dart +++ b/app/lib/src/screens/changelog/release_notes.dart @@ -26,6 +26,28 @@ class ReleaseNote { /// Newest first. Update alongside appVersion and the pubspec at each release. const List releaseNotes = [ + ReleaseNote( + version: '1.12.0', + date: '2026-11-24', + groups: [ + ChangeGroup(ChangeCategory.added, [ + 'Prowlarr search can be narrowed to the indexers and categories you pick, or to all torrent or all Usenet indexers, from one filter button next to the search bar.', + "Prowlarr can search by type: TV, Movie, Audio or Book. Each type shows chips for the parameters it takes, such as ImdbId or Season, which put the {ImdbId:} token in for you.", + "qBittorrent shows what each torrent has uploaded and downloaded since qBittorrent started: beside the all-time totals on the torrent's screen, and on the cards while the list is sorted by session upload or download.", + "A torrent's category can be changed from its own screen: tap Category on the Overview tab. The current category is ticked.", + ]), + ChangeGroup(ChangeCategory.improved, [ + "The calendar's list view opens at today, or at the next day with releases, instead of the start of the month.", + "rTorrent's Test connection looks for rTorrent beneath the address you gave, such as ruTorrent's httprpc plugin, and offers the address it found. When it finds nothing it says where rTorrent usually is.", + ]), + ChangeGroup(ChangeCategory.fixed, [ + 'API keys and tokens are no longer part of the address of poster and artwork requests to Radarr, Sonarr, Lidarr, Plex, Jellyfin and Emby. They travel in a header, like every other request, so a reverse proxy no longer writes them to its access log.', + "Lidarr's log file download saves the file through the app instead of opening the browser on an address carrying the API key.", + "rTorrent through ruTorrent's httprpc plugin works behind nginx.", + 'qBittorrent cards keep their speeds, ratio and ETA inside the card on narrow phones and with large text.', + ]), + ], + ), ReleaseNote( version: '1.11.0', date: '2026-11-18', diff --git a/app/lib/src/screens/instance_form_screen.dart b/app/lib/src/screens/instance_form_screen.dart index 846bb8e6..456e0ca4 100644 --- a/app/lib/src/screens/instance_form_screen.dart +++ b/app/lib/src/screens/instance_form_screen.dart @@ -357,14 +357,29 @@ class _InstanceFormScreenState extends ConsumerState { } } finally { if (mounted) { + // Results belong to the form as it was tested. Anything edited since + // has already cleared them, and putting them back would offer an old + // address over the one now typed. + final bool unchanged = _buildInstance( + widget.instanceId ?? 'connection-test', + ) == + candidate; setState(() { _testingConnection = false; - _connectionResults = results; + _connectionResults = + unchanged ? results : {}; }); } } } + /// Puts the address the test found into the field it was testing, and tests + /// again so the result shows it working. + void _useSuggestedUrl(String which, String url) { + (which == 'External' ? _externalUrl : _localUrl).text = url; + _testConnection(); + } + Future _delete() async { final bool? confirmed = await showDialog( context: context, @@ -721,9 +736,25 @@ class _InstanceFormScreenState extends ConsumerState { ), const SizedBox(width: Insets.sm), Expanded( - child: Text( - '${entry.key}: ${entry.value.message}', - style: theme.textTheme.bodyMedium, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${entry.key}: ${entry.value.message}', + style: theme.textTheme.bodyMedium, + ), + if (entry.value.suggestedUrl + case final String suggested) + TextButton( + onPressed: _testingConnection + ? null + : () => _useSuggestedUrl( + entry.key, + suggested, + ), + child: const Text('Use this address'), + ), + ], ), ), ], diff --git a/app/lib/src/update_check/app_version.dart b/app/lib/src/update_check/app_version.dart index e7111942..6c3c5eb3 100644 --- a/app/lib/src/update_check/app_version.dart +++ b/app/lib/src/update_check/app_version.dart @@ -2,4 +2,4 @@ /// /// Source of truth for the update check and the Settings version line. Bump /// this at release time together with pubspec. -const String appVersion = '1.11.0'; +const String appVersion = '1.12.0'; diff --git a/app/pubspec.yaml b/app/pubspec.yaml index dc8e3060..1dbd41b5 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -2,13 +2,14 @@ name: atrium description: Atrium - mobile controller for a self-hosted media stack. publish_to: none resolution: workspace -version: 1.11.0+30 +version: 1.12.0+31 environment: sdk: ^3.6.0 flutter: ^3.27.0 dependencies: + clock: ^1.1.2 collection: ^1.18.0 connectivity_plus: ^7.2.0 core_models: diff --git a/app/test/calendar_list_today_test.dart b/app/test/calendar_list_today_test.dart new file mode 100644 index 00000000..b86e587b --- /dev/null +++ b/app/test/calendar_list_today_test.dart @@ -0,0 +1,189 @@ +import 'package:atrium/src/preferences.dart'; +import 'package:atrium/src/screens/calendar_screen.dart'; +import 'package:clock/clock.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_profile/core_profile.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_radarr/service_radarr.dart'; + +class _Prefs extends PreferencesController { + _Prefs(this._initial); + final Preferences _initial; + + @override + Preferences build() => _initial; + + @override + Future setCalendarListView(bool listView) async { + state = state.copyWith(calendarListView: listView); + } +} + +const Instance _radarr = Instance( + id: 'test-radarr', + name: 'Test Radarr', + kind: ServiceKind.radarr, + localUrl: 'http://localhost:7878', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'k'), +); + +/// [perDay] movies in cinemas on each of [days] of [month]. The first of a +/// day is titled `M-`, any others `M--`. +List _movies( + DateTime month, + Iterable days, { + int perDay = 1, +}) => + [ + for (final int day in days) + for (int n = 0; n < perDay; n++) + RadarrMovie( + id: month.month * 10000 + day * 100 + n, + title: n == 0 ? 'M${month.month}-$day' : 'M${month.month}-$day-$n', + year: month.year, + inCinemas: DateTime(month.year, month.month, day, 12) + .toIso8601String(), + monitored: true, + hasFile: false, + ), + ]; + +Iterable _range(int from, int to) => + [for (int d = from; d <= to; d++) d]; + +Future _pump( + WidgetTester tester, { + required Iterable Function(DateTime month) days, + bool listView = true, + int perDay = 1, +}) async { + tester.view.physicalSize = const Size(800, 1200); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + await tester.pumpWidget( + ProviderScope( + overrides: [ + preferencesProvider.overrideWith( + () => _Prefs(Preferences(calendarListView: listView)), + ), + activeInstancesProvider.overrideWith((Ref ref) => [_radarr]), + radarrApiProvider(_radarr).overrideWith( + (Ref ref) async => RadarrApi(Dio(), apiKey: 'k'), + ), + radarrCalendarProvider.overrideWith( + (Ref ref, (Instance, DateTime, bool) key) async => + _movies(key.$2, days(key.$2), perDay: perDay), + ), + ], + child: MaterialApp( + theme: AtriumTheme.light(null), + home: const CalendarScreen(), + ), + ), + ); + await _settle(tester); +} + +Future _settle(WidgetTester tester) async { + for (int i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +/// Whether [title] is on screen, in the top third of it. +bool _nearTop(WidgetTester tester, String title) { + final Finder f = find.text(title).hitTestable(); + return f.evaluate().isNotEmpty && tester.getTopLeft(f).dy < 400; +} + +bool _visible(String title) => + find.text(title).hitTestable().evaluate().isNotEmpty; + +void main() { + final Clock nov21 = Clock.fixed(DateTime(2026, 11, 21, 9)); + + testWidgets('the list opens at today', (WidgetTester tester) async { + await withClock(nov21, () async { + await _pump(tester, days: (_) => _range(1, 30)); + expect(_nearTop(tester, 'M11-21'), isTrue); + expect(_visible('M11-1'), isFalse); + }); + }); + + testWidgets('with nothing today it opens at the next day with releases', + (WidgetTester tester) async { + await withClock(nov21, () async { + await _pump( + tester, + days: (_) => _range(1, 30).where((int d) => d != 21), + ); + expect(_nearTop(tester, 'M11-22'), isTrue); + expect(_visible('M11-1'), isFalse); + }); + }); + + testWidgets('with everything past it opens at the latest release', + (WidgetTester tester) async { + await withClock(Clock.fixed(DateTime(2026, 11, 28, 9)), () async { + await _pump(tester, days: (_) => _range(1, 25)); + expect(_visible('M11-25'), isTrue); + expect(_visible('M11-1'), isFalse); + }); + }); + + testWidgets('Today scrolls back to today', (WidgetTester tester) async { + await withClock(nov21, () async { + await _pump(tester, days: (_) => _range(1, 30)); + await tester.fling( + find.byType(CustomScrollView), + const Offset(0, 4000), + 3000, + ); + await _settle(tester); + expect(_visible('M11-1'), isTrue); + await tester.tap(find.widgetWithText(TextButton, 'Today')); + await _settle(tester); + expect(_nearTop(tester, 'M11-21'), isTrue); + }); + }); + + testWidgets('another month opens at its start', (WidgetTester tester) async { + await withClock(nov21, () async { + await _pump(tester, days: (_) => _range(1, 30)); + await tester.tap(find.byIcon(Icons.chevron_right)); + await _settle(tester); + expect(_nearTop(tester, 'M12-1'), isTrue); + }); + }); + + testWidgets('switching from grid to list opens at today', + (WidgetTester tester) async { + await withClock(nov21, () async { + await _pump(tester, days: (_) => _range(1, 30), listView: false); + await tester.tap(find.byTooltip('Switch to list view')); + await _settle(tester); + expect(_nearTop(tester, 'M11-21'), isTrue); + }); + }); + + testWidgets('rows far from the screen are not built', + (WidgetTester tester) async { + await withClock(nov21, () async { + await _pump(tester, days: (_) => _range(1, 30), perDay: 10); + expect(_nearTop(tester, 'M11-21'), isTrue); + // 300 releases; only those around what is on screen should exist, + // since each row loads a poster. + expect( + find.textContaining('M11-', skipOffstage: false).evaluate().length, + lessThan(60), + ); + }); + }); +} diff --git a/app/test/connection_tester_test.dart b/app/test/connection_tester_test.dart index 0b8b9b0e..6dd43df8 100644 --- a/app/test/connection_tester_test.dart +++ b/app/test/connection_tester_test.dart @@ -388,6 +388,228 @@ void main() { expect(result.outcome, ConnectionOutcome.authFailed); }); }); + + group('rTorrent', () { + Instance rtorrentAt(String local, {String external = ''}) => Instance( + id: 'rtorrent', + name: 'rTorrent', + kind: ServiceKind.rtorrent, + localUrl: local, + externalUrl: external, + urlMode: UrlMode.auto, + auth: const InstanceAuth.userPass(username: 'u', password: 'p'), + ); + + /// Tests [instance] against a server that answers each URL from [routes] + /// and anything else with the ruTorrent web page. + Future<(ConnectionTestResult, _RtorrentServer)> testAgainst( + Instance instance, + Map routes, { + UrlMode url = UrlMode.forceLocal, + }) async { + final _RtorrentServer server = _RtorrentServer(routes); + final ProviderContainer container = ProviderContainer( + overrides: [dioFactoryProvider.overrideWithValue(server)], + ); + addTearDown(container.dispose); + final ConnectionTestResult result = await container + .read(connectionTesterProvider) + .test(candidate: instance, url: url); + return (result, server); + } + + test('XML-RPC at the address tests as connected', () async { + final (ConnectionTestResult result, _) = await testAgainst( + rtorrentAt('http://box.test:8000'), + { + 'http://box.test:8000/': _xmlRpcAnswer, + }, + ); + + expect(result.outcome, ConnectionOutcome.connected); + expect(result.suggestedUrl, isNull); + }); + + test('the ruTorrent page finds the httprpc endpoint beneath it', () async { + // badgone88's seedbox: the web UI answers at the address they typed, + // rTorrent only through ruTorrent's httprpc plugin. + final (ConnectionTestResult result, _) = await testAgainst( + rtorrentAt('https://seedbox.test/user/rutorrent/'), + { + 'https://seedbox.test/user/rutorrent/plugins/httprpc/action.php': + _xmlRpcAnswer, + }, + ); + + expect(result.outcome, ConnectionOutcome.authFailed); + expect( + result.suggestedUrl, + 'https://seedbox.test/user/rutorrent/plugins/httprpc/action.php', + ); + expect(result.message, contains(result.suggestedUrl)); + }); + + test('a server root finds ruTorrent beneath it', () async { + final (ConnectionTestResult result, _) = await testAgainst( + rtorrentAt('https://seedbox.test/user'), + { + 'https://seedbox.test/user/rutorrent/plugins/httprpc/action.php': + _xmlRpcAnswer, + }, + ); + + expect( + result.suggestedUrl, + 'https://seedbox.test/user/rutorrent/plugins/httprpc/action.php', + ); + }); + + test('an RPC2 mount is found too', () async { + final (ConnectionTestResult result, _) = await testAgainst( + rtorrentAt('http://box.test'), + { + 'http://box.test/RPC2': _xmlRpcAnswer, + }, + ); + + expect(result.suggestedUrl, 'http://box.test/RPC2'); + }); + + test('the external address is searched under its own URL', () async { + final (ConnectionTestResult result, _) = await testAgainst( + rtorrentAt('http://box.test:8000', external: 'https://seedbox.test/ru'), + { + 'https://seedbox.test/ru/plugins/httprpc/action.php': _xmlRpcAnswer, + }, + url: UrlMode.forceExternal, + ); + + expect( + result.suggestedUrl, + 'https://seedbox.test/ru/plugins/httprpc/action.php', + ); + }); + + test('with nothing found, the message says where rTorrent usually is', + () async { + final (ConnectionTestResult result, _) = await testAgainst( + rtorrentAt('https://seedbox.test/user/rutorrent'), + {}, + ); + + expect(result.outcome, ConnectionOutcome.authFailed); + expect(result.suggestedUrl, isNull); + expect(result.message, contains('/plugins/httprpc/action.php')); + expect(result.message, contains('/RPC2')); + }); + + test('refused credentials are reported without searching', () async { + final (ConnectionTestResult result, _RtorrentServer server) = + await testAgainst( + rtorrentAt('https://seedbox.test/user/rutorrent'), + { + 'https://seedbox.test/user/rutorrent/': () => + ResponseBody.fromString('Unauthorized', 401), + }, + ); + + expect(result.outcome, ConnectionOutcome.authFailed); + expect(result.message, contains('credentials')); + expect(result.suggestedUrl, isNull); + expect(server.requested, hasLength(1)); + }); + + test('an address already at an endpoint is not searched beneath', + () async { + final (ConnectionTestResult result, _RtorrentServer server) = + await testAgainst( + rtorrentAt('https://seedbox.test/rutorrent/plugins/httprpc/action.php'), + {}, + ); + + expect(result.suggestedUrl, isNull); + expect(server.requested, hasLength(1)); + }); + + test('an unreachable server is not searched', () async { + final (ConnectionTestResult result, _RtorrentServer server) = + await testAgainst( + rtorrentAt('http://down.test:8000'), + { + 'http://down.test:8000/': () => throw DioException.connectionError( + requestOptions: RequestOptions(), + reason: 'refused', + ), + }, + ); + + expect(result.outcome, ConnectionOutcome.unreachable); + expect(server.requested, hasLength(1)); + }); + }); +} + +ResponseBody _xmlRpcAnswer() => ResponseBody.fromString( + '' + '0.9.8', + 200, + headers: >{ + Headers.contentTypeHeader: ['text/xml'], + }, + ); + +/// A seedbox: each URL in [routes] answers as given, anything else with the +/// ruTorrent web page. Records every URL asked for. +class _RtorrentServer implements DioFactory { + _RtorrentServer(this.routes); + + final Map routes; + final List requested = []; + + @override + Future create(Instance instance) async { + final String url = instance.urlMode == UrlMode.forceExternal + ? instance.externalUrl + : instance.localUrl; + return Dio(BaseOptions(baseUrl: url.endsWith('/') ? url : '$url/')) + ..httpClientAdapter = _RtorrentRoutes(this); + } +} + +class _RtorrentRoutes implements HttpClientAdapter { + _RtorrentRoutes(this._server); + + final _RtorrentServer _server; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + final String url = options.uri.toString(); + _server.requested.add(url); + // A trailing slash is the client's business, covered by its own tests. + String bare(String u) => u.replaceFirst(RegExp(r'/$'), ''); + final ResponseBody Function()? route = _server.routes.entries + .where((MapEntry e) => + bare(e.key) == bare(url),) + .map((MapEntry e) => e.value) + .firstOrNull; + if (route != null) { + return route(); + } + return ResponseBody.fromString( + 'ruTorrent', + 200, + headers: >{ + Headers.contentTypeHeader: ['text/html; charset=utf-8'], + }, + ); + } + + @override + void close({bool force = false}) {} } class _SlskdDioFactory implements DioFactory { diff --git a/app/test/instance_form_suggested_url_test.dart b/app/test/instance_form_suggested_url_test.dart new file mode 100644 index 00000000..768b5d02 --- /dev/null +++ b/app/test/instance_form_suggested_url_test.dart @@ -0,0 +1,192 @@ +import 'dart:async'; + +import 'package:atrium/src/connection_test/connection_test_result.dart'; +import 'package:atrium/src/connection_test/connection_tester.dart'; +import 'package:atrium/src/screens/instance_form_screen.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_profile/core_profile.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +/// When Test connection finds the service at a nearby address, such as +/// rTorrent beneath the ruTorrent page, the form offers to switch to it. +void main() { + const String typed = 'https://seedbox.test/user/rutorrent'; + const String found = + 'https://seedbox.test/user/rutorrent/plugins/httprpc/action.php'; + + const Instance rtorrent = Instance( + id: 'rtorrent', + name: 'rTorrent', + kind: ServiceKind.rtorrent, + localUrl: typed, + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.userPass(username: '', password: ''), + ); + + late _Profiles profiles; + late List tested; + + /// When set, every test waits for it before answering. + Completer? gate; + + Future edit(WidgetTester tester) async { + tester.view.physicalSize = const Size(900, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + profiles = _Profiles(rtorrent); + tested = []; + gate = null; + final GoRouter router = GoRouter( + initialLocation: '/edit', + routes: [ + GoRoute( + path: '/', + builder: (BuildContext _, GoRouterState __) => + const Scaffold(body: Text('home')), + routes: [ + GoRoute( + path: 'edit', + builder: (BuildContext _, GoRouterState __) => + InstanceFormScreen(instanceId: rtorrent.id), + ), + ], + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + ProviderScope( + overrides: [ + profileListProvider.overrideWith(() => profiles), + activeProfileIdProvider.overrideWith(_Active.new), + connectionTesterProvider + .overrideWith((Ref ref) => _Tester(ref, tested, found, () => gate)), + ], + child: MaterialApp.router(routerConfig: router), + ), + ); + await tester.pumpAndSettle(); + } + + Future tap(WidgetTester tester, String label) async { + await tester.scrollUntilVisible( + find.text(label), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.tap(find.text(label)); + await tester.pumpAndSettle(); + } + + testWidgets('Use this address fills in the address and tests it again', + (WidgetTester tester) async { + await edit(tester); + + await tap(tester, 'Test connection'); + expect(find.textContaining('It answers at $found'), findsOneWidget); + + await tap(tester, 'Use this address'); + expect(find.widgetWithText(TextFormField, found), findsOneWidget); + expect(tested, [typed, found]); + expect(find.text('Local: Connected'), findsOneWidget); + expect(find.text('Use this address'), findsNothing); + + await tap(tester, 'Save changes'); + expect(profiles.saved.single.localUrl, found); + }); + + testWidgets('a test still running when the address is edited is dropped', + (WidgetTester tester) async { + await edit(tester); + gate = Completer(); + + await tester.scrollUntilVisible( + find.text('Test connection'), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.tap(find.text('Test connection')); + await tester.pump(); + + // Edited while the search is still out, then the search comes back. + const String edited = 'https://other.test/rutorrent'; + await tester.enterText(find.widgetWithText(TextFormField, typed), edited); + gate!.complete(); + await tester.pumpAndSettle(); + + // Its suggestion would put the old search's address over the new one. + expect(find.text('Use this address'), findsNothing); + expect(find.textContaining('Local:'), findsNothing); + expect(find.widgetWithText(TextFormField, edited), findsOneWidget); + }); + + testWidgets('no button without a suggestion', (WidgetTester tester) async { + await edit(tester); + await tester.enterText( + find.widgetWithText(TextFormField, typed), + 'http://other.test:8000', + ); + + await tap(tester, 'Test connection'); + expect(find.text('Local: Connected'), findsOneWidget); + expect(find.text('Use this address'), findsNothing); + }); +} + +/// Finds rTorrent at [found] whenever any other address is tested. +class _Tester extends ConnectionTester { + _Tester(super.ref, this.tested, this.found, this.gate); + + final List tested; + final String found; + final Completer? Function() gate; + + @override + Future test({ + required Instance candidate, + required UrlMode url, + }) async { + tested.add(candidate.localUrl); + await gate()?.future; + if (candidate.localUrl == found || + candidate.localUrl == 'http://other.test:8000') { + return const ConnectionTestResult(ConnectionOutcome.connected, 'Connected'); + } + return ConnectionTestResult( + ConnectionOutcome.authFailed, + 'Reachable, but rTorrent is not at this address. It answers at $found', + suggestedUrl: found, + ); + } +} + +class _Profiles extends ProfileListController { + _Profiles(this.instance); + + final Instance instance; + final List saved = []; + + @override + Future> build() async => [ + Profile(id: 'p', name: 'Default', instances: [instance]), + ]; + + @override + Future upsertInstance(String profileId, Instance instance) async { + saved.add(instance); + } +} + +class _Active extends ActiveProfileIdController { + @override + String? build() => 'p'; + + @override + Future select(String? id) async => state = id; +} diff --git a/app/test/new_services_render_test.dart b/app/test/new_services_render_test.dart index a0c7a1bc..51001ec7 100644 --- a/app/test/new_services_render_test.dart +++ b/app/test/new_services_render_test.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:typed_data'; +import 'package:clock/clock.dart'; import 'package:core_models/core_models.dart'; import 'package:core_networking/core_networking.dart'; import 'package:core_profile/core_profile.dart'; @@ -325,7 +326,9 @@ void main() { addTearDown(tester.view.resetDevicePixelRatio); final Instance radarr = _instance(ServiceKind.radarr); - final DateTime airDate = DateTime.now(); + // The screen reads the test's clock, which stands still; the real time + // would already be after it and count as upcoming. + final DateTime airDate = clock.now(); await _pump( tester, diff --git a/docs/REVERSE_PROXY.md b/docs/REVERSE_PROXY.md index 1a6e6e8d..343018e5 100644 --- a/docs/REVERSE_PROXY.md +++ b/docs/REVERSE_PROXY.md @@ -154,6 +154,14 @@ Two consequences worth knowing: TMDB and Fanart.tv, and your proxy credentials have no business leaving your network. +Since 1.12.0 the instance's own key travels the same way: `X-Api-Key` for +Radarr, Sonarr and Lidarr, `X-Plex-Token` for Plex, and the signed-in session +token for Jellyfin and Emby. Artwork URLs no longer carry `?apikey=`, +`api_key=` or `X-Plex-Token=`, so a proxy that logs the full request line, as +Traefik, nginx and Caddy do by default, no longer writes the key to its access +log. Older versions put it there; if your proxy logs go anywhere others can +read, rotate the keys once you have updated. + ## What the dashboard dot means - **Online**: the service answered its own status endpoint and the diff --git a/fastlane/metadata/android/en-US/changelogs/31.txt b/fastlane/metadata/android/en-US/changelogs/31.txt new file mode 100644 index 00000000..eb47f2eb --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/31.txt @@ -0,0 +1,11 @@ +Prowlarr search: pick indexers and categories, and search by TV, Movie, +Audio or Book with parameter chips. + +qBittorrent: session upload and download totals, and change a torrent's +category from its own screen. + +The calendar list opens at today. + +rTorrent finds its address behind ruTorrent and works behind nginx. + +Artwork requests no longer carry API keys or tokens in their address. diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt index 264aa850..edb820ca 100644 --- a/fastlane/metadata/android/en-US/full_description.txt +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -9,7 +9,8 @@ Supported services: * Sonarr, Radarr and Lidarr - library, queue, wanted, history, blocklist, system status and the full settings tree -* Prowlarr - indexers, search and grab +* Prowlarr - indexers, search by type with indexer and category filters, + and grab * Bazarr - subtitle status, search and download * Seerr (Overseerr and Jellyseerr) and Ombi - discover, request and manage requests diff --git a/packages/core_networking/lib/core_networking.dart b/packages/core_networking/lib/core_networking.dart index 5d1858d1..75eed1bb 100644 --- a/packages/core_networking/lib/core_networking.dart +++ b/packages/core_networking/lib/core_networking.dart @@ -15,6 +15,7 @@ export 'src/network_fingerprint.dart'; export 'src/networking_providers.dart'; export 'src/polling.dart'; export 'src/rate_limit_interceptor.dart'; +export 'src/self_path.dart'; export 'src/self_signed_cert_trust.dart'; export 'src/service_auth_headers.dart'; export 'src/service_health.dart'; diff --git a/packages/core_networking/lib/src/self_path.dart b/packages/core_networking/lib/src/self_path.dart new file mode 100644 index 00000000..3e296d3f --- /dev/null +++ b/packages/core_networking/lib/src/self_path.dart @@ -0,0 +1,15 @@ +/// The request path that lands on [baseUrl] itself rather than beneath it. +/// +/// [DioFactory] gives every base URL a trailing slash so relative paths join +/// onto it, so a service whose endpoint is the address itself, such as +/// rTorrent's XML-RPC, would be asked for at `.../action.php/` by an empty +/// path. nginx answers that with a 404, while Apache passes the slash on as +/// path info, which is how it went unnoticed. Below the root this is the +/// address without that slash; at the root it is the root, as before. +String selfPath(String baseUrl) { + final Uri? uri = Uri.tryParse(baseUrl); + if (uri == null || uri.path.length <= 1 || !baseUrl.endsWith('/')) { + return ''; + } + return baseUrl.substring(0, baseUrl.length - 1); +} diff --git a/packages/core_networking/lib/src/service_health.dart b/packages/core_networking/lib/src/service_health.dart index b8034829..f1d7a5db 100644 --- a/packages/core_networking/lib/src/service_health.dart +++ b/packages/core_networking/lib/src/service_health.dart @@ -5,6 +5,7 @@ import 'package:dio/dio.dart'; import 'auth_interceptor.dart'; import 'dio_factory.dart'; +import 'self_path.dart'; /// How a service's health endpoint should be interpreted. enum _HealthMode { @@ -244,7 +245,10 @@ class HealthProbe { body == null ? null : _probeContentType(instance.kind), responseType: body == null ? null : ResponseType.plain, ); - final String path = _probePath(instance, cfg.path); + final String probePath = _probePath(instance, cfg.path); + // An empty path means the address itself; see [selfPath]. + final String path = + probePath.isEmpty ? selfPath(dio.options.baseUrl) : probePath; final Response resp = body == null ? await dio.get(path, options: options) : await dio.post(path, data: body, options: options); diff --git a/packages/core_networking/test/rtorrent_probe_test.dart b/packages/core_networking/test/rtorrent_probe_test.dart new file mode 100644 index 00000000..07b99a0f --- /dev/null +++ b/packages/core_networking/test/rtorrent_probe_test.dart @@ -0,0 +1,95 @@ +import 'dart:typed_data'; + +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_networking/core_networking.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// The real health probe through the real factory, with only the socket +/// replaced. +/// +/// rTorrent's XML-RPC is the address itself, not a route beneath it. The +/// factory gives every base URL a trailing slash, and nginx answers +/// `.../plugins/httprpc/action.php/` with a 404 while `.../action.php` is +/// rTorrent (checked against crazymax/rtorrent-rutorrent). +void main() { + Instance rtorrentAt(String url) => Instance( + id: 'rtorrent', + name: 'rTorrent', + kind: ServiceKind.rtorrent, + localUrl: url, + externalUrl: '', + urlMode: UrlMode.forceLocal, + auth: const InstanceAuth.userPass(username: '', password: ''), + ); + + Future probedUri(String url) async { + final _RecordingFactory factory = _RecordingFactory(); + final Health health = + await HealthProbe(dioFactory: factory).check(rtorrentAt(url)); + expect(health, Health.ok); + return factory.requests.single.uri; + } + + test('an endpoint below the root is asked for without a trailing slash', + () async { + expect( + '${await probedUri('https://box.test/rutorrent/plugins/httprpc/action.php')}', + 'https://box.test/rutorrent/plugins/httprpc/action.php', + ); + expect( + '${await probedUri('https://box.test/RPC2/')}', + 'https://box.test/RPC2', + ); + }); + + test('a bare port is asked for at its root', () async { + expect('${await probedUri('http://box.test:8000')}', 'http://box.test:8000/'); + }); + + test('selfPath leaves the root alone', () { + expect(selfPath('http://box.test:8000/'), ''); + expect( + selfPath('http://box.test/RPC2/'), + 'http://box.test/RPC2', + ); + }); +} + +class _RecordingFactory extends DioFactory { + _RecordingFactory() + : super(resolver: ConnectionResolver(connectivity: Connectivity())); + + final List requests = []; + + @override + Future create(Instance instance) async => + (await super.create(instance))..httpClientAdapter = _Adapter(this); +} + +class _Adapter implements HttpClientAdapter { + _Adapter(this.factory); + + final _RecordingFactory factory; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + factory.requests.add(options); + return ResponseBody.fromString( + '' + '0.16.22', + 200, + headers: >{ + Headers.contentTypeHeader: ['text/xml; charset=UTF-8'], + }, + ); + } + + @override + void close({bool force = false}) {} +} diff --git a/packages/core_ui/lib/src/artwork_headers.dart b/packages/core_ui/lib/src/artwork_headers.dart index ffd2368c..72ba1f88 100644 --- a/packages/core_ui/lib/src/artwork_headers.dart +++ b/packages/core_ui/lib/src/artwork_headers.dart @@ -22,24 +22,37 @@ abstract final class ArtworkHeaders { /// Normalised instance base URL to the headers requests under it need. /// /// Both the local and external URL of an instance map to the same headers, - /// since either may be the one the artwork URL was built from. + /// since either may be the one the artwork URL was built from. Every + /// configured base is a key, with an empty map when it has nothing to + /// send, so a URL is matched to its own instance and never falls through + /// to another one higher up the same host. static Map> _byBase = const >{}; + /// Headers a signed-in client set for its own base: the session token + /// Jellyfin and Emby hand out at login, which no [Instance] holds. + static Map> _sessions = + >{}; + + /// Which instance, and which account on it, each base belonged to when the + /// lookup was last built. A session token is only good for that account. + static Map _owners = const {}; + /// Rebuilds the lookup for [instances], merging each instance's headers - /// over [global] exactly as the Dio factory does. + /// over [global] exactly as the Dio factory does, then its own credential + /// on top, as the auth interceptor does after the custom headers. static void update({ required Iterable instances, required Map global, }) { final Map> next = >{}; + final Map owners = {}; for (final Instance instance in instances) { - final Map headers = - mergeHeaders(global, instance.customHeaders); - if (headers.isEmpty) { - continue; - } + final Map headers = { + ...mergeHeaders(global, instance.customHeaders), + ..._credential(instance), + }; for (final String base in [ instance.localUrl, instance.externalUrl, @@ -47,10 +60,30 @@ abstract final class ArtworkHeaders { final String key = _normalise(base); if (key.isNotEmpty) { next[key] = headers; + owners[key] = (instance.id, instance.auth); } } } + // A token belongs to the account that signed in. When a base is removed, + // or now belongs to another instance or account (a profile switch, a + // changed user), its token goes; that client registers a new one when it + // signs in. + _sessions.removeWhere( + (String base, _) => owners[base] == null || owners[base] != _owners[base], + ); _byBase = next; + _owners = owners; + } + + /// Records the headers a signed-in client needs on artwork under + /// [baseUrl], or clears them when [headers] is null. + static void setSession(String baseUrl, Map? headers) { + final String key = _normalise(baseUrl); + if (headers == null || headers.isEmpty) { + _sessions.remove(key); + } else { + _sessions[key] = Map.unmodifiable(headers); + } } /// Headers for [url], or null when it belongs to no configured instance. @@ -58,7 +91,7 @@ abstract final class ArtworkHeaders { /// Null rather than an empty map because that is what `CachedNetworkImage` /// and `Image.network` already treat as "send nothing", and because artwork /// for something not in the library yet points at TMDB or Fanart.tv, where - /// the user's proxy credentials have no business being sent. + /// the user's proxy credentials and API keys have no business being sent. static Map? forUrl(String? url) { if (url == null || url.isEmpty || _byBase.isEmpty) { return null; @@ -75,11 +108,42 @@ abstract final class ArtworkHeaders { } } } - return best == null ? null : _byBase[best]; + if (best == null) { + return null; + } + final Map headers = { + ..._byBase[best]!, + ...?_sessions[best], + }; + return headers.isEmpty ? null : headers; } + /// The instance's own credential, as a header, for the kinds whose + /// artwork Atrium builds URLs for. + /// + /// These used to ride in the URL (`?apikey=`, `?X-Plex-Token=`), which a + /// reverse proxy writes to its access log in full. Each of these services + /// takes the same header on its artwork that it takes on its API. + static Map _credential(Instance instance) => + switch ((instance.kind, instance.auth)) { + ( + ServiceKind.radarr || ServiceKind.sonarr || ServiceKind.lidarr, + InstanceAuthApiKey(:final String apiKey), + ) + when apiKey.isNotEmpty => + {'X-Api-Key': apiKey}, + (ServiceKind.plex, InstanceAuthPlex(:final String token)) + when token.isNotEmpty => + {'X-Plex-Token': token}, + _ => const {}, + }; + /// Drops every mapping. Only for tests, so one does not leak into the next. - static void reset() => _byBase = const >{}; + static void reset() { + _byBase = const >{}; + _sessions = >{}; + _owners = const {}; + } /// Lowercased and stripped of trailing slashes so the comparison survives /// the ways a base URL and the URL built from it can differ in spelling. @@ -88,6 +152,13 @@ abstract final class ArtworkHeaders { /// the user's own server. static String _normalise(String raw) { String value = raw.trim(); + // Through Uri first, the way the connection resolver builds the base the + // artwork URLs start from: it drops a default port such as :443, and a + // base typed with one would otherwise never match. + final Uri? uri = Uri.tryParse(value); + if (uri != null && uri.hasScheme && uri.host.isNotEmpty) { + value = uri.toString(); + } while (value.endsWith('/')) { value = value.substring(0, value.length - 1); } diff --git a/packages/core_ui/test/artwork_auth_headers_test.dart b/packages/core_ui/test/artwork_auth_headers_test.dart new file mode 100644 index 00000000..d2a95c99 --- /dev/null +++ b/packages/core_ui/test/artwork_auth_headers_test.dart @@ -0,0 +1,274 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Artwork carries the instance's credential in a header, never in the URL, +/// because a reverse proxy writes the whole request line to its access log. +/// These pin which kinds get which header, and that it goes nowhere else. +void main() { + tearDown(ArtworkHeaders.reset); + + Instance instance( + ServiceKind kind, + InstanceAuth auth, { + String local = 'http://media.example.test:7878', + String external = '', + Map headers = const {}, + }) => + Instance( + id: kind.name, + name: kind.name, + kind: kind, + localUrl: local, + externalUrl: external, + urlMode: UrlMode.auto, + auth: auth, + customHeaders: headers, + ); + + void use(List instances) => ArtworkHeaders.update( + instances: instances, + global: const {}, + ); + + const String poster = + 'http://media.example.test:7878/api/v3/mediacover/1/poster-500.jpg'; + + for (final ServiceKind kind in [ + ServiceKind.radarr, + ServiceKind.sonarr, + ServiceKind.lidarr, + ]) { + test('${kind.name} artwork carries the api key as X-Api-Key', () { + use([ + instance(kind, const InstanceAuth.apiKey(apiKey: 'secret')), + ]); + expect( + ArtworkHeaders.forUrl(poster), + {'X-Api-Key': 'secret'}, + ); + }); + } + + test('Plex artwork carries the token as X-Plex-Token', () { + use([ + instance( + ServiceKind.plex, + const InstanceAuth.plexToken(token: 'plex-secret'), + local: 'http://plex.example.test:32400', + ), + ]); + expect( + ArtworkHeaders.forUrl( + 'http://plex.example.test:32400/library/metadata/1/thumb/2', + ), + {'X-Plex-Token': 'plex-secret'}, + ); + }); + + test('it reaches the external url too', () { + use([ + instance( + ServiceKind.radarr, + const InstanceAuth.apiKey(apiKey: 'secret'), + external: 'https://radarr.example.org', + ), + ]); + expect( + ArtworkHeaders.forUrl( + 'https://radarr.example.org/api/v3/mediacover/1/poster-500.jpg', + ), + {'X-Api-Key': 'secret'}, + ); + }); + + test('a default port written out still matches', () { + // The connection resolver builds the base with Uri.parse, which drops + // :443 and :80, so the artwork URL does not have the port the user typed. + // Missing that match now costs the poster, not just a proxy header. + use([ + instance( + ServiceKind.radarr, + const InstanceAuth.apiKey(apiKey: 'secret'), + local: 'http://192.168.0.10:80', + external: 'https://radarr.example.org:443/', + ), + ]); + for (final String base in [ + Uri.parse('http://192.168.0.10:80').toString(), + Uri.parse('https://radarr.example.org:443/').toString(), + ]) { + expect( + ArtworkHeaders.forUrl('${base.replaceAll(RegExp(r'/$'), '')}' + '/api/v3/mediacover/1/poster-500.jpg'), + {'X-Api-Key': 'secret'}, + reason: base, + ); + } + }); + + test('a kind whose artwork Atrium does not build sends no key', () { + use([ + instance(ServiceKind.prowlarr, const InstanceAuth.apiKey(apiKey: 'p')), + ]); + expect(ArtworkHeaders.forUrl(poster), isNull); + }); + + test('an empty key sends no header', () { + use([ + instance(ServiceKind.radarr, const InstanceAuth.apiKey(apiKey: '')), + ]); + expect(ArtworkHeaders.forUrl(poster), isNull); + }); + + test('the key never goes to a third party', () { + use([ + instance(ServiceKind.radarr, const InstanceAuth.apiKey(apiKey: 'secret')), + ]); + expect( + ArtworkHeaders.forUrl('https://image.tmdb.org/t/p/w500/abc.jpg'), + isNull, + ); + }); + + test('a key does not spill onto another instance on the same host', () { + // Radarr at the root, Jellyfin on a sub-path with nothing of its own to + // send. Jellyfin's artwork must not pick up Radarr's key on the way. + use([ + instance( + ServiceKind.radarr, + const InstanceAuth.apiKey(apiKey: 'secret'), + local: 'https://home.example.test', + ), + instance( + ServiceKind.jellyfin, + const InstanceAuth.userPass(username: 'u', password: 'p'), + local: 'https://home.example.test/jellyfin', + ), + ]); + expect( + ArtworkHeaders.forUrl( + 'https://home.example.test/jellyfin/Items/1/Images/Primary', + ), + isNull, + ); + expect( + ArtworkHeaders.forUrl( + 'https://home.example.test/api/v3/mediacover/1/poster.jpg', + ), + {'X-Api-Key': 'secret'}, + ); + }); + + test('the service key wins over a custom header of the same name', () { + // The Dio auth interceptor runs after the custom headers and overwrites + // them, so artwork has to agree or it would carry a different key. + use([ + instance( + ServiceKind.radarr, + const InstanceAuth.apiKey(apiKey: 'secret'), + headers: const { + 'X-Api-Key': 'typed-by-hand', + 'Proxy-Authorization': 'Bearer p', + }, + ), + ]); + expect( + ArtworkHeaders.forUrl(poster), + {'X-Api-Key': 'secret', 'Proxy-Authorization': 'Bearer p'}, + ); + }); + + group('session headers', () { + const String jf = 'http://jellyfin.example.test:8096'; + const String image = '$jf/Items/abc/Images/Primary?maxHeight=420'; + + Instance jellyfin({Map headers = const {}}) => + instance( + ServiceKind.jellyfin, + const InstanceAuth.userPass(username: 'u', password: 'p'), + local: jf, + headers: headers, + ); + + test('a signed-in client puts its token on its own artwork', () { + use([jellyfin()]); + ArtworkHeaders.setSession('$jf/', {'X-Emby-Token': 't'}); + expect(ArtworkHeaders.forUrl(image), {'X-Emby-Token': 't'}); + expect( + ArtworkHeaders.forUrl('https://image.tmdb.org/t/p/w500/abc.jpg'), + isNull, + ); + }); + + test('it sits beside the custom headers and wins a clash', () { + use([ + jellyfin( + headers: const { + 'Authorization': 'Basic proxy', + 'CF-Access-Client-Id': 'id', + }, + ), + ]); + ArtworkHeaders.setSession( + jf, + {'Authorization': 'MediaBrowser Token="t"'}, + ); + expect(ArtworkHeaders.forUrl(image), { + 'Authorization': 'MediaBrowser Token="t"', + 'CF-Access-Client-Id': 'id', + }); + }); + + test('a profile refresh keeps it', () { + use([jellyfin()]); + ArtworkHeaders.setSession(jf, {'X-Emby-Token': 't'}); + use([jellyfin()]); + expect(ArtworkHeaders.forUrl(image), {'X-Emby-Token': 't'}); + }); + + test('signing out clears it', () { + use([jellyfin()]); + ArtworkHeaders.setSession(jf, {'X-Emby-Token': 't'}); + ArtworkHeaders.setSession(jf, null); + expect(ArtworkHeaders.forUrl(image), isNull); + }); + + test('another profile on the same server does not inherit the token', () { + // Two profiles, one Jellyfin, different accounts. Until the new + // profile's client signs in, its artwork must not go out under the + // previous account's token. + Instance account(String id, String user) => Instance( + id: id, + name: id, + kind: ServiceKind.jellyfin, + localUrl: jf, + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.userPass(username: user, password: 'p'), + ); + use([account('profile-a-jf', 'alice')]); + ArtworkHeaders.setSession(jf, {'X-Emby-Token': 'alice'}); + use([account('profile-b-jf', 'bob')]); + expect(ArtworkHeaders.forUrl(image), isNull); + }); + + test('a new account on the same instance drops the old token', () { + use([jellyfin()]); + ArtworkHeaders.setSession(jf, {'X-Emby-Token': 't'}); + use([ + jellyfin().copyWith( + auth: const InstanceAuth.userPass(username: 'other', password: 'p'), + ), + ]); + expect(ArtworkHeaders.forUrl(image), isNull); + }); + + test('removing the instance drops its token', () { + use([jellyfin()]); + ArtworkHeaders.setSession(jf, {'X-Emby-Token': 't'}); + use([]); + expect(ArtworkHeaders.forUrl(image), isNull); + }); + }); +} diff --git a/packages/core_ui/test/artwork_headers_test.dart b/packages/core_ui/test/artwork_headers_test.dart index fab9fc03..2b916673 100644 --- a/packages/core_ui/test/artwork_headers_test.dart +++ b/packages/core_ui/test/artwork_headers_test.dart @@ -21,7 +21,9 @@ void main() { localUrl: local, externalUrl: external, urlMode: UrlMode.auto, - auth: const InstanceAuth.apiKey(apiKey: 'k'), + // No key, so these cover the custom headers on their own. The key + // itself is covered in artwork_auth_headers_test.dart. + auth: const InstanceAuth.apiKey(apiKey: ''), customHeaders: headers, ); diff --git a/services/service_emby/lib/src/emby_client.dart b/services/service_emby/lib/src/emby_client.dart index 2f2aa89d..7a4918c5 100644 --- a/services/service_emby/lib/src/emby_client.dart +++ b/services/service_emby/lib/src/emby_client.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:core_networking/core_networking.dart'; +import 'package:core_ui/core_ui.dart'; import 'package:dio/dio.dart'; import 'package:dio/io.dart'; @@ -146,6 +147,10 @@ class EmbyClient { _userId = result.user.id; _serverId = result.serverId; _dio.options.headers['X-Emby-Token'] = _token; + // Artwork is fetched outside Dio, so it gets the token through + // ArtworkHeaders as a header. It used to ride in the URL as api_key, + // which a reverse proxy writes to its access log in full. + ArtworkHeaders.setSession(baseUrl.toString(), {'X-Emby-Token': result.accessToken}); _loggedIn = true; } on DioException catch (e) { throw NetworkException.fromDio(e); @@ -397,8 +402,6 @@ class EmbyClient { ? 1.0 : (2 / 3))); - final String key = _token == null ? '' : '&api_key=$_token'; - // Resolve primary image target ID and tag String? posterTargetId; String? posterTag; @@ -492,7 +495,7 @@ class EmbyClient { } final String? posterUrl = posterTargetId != null - ? '$_baseStr/Items/$posterTargetId/Images/Primary?quality=100${(posterTag != null && posterTag.isNotEmpty) ? '&tag=$posterTag' : ''}$key' + ? '$_baseStr/Items/$posterTargetId/Images/Primary?quality=100${(posterTag != null && posterTag.isNotEmpty) ? '&tag=$posterTag' : ''}' : null; // Resolve backdrop image target ID and tag @@ -505,7 +508,7 @@ class EmbyClient { if (backdropTags != null && backdropTags.isNotEmpty) { final String tag = backdropTags.first.toString(); backdropUrl = - '$_baseStr/Items/${nowPlaying['Id']}/Images/Backdrop/0?quality=100&tag=$tag$key'; + '$_baseStr/Items/${nowPlaying['Id']}/Images/Backdrop/0?quality=100&tag=$tag'; } else if (parentBackdropTags != null && parentBackdropTags.isNotEmpty) { final String? parentBackdropId = @@ -516,7 +519,7 @@ class EmbyClient { if (parentBackdropId != null && parentBackdropId.isNotEmpty) { final String tag = parentBackdropTags.first.toString(); backdropUrl = - '$_baseStr/Items/$parentBackdropId/Images/Backdrop/0?quality=100&tag=$tag$key'; + '$_baseStr/Items/$parentBackdropId/Images/Backdrop/0?quality=100&tag=$tag'; } } else if (type != 'Audio') { final String? fallbackBackdropId = @@ -524,7 +527,7 @@ class EmbyClient { nowPlaying['Id'] as String?; if (fallbackBackdropId != null && fallbackBackdropId.isNotEmpty) { backdropUrl = - '$_baseStr/Items/$fallbackBackdropId/Images/Backdrop/0?quality=100$key'; + '$_baseStr/Items/$fallbackBackdropId/Images/Backdrop/0?quality=100'; } } @@ -730,74 +733,70 @@ class EmbyClient { /// Builds a primary-image (poster) URL for [item], or null if it has none. String? imageUrl(EmbyItem item, {int maxHeight = 420}) { - final String key = _token == null ? '' : '&api_key=$_token'; - // Prefer the Series poster (anime cover) over the episode thumbnail. if (item.type == 'Episode' && item.seriesId != null) { final String tagParam = item.seriesPrimaryImageTag != null ? '&tag=${item.seriesPrimaryImageTag}' : ''; return '$_baseStr/Items/${item.seriesId}/Images/Primary' - '?quality=100$tagParam$key'; + '?quality=100$tagParam'; } if (item.type == 'Audio') { if (item.albumPrimaryImageTag != null && item.albumId != null) { return '$_baseStr/Items/${item.albumId}/Images/Primary' - '?quality=100&tag=${item.albumPrimaryImageTag}$key'; + '?quality=100&tag=${item.albumPrimaryImageTag}'; } if (item.parentPrimaryImageTag != null && item.parentId != null) { return '$_baseStr/Items/${item.parentId}/Images/Primary' - '?quality=100&tag=${item.parentPrimaryImageTag}$key'; + '?quality=100&tag=${item.parentPrimaryImageTag}'; } if (item.imageTags.containsKey('Primary')) { return '$_baseStr/Items/${item.id}/Images/Primary' - '?quality=100&tag=${item.imageTags['Primary']}$key'; + '?quality=100&tag=${item.imageTags['Primary']}'; } final String targetId = item.albumId ?? item.parentId ?? item.id; return '$_baseStr/Items/$targetId/Images/Primary' - '?quality=100$key'; + '?quality=100'; } if (item.primaryImageItemId != null) { final String tagParam = item.primaryImageTag != null ? '&tag=${item.primaryImageTag}' : ''; return '$_baseStr/Items/${item.primaryImageItemId}/Images/Primary' - '?quality=100$tagParam$key'; + '?quality=100$tagParam'; } if (item.imageTags.containsKey('Primary')) { final String tag = item.imageTags['Primary']!; return '$_baseStr/Items/${item.id}/Images/Primary' - '?tag=$tag&quality=100$key'; + '?tag=$tag&quality=100'; } if (item.seriesPrimaryImageTag != null && item.seriesId != null) { final String tag = item.seriesPrimaryImageTag!; return '$_baseStr/Items/${item.seriesId}/Images/Primary' - '?tag=$tag&quality=100$key'; + '?tag=$tag&quality=100'; } if (item.parentPrimaryImageTag != null && item.parentId != null) { final String tag = item.parentPrimaryImageTag!; return '$_baseStr/Items/${item.parentId}/Images/Primary' - '?tag=$tag&quality=100$key'; + '?tag=$tag&quality=100'; } // Fallback: If no tags were provided in the payload, try fetching the primary image directly. return '$_baseStr/Items/${item.id}/Images/Primary' - '?quality=100$key'; + '?quality=100'; } /// Builds a banner image URL for [item], or null if it has none. String? bannerImageUrl(EmbyItem item, {int maxWidth = 1920}) { - final String key = _token == null ? '' : '&api_key=$_token'; - if (item.imageTags.containsKey('Banner')) { - return '$_baseStr/Items/${item.id}/Images/Banner/0?quality=100&tag=${item.imageTags['Banner']}$key'; + return '$_baseStr/Items/${item.id}/Images/Banner/0?quality=100&tag=${item.imageTags['Banner']}'; } else if (item.seriesId != null && item.seriesPrimaryImageTag != null) { // Sometimes series have banners under their own ID - return '$_baseStr/Items/${item.seriesId}/Images/Banner/0?quality=100$key'; + return '$_baseStr/Items/${item.seriesId}/Images/Banner/0?quality=100'; } return null; @@ -818,8 +817,6 @@ class EmbyClient { /// Builds a backdrop image URL for [item], or null if it has none. String? backdropImageUrl(EmbyItem item, {int maxWidth = 1920}) { - final String key = _token == null ? '' : '&api_key=$_token'; - String targetId = item.id; String tagParam = ''; int targetIndex = 0; @@ -850,14 +847,13 @@ class EmbyClient { } } - return '$_baseStr/Items/$targetId/Images/Backdrop/$targetIndex?quality=100$tagParam$key'; + return '$_baseStr/Items/$targetId/Images/Backdrop/$targetIndex?quality=100$tagParam'; } String untaggedImageUrl(String itemId, String imageType) { final String targetType = imageType == 'Backdrop' ? 'Backdrop/0' : imageType; - final String key = _token == null ? '' : '&api_key=$_token'; - return '$_baseStr/Items/$itemId/Images/$targetType?quality=100$key'; + return '$_baseStr/Items/$itemId/Images/$targetType?quality=100'; } Future> getRemoteImages( diff --git a/services/service_emby/pubspec.yaml b/services/service_emby/pubspec.yaml index 8621dee0..dd0199df 100644 --- a/services/service_emby/pubspec.yaml +++ b/services/service_emby/pubspec.yaml @@ -31,5 +31,7 @@ dependencies: dev_dependencies: build_runner: ^2.4.13 + flutter_test: + sdk: flutter freezed: ^3.2.5 json_serializable: ^6.8.0 diff --git a/services/service_emby/test/emby_artwork_token_test.dart b/services/service_emby/test/emby_artwork_token_test.dart new file mode 100644 index 00000000..1dbf1bbf --- /dev/null +++ b/services/service_emby/test/emby_artwork_token_test.dart @@ -0,0 +1,129 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_emby/service_emby.dart'; + +const String _base = 'http://emby.example.test:8096'; +const String _token = 'session-token-1'; + +/// Answers sign-in and one playing session, nothing else. +class _FakeEmby implements HttpClientAdapter { + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + final Object body = switch (options.path) { + 'Users/AuthenticateByName' => { + 'AccessToken': _token, + 'ServerId': 'srv', + 'User': {'Id': 'user-1', 'Name': 'atrium-test'}, + }, + 'Sessions' => [ + { + 'Id': 's1', + 'UserName': 'atrium-test', + 'Client': 'Web', + 'DeviceName': 'Browser', + 'NowPlayingItem': { + 'Id': 'movie-1', + 'Name': 'Big Buck Bunny', + 'Type': 'Movie', + 'RunTimeTicks': 6000000000, + 'ImageTags': {'Primary': 'p1'}, + 'BackdropImageTags': ['b1'], + }, + 'PlayState': {'PositionTicks': 0, 'IsPaused': false}, + }, + ], + _ => {}, + }; + return ResponseBody.fromString( + jsonEncode(body), + 200, + headers: >{ + Headers.contentTypeHeader: [Headers.jsonContentType], + }, + ); + } + + @override + void close({bool force = false}) {} +} + +void main() { + late EmbyClient client; + + setUp(() async { + ArtworkHeaders.update( + instances: const [ + Instance( + id: 'emby', + name: 'Emby', + kind: ServiceKind.emby, + localUrl: _base, + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.userPass(username: 'atrium-test', password: 'pw'), + ), + ], + global: const {}, + ); + final Dio dio = Dio(BaseOptions(baseUrl: '$_base/')) + ..httpClientAdapter = _FakeEmby(); + client = EmbyClient( + dio: dio, + baseUrl: Uri.parse('$_base/'), + username: 'atrium-test', + password: 'pw', + deviceId: 'device-1', + ); + await client.login(); + }); + + tearDown(ArtworkHeaders.reset); + + const EmbyItem movie = EmbyItem( + id: 'movie-1', + type: 'Movie', + imageTags: {'Primary': 'p1', 'Banner': 'n1'}, + backdropImageTags: ['b1'], + ); + + /// The token stays out of [url], and the artwork lookup sends it as a + /// header instead. + void expectHeaderNotQuery(String? url) { + expect(url, isNotNull); + expect(url, startsWith(_base)); + expect(url, isNot(contains(_token))); + expect(url, isNot(contains('api_key'))); + expect(ArtworkHeaders.forUrl(url)?['X-Emby-Token'], _token); + } + + test('posters', () => expectHeaderNotQuery(client.imageUrl(movie))); + test('banners', () => expectHeaderNotQuery(client.bannerImageUrl(movie))); + test('backdrops', () => expectHeaderNotQuery(client.backdropImageUrl(movie))); + test( + 'untagged images', + () => expectHeaderNotQuery(client.untaggedImageUrl('movie-1', 'Primary')), + ); + + test('now-playing artwork', () async { + final List sessions = await client.getSessions(); + expect(sessions, hasLength(1)); + expectHeaderNotQuery(sessions.single.posterUrl); + expectHeaderNotQuery(sessions.single.backdropUrl); + }); + + test('the token goes nowhere but its own server', () { + expect( + ArtworkHeaders.forUrl('https://image.tmdb.org/t/p/w500/abc.jpg'), + isNull, + ); + }); +} diff --git a/services/service_jellyfin/lib/src/jellyfin_client.dart b/services/service_jellyfin/lib/src/jellyfin_client.dart index 6775b659..74438a7f 100644 --- a/services/service_jellyfin/lib/src/jellyfin_client.dart +++ b/services/service_jellyfin/lib/src/jellyfin_client.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'package:core_networking/core_networking.dart'; +import 'package:core_ui/core_ui.dart'; import 'package:dio/dio.dart'; import 'package:dio/io.dart'; @@ -119,6 +120,10 @@ class JellyfinClient { _userId = result.user.id; _serverId = result.serverId; _dio.options.headers['Authorization'] = _authHeader(); + // Artwork is fetched outside Dio, so it gets the token through + // ArtworkHeaders as a header. It used to ride in the URL as api_key, + // which a reverse proxy writes to its access log in full. + ArtworkHeaders.setSession(baseUrl.toString(), {'Authorization': _authHeader()}); _loggedIn = true; } on DioException catch (e) { throw NetworkException.fromDio(e); @@ -373,8 +378,6 @@ class JellyfinClient { ? 1.0 : (2 / 3))); - final String key = _token == null ? '' : '&api_key=$_token'; - // Resolve primary image target ID and tag String? posterTargetId; String? posterTag; @@ -468,7 +471,7 @@ class JellyfinClient { } final String? posterUrl = posterTargetId != null - ? '$_baseStr/Items/$posterTargetId/Images/Primary?quality=100${(posterTag != null && posterTag.isNotEmpty) ? '&tag=$posterTag' : ''}$key' + ? '$_baseStr/Items/$posterTargetId/Images/Primary?quality=100${(posterTag != null && posterTag.isNotEmpty) ? '&tag=$posterTag' : ''}' : null; // Resolve backdrop image target ID and tag @@ -481,7 +484,7 @@ class JellyfinClient { if (backdropTags != null && backdropTags.isNotEmpty) { final String tag = backdropTags.first.toString(); backdropUrl = - '$_baseStr/Items/${nowPlaying['Id']}/Images/Backdrop/0?quality=100&tag=$tag$key'; + '$_baseStr/Items/${nowPlaying['Id']}/Images/Backdrop/0?quality=100&tag=$tag'; } else if (parentBackdropTags != null && parentBackdropTags.isNotEmpty) { final String? parentBackdropId = @@ -492,7 +495,7 @@ class JellyfinClient { if (parentBackdropId != null && parentBackdropId.isNotEmpty) { final String tag = parentBackdropTags.first.toString(); backdropUrl = - '$_baseStr/Items/$parentBackdropId/Images/Backdrop/0?quality=100&tag=$tag$key'; + '$_baseStr/Items/$parentBackdropId/Images/Backdrop/0?quality=100&tag=$tag'; } } else if (type != 'Audio') { final String? fallbackBackdropId = @@ -500,7 +503,7 @@ class JellyfinClient { nowPlaying['Id'] as String?; if (fallbackBackdropId != null && fallbackBackdropId.isNotEmpty) { backdropUrl = - '$_baseStr/Items/$fallbackBackdropId/Images/Backdrop/0?quality=100$key'; + '$_baseStr/Items/$fallbackBackdropId/Images/Backdrop/0?quality=100'; } } @@ -766,74 +769,70 @@ class JellyfinClient { /// Builds a primary-image (poster) URL for [item], or null if it has none. String? imageUrl(JellyfinItem item, {int maxHeight = 420}) { - final String key = _token == null ? '' : '&api_key=$_token'; - // Prefer the Series poster (anime cover) over the episode thumbnail. if (item.type == 'Episode' && item.seriesId != null) { final String tagParam = item.seriesPrimaryImageTag != null ? '&tag=${item.seriesPrimaryImageTag}' : ''; return '$_baseStr/Items/${item.seriesId}/Images/Primary' - '?quality=100$tagParam$key'; + '?quality=100$tagParam'; } if (item.type == 'Audio') { if (item.albumPrimaryImageTag != null && item.albumId != null) { return '$_baseStr/Items/${item.albumId}/Images/Primary' - '?quality=100&tag=${item.albumPrimaryImageTag}$key'; + '?quality=100&tag=${item.albumPrimaryImageTag}'; } if (item.parentPrimaryImageTag != null && item.parentId != null) { return '$_baseStr/Items/${item.parentId}/Images/Primary' - '?quality=100&tag=${item.parentPrimaryImageTag}$key'; + '?quality=100&tag=${item.parentPrimaryImageTag}'; } if (item.imageTags.containsKey('Primary')) { return '$_baseStr/Items/${item.id}/Images/Primary' - '?quality=100&tag=${item.imageTags['Primary']}$key'; + '?quality=100&tag=${item.imageTags['Primary']}'; } final String targetId = item.albumId ?? item.parentId ?? item.id; return '$_baseStr/Items/$targetId/Images/Primary' - '?quality=100$key'; + '?quality=100'; } if (item.primaryImageItemId != null) { final String tagParam = item.primaryImageTag != null ? '&tag=${item.primaryImageTag}' : ''; return '$_baseStr/Items/${item.primaryImageItemId}/Images/Primary' - '?quality=100$tagParam$key'; + '?quality=100$tagParam'; } if (item.imageTags.containsKey('Primary')) { final String tag = item.imageTags['Primary']!; return '$_baseStr/Items/${item.id}/Images/Primary' - '?tag=$tag&quality=100$key'; + '?tag=$tag&quality=100'; } if (item.seriesPrimaryImageTag != null && item.seriesId != null) { final String tag = item.seriesPrimaryImageTag!; return '$_baseStr/Items/${item.seriesId}/Images/Primary' - '?tag=$tag&quality=100$key'; + '?tag=$tag&quality=100'; } if (item.parentPrimaryImageTag != null && item.parentId != null) { final String tag = item.parentPrimaryImageTag!; return '$_baseStr/Items/${item.parentId}/Images/Primary' - '?tag=$tag&quality=100$key'; + '?tag=$tag&quality=100'; } // Fallback: If no tags were provided in the payload, try fetching the primary image directly. return '$_baseStr/Items/${item.id}/Images/Primary' - '?quality=100$key'; + '?quality=100'; } /// Builds a banner image URL for [item], or null if it has none. String? bannerImageUrl(JellyfinItem item, {int maxWidth = 1920}) { - final String key = _token == null ? '' : '&api_key=$_token'; - if (item.imageTags.containsKey('Banner')) { - return '$_baseStr/Items/${item.id}/Images/Banner/0?quality=100&tag=${item.imageTags['Banner']}$key'; + return '$_baseStr/Items/${item.id}/Images/Banner/0?quality=100&tag=${item.imageTags['Banner']}'; } else if (item.seriesId != null && item.seriesPrimaryImageTag != null) { // Sometimes series have banners under their own ID - return '$_baseStr/Items/${item.seriesId}/Images/Banner/0?quality=100$key'; + return '$_baseStr/Items/${item.seriesId}/Images/Banner/0?quality=100'; } return null; @@ -854,8 +853,6 @@ class JellyfinClient { /// Builds a backdrop image URL for [item], or null if it has none. String? backdropImageUrl(JellyfinItem item, {int maxWidth = 1920}) { - final String key = _token == null ? '' : '&api_key=$_token'; - String targetId = item.id; String tagParam = ''; int targetIndex = 0; @@ -886,14 +883,13 @@ class JellyfinClient { } } - return '$_baseStr/Items/$targetId/Images/Backdrop/$targetIndex?quality=100$tagParam$key'; + return '$_baseStr/Items/$targetId/Images/Backdrop/$targetIndex?quality=100$tagParam'; } String untaggedImageUrl(String itemId, String imageType) { final String targetType = imageType == 'Backdrop' ? 'Backdrop/0' : imageType; - final String key = _token == null ? '' : '&api_key=$_token'; - return '$_baseStr/Items/$itemId/Images/$targetType?quality=100$key'; + return '$_baseStr/Items/$itemId/Images/$targetType?quality=100'; } Future> getRemoteImages( diff --git a/services/service_jellyfin/pubspec.yaml b/services/service_jellyfin/pubspec.yaml index 1c7b4980..83f8d3ba 100644 --- a/services/service_jellyfin/pubspec.yaml +++ b/services/service_jellyfin/pubspec.yaml @@ -31,5 +31,7 @@ dependencies: url_launcher: ^6.3.2 dev_dependencies: build_runner: ^2.4.13 + flutter_test: + sdk: flutter freezed: ^3.2.5 json_serializable: ^6.8.0 diff --git a/services/service_jellyfin/test/jellyfin_artwork_token_test.dart b/services/service_jellyfin/test/jellyfin_artwork_token_test.dart new file mode 100644 index 00000000..fddce168 --- /dev/null +++ b/services/service_jellyfin/test/jellyfin_artwork_token_test.dart @@ -0,0 +1,132 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_jellyfin/service_jellyfin.dart'; + +const String _base = 'http://jellyfin.example.test:8096'; +const String _token = 'session-token-1'; + +/// Answers sign-in and one playing session, nothing else. +class _FakeJellyfin implements HttpClientAdapter { + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + final Object body = switch (options.path) { + 'Users/AuthenticateByName' => { + 'AccessToken': _token, + 'ServerId': 'srv', + 'User': {'Id': 'user-1', 'Name': 'atrium-test'}, + }, + 'Sessions' => [ + { + 'Id': 's1', + 'UserName': 'atrium-test', + 'Client': 'Web', + 'DeviceName': 'Browser', + 'NowPlayingItem': { + 'Id': 'movie-1', + 'Name': 'Big Buck Bunny', + 'Type': 'Movie', + 'RunTimeTicks': 6000000000, + 'ImageTags': {'Primary': 'p1'}, + 'BackdropImageTags': ['b1'], + }, + 'PlayState': {'PositionTicks': 0, 'IsPaused': false}, + }, + ], + _ => {}, + }; + return ResponseBody.fromString( + jsonEncode(body), + 200, + headers: >{ + Headers.contentTypeHeader: [Headers.jsonContentType], + }, + ); + } + + @override + void close({bool force = false}) {} +} + +void main() { + late JellyfinClient client; + + setUp(() async { + ArtworkHeaders.update( + instances: const [ + Instance( + id: 'jf', + name: 'Jellyfin', + kind: ServiceKind.jellyfin, + localUrl: _base, + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.userPass(username: 'atrium-test', password: 'pw'), + ), + ], + global: const {}, + ); + final Dio dio = Dio(BaseOptions(baseUrl: '$_base/')) + ..httpClientAdapter = _FakeJellyfin(); + client = JellyfinClient( + dio: dio, + baseUrl: Uri.parse('$_base/'), + username: 'atrium-test', + password: 'pw', + deviceId: 'device-1', + ); + await client.login(); + }); + + tearDown(ArtworkHeaders.reset); + + const JellyfinItem movie = JellyfinItem( + id: 'movie-1', + type: 'Movie', + imageTags: {'Primary': 'p1', 'Banner': 'n1'}, + backdropImageTags: ['b1'], + ); + + /// The token stays out of [url], and the artwork lookup sends it as a + /// header instead. + void expectHeaderNotQuery(String? url) { + expect(url, isNotNull); + expect(url, startsWith(_base)); + expect(url, isNot(contains(_token))); + expect(url, isNot(contains('api_key'))); + expect( + ArtworkHeaders.forUrl(url)?['Authorization'], + contains('Token="$_token"'), + ); + } + + test('posters', () => expectHeaderNotQuery(client.imageUrl(movie))); + test('banners', () => expectHeaderNotQuery(client.bannerImageUrl(movie))); + test('backdrops', () => expectHeaderNotQuery(client.backdropImageUrl(movie))); + test( + 'untagged images', + () => expectHeaderNotQuery(client.untaggedImageUrl('movie-1', 'Primary')), + ); + + test('now-playing artwork', () async { + final List sessions = await client.getSessions(); + expect(sessions, hasLength(1)); + expectHeaderNotQuery(sessions.single.posterUrl); + expectHeaderNotQuery(sessions.single.backdropUrl); + }); + + test('the token goes nowhere but its own server', () { + expect( + ArtworkHeaders.forUrl('https://image.tmdb.org/t/p/w500/abc.jpg'), + isNull, + ); + }); +} diff --git a/services/service_lidarr/lib/src/features/system/log_file_save.dart b/services/service_lidarr/lib/src/features/system/log_file_save.dart new file mode 100644 index 00000000..4d5f04dd --- /dev/null +++ b/services/service_lidarr/lib/src/features/system/log_file_save.dart @@ -0,0 +1,59 @@ +import 'dart:convert'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// Saves a log file's text, already read through the API, with the system +/// save sheet. +/// +/// The API is the only route that carries the key as a header. A browser +/// can only be handed a URL, so the old "open in browser" download put the +/// key in its query, where the browser's history and any reverse proxy's +/// access log kept it. +Future saveLidarrLogFile( + BuildContext context, { + required String filename, + required Future Function() read, +}) async { + final String name = _safeFileName(filename); + final ScaffoldMessengerState messenger = ScaffoldMessenger.of(context); + void say(String text) => messenger.showSnackBar( + SnackBar(content: Text(text), behavior: SnackBarBehavior.floating), + ); + + final String content; + try { + content = await read(); + } on Object { + say('Could not read $name'); + return; + } + + final String? saved; + try { + saved = await FilePicker.saveFile( + dialogTitle: 'Save log file', + fileName: name, + bytes: Uint8List.fromList(utf8.encode(content)), + ); + } on PlatformException catch (e) { + say('Could not open save sheet: ${e.message}'); + return; + } + if (saved != null) { + say('Saved $name'); + } +} + +/// The last segment of [reported], with characters a file name cannot hold +/// replaced. The name comes from the server, so it is never trusted as a +/// path. +String _safeFileName(String reported) { + final String last = reported + .split(RegExp(r'[\\/]')) + .last + .replaceAll(RegExp(r'[<>:"|?*]'), '_') + .trim(); + return last.isEmpty || last == '.' || last == '..' ? 'lidarr.txt' : last; +} diff --git a/services/service_lidarr/lib/src/features/system/views/log_file_reader_screen.dart b/services/service_lidarr/lib/src/features/system/views/log_file_reader_screen.dart index 442b867e..92aa91fc 100644 --- a/services/service_lidarr/lib/src/features/system/views/log_file_reader_screen.dart +++ b/services/service_lidarr/lib/src/features/system/views/log_file_reader_screen.dart @@ -4,11 +4,11 @@ import 'package:core_ui/core_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:url_launcher/url_launcher.dart'; import '../../../core/lidarr_formatters.dart'; import '../../../generated/generated.dart'; import '../../../lidarr_providers.dart'; +import '../log_file_save.dart'; /// High-performance, virtualized in-app log viewer for Lidarr log files. class LogFileReaderScreen extends ConsumerStatefulWidget { @@ -138,49 +138,20 @@ class _LogFileReaderScreenState extends ConsumerState { } } - String _buildDirectDownloadUrl() { - final String rawBase = widget.instance.localUrl.isNotEmpty - ? widget.instance.localUrl - : widget.instance.externalUrl; - final String host = rawBase.replaceAll(RegExp(r'/+$'), ''); - final String path = - widget.file.downloadUrl ?? '/logfile/${widget.file.filename}'; - final String normalizedPath = path.startsWith('/') ? path : '/$path'; - final String apiKey = switch (widget.instance.auth) { - InstanceAuthApiKey(:final String apiKey) => apiKey, - _ => '', - }; - final String separator = normalizedPath.contains('?') ? '&' : '?'; - return '$host$normalizedPath${apiKey.isNotEmpty ? '${separator}apikey=$apiKey' : ''}'; - } - - Future _downloadLogFile() async { - final String downloadUrl = _buildDirectDownloadUrl(); - final Uri uri = Uri.parse(downloadUrl); - try { - final bool launched = await launchUrl( - uri, - mode: LaunchMode.externalApplication, + Future _downloadLogFile() => saveLidarrLogFile( + context, + filename: widget.file.filename ?? 'lidarr.txt', + read: () => ref.read( + lidarrLogFileContentProvider( + ( + widget.instance, + filename: widget.file.filename ?? '', + contentsUrl: widget.file.contentsUrl, + downloadUrl: widget.file.downloadUrl, + ), + ).future, + ), ); - if (!launched && mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Could not open download URL: $downloadUrl'), - behavior: SnackBarBehavior.floating, - ), - ); - } - } catch (e) { - if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Failed to trigger download: $e'), - behavior: SnackBarBehavior.floating, - ), - ); - } - } - } Color _getLineColor(String line, ColorScheme cs) { final String lower = line.toLowerCase(); diff --git a/services/service_lidarr/lib/src/features/system/views/log_files_view.dart b/services/service_lidarr/lib/src/features/system/views/log_files_view.dart index 00e30a15..4dd8fcd6 100644 --- a/services/service_lidarr/lib/src/features/system/views/log_files_view.dart +++ b/services/service_lidarr/lib/src/features/system/views/log_files_view.dart @@ -3,11 +3,11 @@ import 'package:core_ui/core_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:url_launcher/url_launcher.dart'; import '../../../core/lidarr_formatters.dart'; import '../../../generated/generated.dart'; import '../../../lidarr_providers.dart'; +import '../log_file_save.dart'; import 'log_file_reader_screen.dart'; /// Log files available on disk view. @@ -16,46 +16,24 @@ class LogFilesView extends ConsumerWidget { final Instance instance; - String _buildDirectDownloadUrl(LogFileResource file) { - final String rawBase = - instance.localUrl.isNotEmpty ? instance.localUrl : instance.externalUrl; - final String host = rawBase.replaceAll(RegExp(r'/+$'), ''); - final String path = file.downloadUrl ?? '/logfile/${file.filename}'; - final String normalizedPath = path.startsWith('/') ? path : '/$path'; - final String apiKey = switch (instance.auth) { - InstanceAuthApiKey(:final String apiKey) => apiKey, - _ => '', - }; - final String separator = normalizedPath.contains('?') ? '&' : '?'; - return '$host$normalizedPath${apiKey.isNotEmpty ? '${separator}apikey=$apiKey' : ''}'; - } - - Future _downloadFile(BuildContext context, LogFileResource file) async { - final String downloadUrl = _buildDirectDownloadUrl(file); - final Uri uri = Uri.parse(downloadUrl); - try { - final bool launched = await launchUrl( - uri, - mode: LaunchMode.externalApplication, - ); - if (!launched && context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Could not open download URL: $downloadUrl'), - behavior: SnackBarBehavior.floating, - ), - ); - } - } catch (e) { - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Failed to trigger download: $e'), - behavior: SnackBarBehavior.floating, - ), - ); - } - } + Future _downloadFile( + BuildContext context, + WidgetRef ref, + LogFileResource file, + ) { + final provider = lidarrLogFileContentProvider( + ( + instance, + filename: file.filename ?? '', + contentsUrl: file.contentsUrl, + downloadUrl: file.downloadUrl, + ), + ); + return saveLidarrLogFile( + context, + filename: file.filename ?? 'lidarr.txt', + read: () => ref.read(provider.future), + ); } void _openFileReader(BuildContext context, LogFileResource file) { @@ -70,7 +48,11 @@ class LogFilesView extends ConsumerWidget { ); } - void _showFileDetailDialog(BuildContext context, LogFileResource file) { + void _showFileDetailDialog( + BuildContext context, + WidgetRef ref, + LogFileResource file, + ) { showDialog( context: context, builder: (BuildContext ctx) { @@ -138,7 +120,7 @@ class LogFilesView extends ConsumerWidget { label: const Text('Download'), onPressed: () { Navigator.pop(ctx); - _downloadFile(context, file); + _downloadFile(context, ref, file); }, ), FilledButton.icon( @@ -244,12 +226,12 @@ class LogFilesView extends ConsumerWidget { IconButton( icon: const Icon(Icons.download_outlined, size: 20), tooltip: 'Download', - onPressed: () => _downloadFile(context, file), + onPressed: () => _downloadFile(context, ref, file), ), IconButton( icon: const Icon(Icons.info_outline, size: 20), tooltip: 'Details', - onPressed: () => _showFileDetailDialog(context, file), + onPressed: () => _showFileDetailDialog(context, ref, file), ), const Icon( Icons.chevron_right, diff --git a/services/service_lidarr/lib/src/lidarr_artwork.dart b/services/service_lidarr/lib/src/lidarr_artwork.dart index c91c8d3f..a1883293 100644 --- a/services/service_lidarr/lib/src/lidarr_artwork.dart +++ b/services/service_lidarr/lib/src/lidarr_artwork.dart @@ -45,7 +45,8 @@ abstract final class LidarrArtwork { static bool _isRemote(String? url) => url != null && url.isNotEmpty && url.startsWith('http'); - /// Builds an absolute, authenticated image URL for an item's [MediaCover]. + /// Builds an absolute image URL for an item's [MediaCover]. The api key is + /// not in it; `AtriumNetworkImage` sends it as a header. /// /// Lidarr hands out web paths, prefixed with its URL Base when one is set: /// `/base/MediaCover//poster.jpg`, @@ -116,17 +117,10 @@ abstract final class LidarrArtwork { resolvedPath = pathOrUrl; } - final String? apiKey = switch (instance.auth) { - InstanceAuthApiKey(:final String apiKey) when apiKey.isNotEmpty => apiKey, - _ => null, - }; - final String separator = resolvedPath.contains('?') ? '&' : '?'; - final String withKey = apiKey != null - ? '$resolvedPath${separator}apikey=$apiKey' - : resolvedPath; - + // No key in the URL: a reverse proxy logs the full request line. + // Artwork carries it as an X-Api-Key header, from ArtworkHeaders. final Uri base = Uri.parse(rawBase.endsWith('/') ? rawBase : '$rawBase/'); - return base.resolve(withKey).toString(); + return base.resolve(resolvedPath).toString(); } /// Poster / artwork image for an artist. Defaults to optimized 250px thumbnail. diff --git a/services/service_lidarr/pubspec.yaml b/services/service_lidarr/pubspec.yaml index a8917a24..005d920f 100644 --- a/services/service_lidarr/pubspec.yaml +++ b/services/service_lidarr/pubspec.yaml @@ -16,6 +16,7 @@ dependencies: core_storage: core_ui: dio: ^5.7.0 + file_picker: ^12.0.0-beta.7 flutter: sdk: flutter flutter_riverpod: ^3.3.2 @@ -33,3 +34,4 @@ dev_dependencies: sdk: flutter freezed: ^3.2.5 json_serializable: ^6.8.0 + plugin_platform_interface: ^2.1.8 diff --git a/services/service_lidarr/test/features/log_file_save_test.dart b/services/service_lidarr/test/features/log_file_save_test.dart new file mode 100644 index 00000000..71ff2490 --- /dev/null +++ b/services/service_lidarr/test/features/log_file_save_test.dart @@ -0,0 +1,136 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:service_lidarr/service_lidarr.dart'; +import 'package:service_lidarr/src/features/system/views/log_file_reader_screen.dart'; +import 'package:service_lidarr/src/features/system/views/log_files_view.dart'; + +import 'test_helpers.dart'; + +/// Stands in for the system save sheet and keeps what it was handed. +class _SaveSheet extends FilePickerPlatform with MockPlatformInterfaceMixin { + String? fileName; + Uint8List? bytes; + + @override + Future saveFile({ + String? dialogTitle, + required String fileName, + String? initialDirectory, + FileType type = FileType.any, + List? allowedExtensions, + required Uint8List bytes, + dynamic Function(FilePickerStatus)? onFileLoading, + bool lockParentWindow = false, + }) async { + this.fileName = fileName; + this.bytes = bytes; + return '/storage/emulated/0/Download/$fileName'; + } +} + +const LogFileResource _file = LogFileResource( + id: 1, + filename: 'lidarr.txt', + lastWriteTime: '2026-11-24T10:00:00Z', + contentsUrl: '/api/v1/log/file/lidarr.txt', + downloadUrl: '/logfile/lidarr.txt', +); + +const String _log = '2026-11-24 10:00:00.0|Info|Bootstrap|Starting Lidarr\n'; + +/// Saving a log file hands the system save sheet the text the app read +/// through its API. It used to open the browser on a URL with the api key in +/// its query, which put the key in the browser's history and in any reverse +/// proxy's access log. +void main() { + late _SaveSheet sheet; + + setUp(() { + sheet = _SaveSheet(); + FilePickerPlatform.instance = sheet; + }); + + Future pump(WidgetTester tester, Widget child) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + lidarrLogFilesProvider(testInstance) + .overrideWith((Ref ref) async => [_file]), + // Slow, as a real read over the network is, so a provider dropped + // while it is still loading shows up as a log that never saves. + lidarrLogFileContentProvider.overrideWith((ref, key) async { + await Future.delayed(const Duration(milliseconds: 200)); + return _log; + }), + ], + child: MaterialApp(home: Scaffold(body: child)), + ), + ); + await tester.pumpAndSettle(); + } + + void expectSaved(WidgetTester tester) { + expect(sheet.fileName, 'lidarr.txt'); + expect(utf8.decode(sheet.bytes!), _log); + expect(find.textContaining('test-api-key'), findsNothing); + } + + testWidgets('the reader saves the log it is showing', (tester) async { + await pump( + tester, + const LogFileReaderScreen(instance: testInstance, file: _file), + ); + await tester.tap(find.byTooltip('Download log file')); + await tester.pumpAndSettle(); + expectSaved(tester); + }); + + testWidgets('the list saves a log without opening it', (tester) async { + await pump(tester, const LogFilesView(instance: testInstance)); + await tester.tap(find.byTooltip('Download')); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pumpAndSettle(); + expectSaved(tester); + }); + + testWidgets('a name from the server cannot point outside the folder', + (tester) async { + // The file name is whatever Lidarr reports. The save sheet gets only its + // last segment, cleaned, never a path. + for (final (String reported, String offered) in <(String, String)>[ + ('../../.ssh/authorized_keys', 'authorized_keys'), + (r'..\..\evil.txt', 'evil.txt'), + ('..', 'lidarr.txt'), + ('', 'lidarr.txt'), + ('a:b*c?.txt', 'a_b_c_.txt'), + ]) { + await pump( + tester, + LogFileReaderScreen( + instance: testInstance, + file: _file.copyWith(filename: reported), + ), + ); + await tester.tap(find.byTooltip('Download log file')); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pumpAndSettle(); + expect(sheet.fileName, offered, reason: reported); + } + }); + + testWidgets('the details dialog saves it too', (tester) async { + await pump(tester, const LogFilesView(instance: testInstance)); + await tester.tap(find.byTooltip('Details')); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(OutlinedButton, 'Download')); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pumpAndSettle(); + expectSaved(tester); + }); +} diff --git a/services/service_lidarr/test/lidarr_artwork_test.dart b/services/service_lidarr/test/lidarr_artwork_test.dart index 61b0f2cd..db1d54ac 100644 --- a/services/service_lidarr/test/lidarr_artwork_test.dart +++ b/services/service_lidarr/test/lidarr_artwork_test.dart @@ -56,7 +56,7 @@ void main() { expect( url, 'http://192.168.1.10:8686/lidarr/api/v1/mediacover/artist/5/' - 'poster-250.jpg?lastWrite=639210363806026257&apikey=k', + 'poster-250.jpg?lastWrite=639210363806026257', ); expect(url, isNot(contains('/lidarr/lidarr/'))); expect(url, isNot(contains('/MediaCover/'))); @@ -66,7 +66,7 @@ void main() { expect( LidarrArtwork.albumCoverUrl(_lidarr(), [_albumCover]), 'http://192.168.1.10:8686/lidarr/api/v1/mediacover/album/30/' - 'cover-250.jpg?lastWrite=639223812709425181&apikey=k', + 'cover-250.jpg?lastWrite=639223812709425181', ); }); @@ -89,8 +89,7 @@ void main() { ); expect( url, - 'http://192.168.1.10:8686/lidarr/MediaCoverProxy/0a1b2c/1-500.jpg' - '?apikey=k', + 'http://192.168.1.10:8686/lidarr/MediaCoverProxy/0a1b2c/1-500.jpg', ); }); }); @@ -194,8 +193,7 @@ void main() { ], width: null, ), - 'https://lidarr.example.org/api/v1/mediacover/artist/5/poster.jpg' - '?apikey=k', + 'https://lidarr.example.org/api/v1/mediacover/artist/5/poster.jpg', ); }); } diff --git a/services/service_lidarr/test/lidarr_runtime_test.dart b/services/service_lidarr/test/lidarr_runtime_test.dart index 8880492d..bcf0ebe5 100644 --- a/services/service_lidarr/test/lidarr_runtime_test.dart +++ b/services/service_lidarr/test/lidarr_runtime_test.dart @@ -126,7 +126,7 @@ void main() { expect( posterUrl, equals( - 'https://lidarr.kurai.cloud/api/v1/mediacover/artist/5/poster-250.jpg?lastWrite=639210363806026257&apikey=my-api-key', + 'https://lidarr.kurai.cloud/api/v1/mediacover/artist/5/poster-250.jpg?lastWrite=639210363806026257', ), ); @@ -136,7 +136,7 @@ void main() { expect( posterFullUrl, equals( - 'https://lidarr.kurai.cloud/api/v1/mediacover/artist/5/poster.jpg?lastWrite=639210363806026257&apikey=my-api-key', + 'https://lidarr.kurai.cloud/api/v1/mediacover/artist/5/poster.jpg?lastWrite=639210363806026257', ), ); @@ -145,7 +145,7 @@ void main() { expect( albumUrl, equals( - 'https://lidarr.kurai.cloud/api/v1/mediacover/album/30/cover-250.jpg?lastWrite=639223812709425181&apikey=my-api-key', + 'https://lidarr.kurai.cloud/api/v1/mediacover/album/30/cover-250.jpg?lastWrite=639223812709425181', ), ); @@ -163,7 +163,7 @@ void main() { expect( subpathUrl, equals( - 'http://192.168.1.100:8686/lidarr/api/v1/mediacover/artist/5/poster-250.jpg?lastWrite=639210363806026257&apikey=key', + 'http://192.168.1.100:8686/lidarr/api/v1/mediacover/artist/5/poster-250.jpg?lastWrite=639210363806026257', ), ); }); diff --git a/services/service_plex/lib/src/plex_api.dart b/services/service_plex/lib/src/plex_api.dart index 4169e1e4..6089ac7e 100644 --- a/services/service_plex/lib/src/plex_api.dart +++ b/services/service_plex/lib/src/plex_api.dart @@ -155,12 +155,15 @@ class PlexApi { /// Builds an absolute poster URL from a relative [thumb] path. Returns null /// when the item has no thumbnail. The Dio base URL is the already-resolved /// LAN/WAN address. + /// + /// The token is not in it: a reverse proxy logs the full request line. + /// `AtriumNetworkImage` sends it as an X-Plex-Token header instead. String? imageUrl(String? thumb) { if (thumb == null || thumb.isEmpty) { return null; } final String base = _dio.options.baseUrl.replaceAll(RegExp(r'/+$'), ''); - return '$base$thumb?X-Plex-Token=$token'; + return '$base$thumb'; } /// Stable-ish client id for Companion command routing + a per-client diff --git a/services/service_plex/test/plex_image_url_test.dart b/services/service_plex/test/plex_image_url_test.dart new file mode 100644 index 00000000..b646596a --- /dev/null +++ b/services/service_plex/test/plex_image_url_test.dart @@ -0,0 +1,30 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_plex/service_plex.dart'; + +void main() { + PlexApi api(String baseUrl) => + PlexApi(Dio(BaseOptions(baseUrl: baseUrl)), token: 'plex-secret'); + + test('a poster url is the thumb under the resolved address', () { + expect( + api('http://192.168.0.10:32400/').imageUrl('/library/metadata/7/thumb/9'), + 'http://192.168.0.10:32400/library/metadata/7/thumb/9', + ); + }); + + test('the token stays out of the url', () { + // A reverse proxy writes the full request line to its access log. + // Artwork carries the token as an X-Plex-Token header instead, from + // ArtworkHeaders in core_ui. + expect( + api('https://plex.example.org').imageUrl('/library/metadata/7/art/9'), + isNot(contains('plex-secret')), + ); + }); + + test('no thumb, no url', () { + expect(api('http://192.168.0.10:32400').imageUrl(null), isNull); + expect(api('http://192.168.0.10:32400').imageUrl(''), isNull); + }); +} diff --git a/services/service_prowlarr/lib/service_prowlarr.dart b/services/service_prowlarr/lib/service_prowlarr.dart index 83122284..4e639881 100644 --- a/services/service_prowlarr/lib/service_prowlarr.dart +++ b/services/service_prowlarr/lib/service_prowlarr.dart @@ -6,10 +6,12 @@ /// template. library; +export 'src/models/prowlarr_category.dart'; export 'src/models/prowlarr_indexer.dart'; export 'src/models/prowlarr_indexer_stats.dart'; export 'src/models/prowlarr_release.dart'; export 'src/prowlarr_api.dart'; export 'src/prowlarr_home.dart'; export 'src/prowlarr_providers.dart'; +export 'src/prowlarr_search_filters.dart'; export 'src/prowlarr_search_screen.dart'; diff --git a/services/service_prowlarr/lib/src/models/prowlarr_category.dart b/services/service_prowlarr/lib/src/models/prowlarr_category.dart new file mode 100644 index 00000000..cbe1d125 --- /dev/null +++ b/services/service_prowlarr/lib/src/models/prowlarr_category.dart @@ -0,0 +1,31 @@ +/// One of Prowlarr's standard Newznab categories, from +/// `GET /api/v1/indexer/categories`: a parent such as Movies (2000) with its +/// subcategories such as Movies/HD (2040). +class ProwlarrCategory { + const ProwlarrCategory({ + required this.id, + required this.name, + this.subCategories = const [], + }); + + factory ProwlarrCategory.fromJson(Map json) => + ProwlarrCategory( + id: (json['id'] as num?)?.toInt() ?? 0, + name: (json['name'] as String?) ?? '', + subCategories: [ + for (final Object? e + in (json['subCategories'] as List?) ?? []) + if (e is Map) ProwlarrCategory.fromJson(e), + ], + ); + + final int id; + final String name; + final List subCategories; + + /// The name without its parent's prefix: "HD" for "Movies/HD". + String get shortName { + final int slash = name.indexOf('/'); + return slash < 0 ? name : name.substring(slash + 1); + } +} diff --git a/services/service_prowlarr/lib/src/prowlarr_api.dart b/services/service_prowlarr/lib/src/prowlarr_api.dart index a6b0144d..f4057b2d 100644 --- a/services/service_prowlarr/lib/src/prowlarr_api.dart +++ b/services/service_prowlarr/lib/src/prowlarr_api.dart @@ -2,6 +2,7 @@ import 'package:core_networking/core_networking.dart'; import 'package:dio/dio.dart'; import 'models/prowlarr_application.dart'; +import 'models/prowlarr_category.dart'; import 'models/prowlarr_history.dart'; import 'models/prowlarr_indexer.dart'; import 'models/prowlarr_indexer_stats.dart'; @@ -32,6 +33,20 @@ class ProwlarrApi { } } + /// The standard category tree a search can be narrowed to. + Future> getCategories() async { + try { + final Response resp = + await _dio.get('$_base/indexer/categories'); + return [ + for (final Object? e in resp.data as List) + if (e is Map) ProwlarrCategory.fromJson(e), + ]; + } on DioException catch (e) { + throw NetworkException.fromDio(e); + } + } + Future getIndexerStats() async { try { final Response resp = @@ -171,6 +186,7 @@ class ProwlarrApi { String query, { List indexerIds = const [], List categories = const [], + String type = 'search', int limit = 150, }) async { try { @@ -178,7 +194,7 @@ class ProwlarrApi { '$_base/search', queryParameters: { 'query': query, - 'type': 'search', + 'type': type, 'limit': limit, 'offset': 0, if (indexerIds.isNotEmpty) 'indexerIds': indexerIds, diff --git a/services/service_prowlarr/lib/src/prowlarr_providers.dart b/services/service_prowlarr/lib/src/prowlarr_providers.dart index 1b34a192..03af2b7e 100644 --- a/services/service_prowlarr/lib/src/prowlarr_providers.dart +++ b/services/service_prowlarr/lib/src/prowlarr_providers.dart @@ -3,6 +3,7 @@ import 'package:core_networking/core_networking.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'models/prowlarr_application.dart'; +import 'models/prowlarr_category.dart'; import 'models/prowlarr_history.dart'; import 'models/prowlarr_indexer.dart'; import 'models/prowlarr_indexer_stats.dart'; @@ -44,6 +45,23 @@ final prowlarrIndexersProvider = return indexers; }); +/// Prowlarr's standard category tree, for narrowing a search. Fixed per +/// Prowlarr version, so it is fetched once and not polled. +final prowlarrCategoriesProvider = + FutureProvider.autoDispose.family, Instance>(( + Ref ref, + Instance instance, +) async { + final ProwlarrApi api = await ref.watch( + prowlarrApiProvider(instance).future, + ); + final List tree = await api.getCategories(); + // Kept once loaded, so reopening the filters doesn't fetch it again. A + // failure isn't kept, so Retry asks again. + ref.keepAlive(); + return tree; +}); + /// Indexer stats keyed by indexerId, for badge counts in the list. Polls /// slowly while watched. final prowlarrStatsByIdProvider = diff --git a/services/service_prowlarr/lib/src/prowlarr_search_filters.dart b/services/service_prowlarr/lib/src/prowlarr_search_filters.dart new file mode 100644 index 00000000..5541c4fc --- /dev/null +++ b/services/service_prowlarr/lib/src/prowlarr_search_filters.dart @@ -0,0 +1,528 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/foundation.dart' show setEquals; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'models/prowlarr_category.dart'; +import 'models/prowlarr_indexer.dart'; +import 'prowlarr_providers.dart'; + +/// Prowlarr's ids for "every usenet indexer" and "every torrent indexer". +/// Sent as indexer ids, they cover indexers added later too. +const int prowlarrAllUsenet = -1; +const int prowlarrAllTorrents = -2; + +/// Prowlarr's search types. A typed search reads `{Key:Value}` parameters +/// such as `{ImdbId:tt0111161}` out of the query; a basic one does not. +enum ProwlarrSearchType { + basic('search', 'Basic', []), + tv('tvsearch', 'TV', [ + 'ImdbId', + 'TvdbId', + 'TmdbId', + 'TvMazeId', + 'Season', + 'Episode', + 'Year', + ]), + movie('movie', 'Movie', ['ImdbId', 'TmdbId', 'TraktId', 'Year']), + audio('music', 'Audio', ['Artist', 'Album', 'Label', 'Year']), + book('book', 'Book', ['Author', 'Title', 'Publisher', 'Year']); + + const ProwlarrSearchType(this.apiValue, this.label, this.tokens); + + /// The `type` sent to `/api/v1/search`. + final String apiValue; + final String label; + + /// The parameters Prowlarr reads for this type. + final List tokens; +} + +/// What a search is narrowed to. Empty means all, as in Prowlarr. +@immutable +class ProwlarrSearchFilter { + const ProwlarrSearchFilter({ + this.type = ProwlarrSearchType.basic, + this.indexerIds = const {}, + this.categories = const {}, + }); + + final ProwlarrSearchType type; + final Set indexerIds; + final Set categories; + + bool get isEmpty => + type == ProwlarrSearchType.basic && + indexerIds.isEmpty && + categories.isEmpty; + + /// How many things are picked, for the filter button's badge. + int get count => + (type == ProwlarrSearchType.basic ? 0 : 1) + + indexerIds.length + + categories.length; + + ProwlarrSearchFilter copyWith({ + ProwlarrSearchType? type, + Set? indexerIds, + Set? categories, + }) => + ProwlarrSearchFilter( + type: type ?? this.type, + indexerIds: indexerIds ?? this.indexerIds, + categories: categories ?? this.categories, + ); + + @override + bool operator ==(Object other) => + other is ProwlarrSearchFilter && + other.type == type && + setEquals(other.indexerIds, indexerIds) && + setEquals(other.categories, categories); + + @override + int get hashCode => Object.hash( + type, + Object.hashAllUnordered(indexerIds), + Object.hashAllUnordered(categories), + ); +} + +/// The search field's hint: what a search with [filter] will reach. +String prowlarrSearchHint(ProwlarrSearchFilter filter) { + final String reach = _reach(filter.indexerIds); + return filter.type == ProwlarrSearchType.basic + ? 'Search $reach...' + : '${filter.type.label} search, $reach...'; +} + +/// Which indexers [ids] covers: "all torrents and 1 indexer". +String _reach(Set ids) { + final bool torrents = ids.contains(prowlarrAllTorrents); + final bool usenet = ids.contains(prowlarrAllUsenet); + final int others = ids + .where((int id) => id != prowlarrAllTorrents && id != prowlarrAllUsenet) + .length; + final String count = '$others ${others == 1 ? 'indexer' : 'indexers'}'; + if (ids.isEmpty || (torrents && usenet)) { + return 'all indexers'; + } + if (!torrents && !usenet) { + return count; + } + final String group = torrents ? 'all torrents' : 'all usenet'; + return others == 0 ? group : '$group and $count'; +} + +/// [value] with `{token:}` in place of its selection, or on the end when +/// it has none, and the cursor inside it ready for the value. +TextEditingValue prowlarrInsertToken(TextEditingValue value, String token) { + final String insert = '{$token:}'; + final TextSelection selection = value.selection; + final int start = selection.isValid ? selection.start : value.text.length; + final int end = selection.isValid ? selection.end : value.text.length; + return TextEditingValue( + text: value.text.replaceRange(start, end, insert), + selection: TextSelection.collapsed(offset: start + insert.length - 1), + ); +} + +/// The parameters a typed search reads, as chips under the search field. +/// Braces are fiddly on a phone keyboard; a tap puts one in. +class ProwlarrTokenChips extends StatelessWidget + implements PreferredSizeWidget { + const ProwlarrTokenChips({ + required this.type, + required this.onToken, + super.key, + }); + + final ProwlarrSearchType type; + final ValueChanged onToken; + + @override + Size get preferredSize => const Size.fromHeight(48); + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 48, + child: ListView.separated( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric( + horizontal: Insets.lg, + vertical: Insets.xs, + ), + itemCount: type.tokens.length, + separatorBuilder: (_, __) => const SizedBox(width: Insets.sm), + itemBuilder: (BuildContext context, int i) => ActionChip( + label: Text(type.tokens[i]), + onPressed: () => onToken(type.tokens[i]), + ), + ), + ); + } +} + +/// Indexers grouped by protocol, as on Prowlarr's search page. Ticking a +/// group searches every indexer of that protocol, and stands in for any of +/// them that were ticked one by one. +class ProwlarrIndexerPicker extends StatelessWidget { + const ProwlarrIndexerPicker({ + required this.indexers, + required this.selected, + required this.onChanged, + super.key, + }); + + final List indexers; + final Set selected; + final ValueChanged> onChanged; + + @override + Widget build(BuildContext context) { + final List rows = []; + for (final (String protocol, int groupId, String label) + in <(String, int, String)>[ + ('torrent', prowlarrAllTorrents, 'Torrents'), + ('usenet', prowlarrAllUsenet, 'Usenet'), + ]) { + final List group = indexers + .where((ProwlarrIndexer i) => i.protocol == protocol) + .toList(); + if (group.isEmpty) { + continue; + } + final bool groupOn = selected.contains(groupId); + rows.add( + CheckboxListTile( + value: groupOn, + title: Text( + label, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + subtitle: Text('Every $protocol indexer'), + onChanged: (bool? on) { + final Set next = Set.of(selected); + if (on ?? false) { + next + ..removeAll(group.map((ProwlarrIndexer i) => i.id)) + ..add(groupId); + } else { + next.remove(groupId); + } + onChanged(next); + }, + ), + ); + for (final ProwlarrIndexer i in group) { + rows.add( + CheckboxListTile( + contentPadding: + const EdgeInsets.only(left: Insets.xl, right: Insets.lg), + dense: true, + value: groupOn || selected.contains(i.id), + title: Text(i.name), + subtitle: i.enable ? null : const Text('Disabled'), + // A disabled indexer can't be picked, but one picked before it + // was disabled can still be let go of. + onChanged: groupOn || (!i.enable && !selected.contains(i.id)) + ? null + : (bool? on) => onChanged(_toggled(selected, i.id, on)), + ), + ); + } + } + if (rows.isEmpty) { + return const Padding( + padding: EdgeInsets.all(Insets.lg), + child: Text('No indexers set up in Prowlarr.'), + ); + } + return Column(mainAxisSize: MainAxisSize.min, children: rows); + } +} + +/// Prowlarr's category tree. Ticking a parent such as Movies covers all of +/// its subcategories, and stands in for any that were ticked one by one. +class ProwlarrCategoryPicker extends StatelessWidget { + const ProwlarrCategoryPicker({ + required this.categories, + required this.selected, + required this.onChanged, + super.key, + }); + + final List categories; + final Set selected; + final ValueChanged> onChanged; + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final ProwlarrCategory parent in categories) + ExpansionTile( + key: PageStorageKey(parent.id), + initiallyExpanded: parent.subCategories + .any((ProwlarrCategory s) => selected.contains(s.id)), + leading: Checkbox( + value: selected.contains(parent.id), + onChanged: (bool? on) { + final Set next = Set.of(selected); + if (on ?? false) { + next + ..removeAll( + parent.subCategories.map((ProwlarrCategory s) => s.id), + ) + ..add(parent.id); + } else { + next.remove(parent.id); + } + onChanged(next); + }, + ), + title: Text(parent.name), + children: [ + for (final ProwlarrCategory sub in parent.subCategories) + CheckboxListTile( + contentPadding: const EdgeInsets.only( + left: Insets.xl * 2, + right: Insets.lg, + ), + dense: true, + value: selected.contains(parent.id) || + selected.contains(sub.id), + title: Text(sub.shortName), + onChanged: selected.contains(parent.id) + ? null + : (bool? on) => onChanged(_toggled(selected, sub.id, on)), + ), + ], + ), + ], + ); + } +} + +Set _toggled(Set selected, int id, bool? on) { + final Set next = Set.of(selected); + (on ?? false) ? next.add(id) : next.remove(id); + return next; +} + +/// The search screen's filter button: a badge with how many things are +/// picked, opening one sheet with the indexer and category pickers. +class ProwlarrFilterButton extends StatelessWidget { + const ProwlarrFilterButton({ + required this.instance, + required this.filter, + this.onClosed, + super.key, + }); + + final Instance instance; + final ValueNotifier filter; + + /// Called once each time the sheet is dismissed, however it was closed. + final VoidCallback? onClosed; + + Future _open(BuildContext context) async { + // With nothing focused, closing the sheet has no focus to give back, + // so the keyboard stays down. + FocusManager.instance.primaryFocus?.unfocus(); + await showModalBottomSheet( + context: context, + useRootNavigator: true, + isScrollControlled: true, + showDragHandle: true, + builder: (BuildContext sheet) => + _FilterSheet(instance: instance, filter: filter), + ); + onClosed?.call(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: filter, + builder: (BuildContext context, ProwlarrSearchFilter value, _) => + IconButton( + tooltip: 'Filters', + icon: Badge( + isLabelVisible: value.count > 0, + label: Text('${value.count}'), + child: const Icon(Icons.tune), + ), + onPressed: () => _open(context), + ), + ); + } +} + +class _FilterSheet extends ConsumerWidget { + const _FilterSheet({required this.instance, required this.filter}); + + final Instance instance; + final ValueNotifier filter; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final AsyncValue> indexers = + ref.watch(prowlarrIndexersProvider(instance)); + final AsyncValue> categories = + ref.watch(prowlarrCategoriesProvider(instance)); + return DraggableScrollableSheet( + expand: false, + initialChildSize: 0.7, + maxChildSize: 0.92, + builder: (BuildContext context, ScrollController scroll) => + ValueListenableBuilder( + valueListenable: filter, + builder: (BuildContext context, ProwlarrSearchFilter value, _) => + Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB( + Insets.lg, + 0, + Insets.sm, + Insets.sm, + ), + child: Row( + children: [ + Expanded( + child: Text( + 'Search filters', + style: Theme.of(context).textTheme.titleMedium, + ), + ), + TextButton( + onPressed: () => + filter.value = const ProwlarrSearchFilter(), + child: const Text('Clear'), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Done'), + ), + ], + ), + ), + const Divider(height: 1), + Expanded( + child: SingleChildScrollView( + controller: scroll, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const _SectionHeader('Search type'), + Padding( + padding: + const EdgeInsets.symmetric(horizontal: Insets.lg), + child: Wrap( + spacing: Insets.sm, + runSpacing: Insets.xs, + children: [ + for (final ProwlarrSearchType t + in ProwlarrSearchType.values) + ChoiceChip( + label: Text(t.label), + selected: value.type == t, + onSelected: (_) => + filter.value = value.copyWith(type: t), + ), + ], + ), + ), + const Divider(), + const _SectionHeader('Indexers'), + _loaded( + indexers, + what: 'indexers', + onRetry: () => + ref.invalidate(prowlarrIndexersProvider(instance)), + data: (List list) => + ProwlarrIndexerPicker( + indexers: list, + selected: value.indexerIds, + onChanged: (Set ids) => + filter.value = value.copyWith(indexerIds: ids), + ), + ), + const Divider(), + const _SectionHeader('Categories'), + _loaded( + categories, + what: 'categories', + onRetry: () => + ref.invalidate(prowlarrCategoriesProvider(instance)), + data: (List list) => + ProwlarrCategoryPicker( + categories: list, + selected: value.categories, + onChanged: (Set ids) => + filter.value = value.copyWith(categories: ids), + ), + ), + const SizedBox(height: Insets.xl), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +/// [data] once [value] has loaded; a spinner before, and a retry after a +/// failure, so one section failing leaves the other usable. +Widget _loaded( + AsyncValue value, { + required String what, + required VoidCallback onRetry, + required Widget Function(T data) data, +}) => + value.when( + data: data, + loading: () => const Padding( + padding: EdgeInsets.all(Insets.xl), + child: Center(child: ExpressiveProgressIndicator()), + ), + error: (Object e, _) => Padding( + padding: const EdgeInsets.symmetric(horizontal: Insets.lg), + child: Row( + children: [ + Expanded(child: Text('Could not load $what')), + TextButton(onPressed: onRetry, child: const Text('Retry')), + ], + ), + ), + ); + +class _SectionHeader extends StatelessWidget { + const _SectionHeader(this.text); + + final String text; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.fromLTRB( + Insets.lg, + Insets.md, + Insets.lg, + Insets.xs, + ), + child: Text( + text, + style: Theme.of(context).textTheme.labelLarge?.copyWith( + color: Theme.of(context).colorScheme.primary, + ), + ), + ); +} diff --git a/services/service_prowlarr/lib/src/prowlarr_search_screen.dart b/services/service_prowlarr/lib/src/prowlarr_search_screen.dart index b22f5f87..e4e2d93c 100644 --- a/services/service_prowlarr/lib/src/prowlarr_search_screen.dart +++ b/services/service_prowlarr/lib/src/prowlarr_search_screen.dart @@ -2,16 +2,19 @@ import 'package:core_models/core_models.dart'; import 'package:core_networking/core_networking.dart'; import 'package:core_ui/core_ui.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'models/prowlarr_release.dart'; import 'prowlarr_api.dart'; import 'prowlarr_providers.dart'; +import 'prowlarr_search_filters.dart'; /// Sort orders for search results. enum _SortBy { seeders, size, age } -/// Manual search across all of an instance's indexers, with grab-to-client. +/// Manual search across an instance's indexers, with grab-to-client. The +/// filter button narrows it to some indexers and categories. /// /// Search is submit-driven (not debounced): one query fans out to every /// enabled indexer and can take tens of seconds, so firing on every @@ -28,13 +31,41 @@ class ProwlarrSearchScreen extends ConsumerStatefulWidget { class _ProwlarrSearchScreenState extends ConsumerState { final TextEditingController _controller = TextEditingController(); + final FocusNode _field = FocusNode(); + + // The chip row coming and going rebuilds the app bar's layout. The key + // moves the field instead of rebuilding it, so autofocus doesn't fire + // again and pull the keyboard up behind the filter sheet. + final GlobalKey _fieldKey = GlobalKey(); List? _results; bool _searching = false; String? _error; _SortBy _sortBy = _SortBy.seeders; + final ValueNotifier _filter = + ValueNotifier(const ProwlarrSearchFilter()); + + /// The query and filter last searched with: what the results on screen + /// are for. + String? _lastQuery; + ProwlarrSearchFilter? _lastFilter; + + /// Bumped per search, so an answer to an older one is dropped. + int _generation = 0; + + @override + void initState() { + super.initState(); + _filter.addListener(_onFilter); + } + + // The hint follows the filter. + void _onFilter() => setState(() {}); @override void dispose() { + _filter.removeListener(_onFilter); + _filter.dispose(); + _field.dispose(); _controller.dispose(); super.dispose(); } @@ -44,6 +75,10 @@ class _ProwlarrSearchScreenState extends ConsumerState { if (term.length < 2) { return; } + final ProwlarrSearchFilter filter = _filter.value; + _lastQuery = term; + _lastFilter = filter; + final int generation = ++_generation; setState(() { _searching = true; _error = null; @@ -51,8 +86,13 @@ class _ProwlarrSearchScreenState extends ConsumerState { try { final ProwlarrApi api = await ref.read(prowlarrApiProvider(widget.instance).future); - final List releases = await api.search(term); - if (!mounted) { + final List releases = await api.search( + term, + indexerIds: filter.indexerIds.toList(), + categories: filter.categories.toList(), + type: filter.type.apiValue, + ); + if (!mounted || generation != _generation) { return; } setState(() { @@ -60,7 +100,7 @@ class _ProwlarrSearchScreenState extends ConsumerState { _searching = false; }); } on Object catch (e) { - if (!mounted) { + if (!mounted || generation != _generation) { return; } setState(() { @@ -70,6 +110,15 @@ class _ProwlarrSearchScreenState extends ConsumerState { } } + /// After the filter sheet closes: search again if a search has been made + /// and the filter is no longer the one it used. + void _onFiltersClosed() { + final String? query = _lastQuery; + if (query != null && _filter.value != _lastFilter) { + _search(query); + } + } + List _sorted(List list) { final List out = List.of(list); switch (_sortBy) { @@ -96,16 +145,40 @@ class _ProwlarrSearchScreenState extends ConsumerState { return Scaffold( appBar: AppBar( title: TextField( + key: _fieldKey, controller: _controller, + focusNode: _field, autofocus: true, textInputAction: TextInputAction.search, - decoration: const InputDecoration( - hintText: 'Search all indexers...', + decoration: InputDecoration( + hintText: prowlarrSearchHint(_filter.value), border: InputBorder.none, ), onSubmitted: _search, ), + bottom: _filter.value.type == ProwlarrSearchType.basic + ? null + : ProwlarrTokenChips( + type: _filter.value.type, + onToken: (String token) { + _controller.value = + prowlarrInsertToken(_controller.value, token); + if (_field.hasFocus) { + // Back hides the keyboard but leaves the focus, so + // asking for focus again would not bring it back. + SystemChannels.textInput + .invokeMethod('TextInput.show'); + } else { + _field.requestFocus(); + } + }, + ), actions: [ + ProwlarrFilterButton( + instance: widget.instance, + filter: _filter, + onClosed: _onFiltersClosed, + ), PopupMenuButton<_SortBy>( tooltip: 'Sort', icon: const Icon(Icons.sort), @@ -154,7 +227,7 @@ class _ProwlarrSearchScreenState extends ConsumerState { return ErrorView( title: 'Search failed', message: _error!, - onRetry: () => _search(_controller.text), + onRetry: () => _search(_lastQuery ?? _controller.text), ); } final List? results = _results; diff --git a/services/service_prowlarr/test/prowlarr_filter_button_test.dart b/services/service_prowlarr/test/prowlarr_filter_button_test.dart new file mode 100644 index 00000000..dfbacb07 --- /dev/null +++ b/services/service_prowlarr/test/prowlarr_filter_button_test.dart @@ -0,0 +1,177 @@ +import 'package:core_networking/core_networking.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_prowlarr/service_prowlarr.dart'; + +import 'support/fake_prowlarr.dart'; +import 'support/prowlarr_test_instance.dart'; + +void main() { + late FakeProwlarr server; + late ValueNotifier filter; + late FocusNode field; + late int closed; + + setUp(() { + server = FakeProwlarr(); + filter = ValueNotifier(const ProwlarrSearchFilter()); + field = FocusNode(); + closed = 0; + }); + + tearDown(() { + filter.dispose(); + field.dispose(); + }); + + Future pump(WidgetTester tester) => tester.pumpWidget( + ProviderScope( + overrides: [ + instanceDioProvider(prowlarrTestInstance) + .overrideWith((Ref ref) async => dioFor(server)), + ], + child: MaterialApp( + home: Scaffold( + appBar: AppBar( + title: TextField(focusNode: field), + actions: [ + ProwlarrFilterButton( + instance: prowlarrTestInstance, + filter: filter, + onClosed: () => closed++, + ), + ], + ), + ), + ), + ), + ); + + Future open(WidgetTester tester) async { + await tester.tap(find.byTooltip('Filters')); + await tester.pumpAndSettle(); + } + + testWidgets('badge shows the filter count and hides at zero', + (WidgetTester tester) async { + await pump(tester); + expect(tester.widget(find.byType(Badge)).isLabelVisible, isFalse); + filter.value = const ProwlarrSearchFilter( + indexerIds: {prowlarrAllTorrents}, + categories: {2000}, + ); + await tester.pump(); + expect(tester.widget(find.byType(Badge)).isLabelVisible, isTrue); + expect( + find.descendant(of: find.byType(Badge), matching: find.text('2')), + findsOneWidget, + ); + }); + + testWidgets('the sheet has both sections and Done closes it', + (WidgetTester tester) async { + await pump(tester); + await open(tester); + expect(find.text('Search filters'), findsOneWidget); + expect(find.text('Indexers'), findsOneWidget); + expect(find.text('Categories'), findsOneWidget); + expect(closed, 0); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + expect(find.text('Search filters'), findsNothing); + expect(closed, 1); + }); + + testWidgets('Clear empties the filter', (WidgetTester tester) async { + filter.value = const ProwlarrSearchFilter( + indexerIds: {prowlarrAllTorrents}, + categories: {2000}, + ); + await pump(tester); + await open(tester); + await tester.tap(find.text('Clear')); + await tester.pump(); + expect(filter.value.isEmpty, isTrue); + }); + + testWidgets('closing the sheet leaves the search field unfocused', + (WidgetTester tester) async { + await pump(tester); + field.requestFocus(); + await tester.pump(); + expect(field.hasFocus, isTrue); + await open(tester); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + expect(field.hasFocus, isFalse); + }); + + testWidgets('a failed category load keeps indexers and offers retry', + (WidgetTester tester) async { + server.fail('GET', 'api/v1/indexer/categories', 500); + await pump(tester); + await open(tester); + expect(find.text('Example Public Tracker'), findsOneWidget); + expect(find.text('Could not load categories'), findsOneWidget); + server.mend('GET', 'api/v1/indexer/categories'); + await tester.ensureVisible(find.text('Retry')); + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(find.text('Could not load categories'), findsNothing); + expect(find.text('Movies'), findsOneWidget); + }); + + testWidgets('categories are fetched once, not on every open', + (WidgetTester tester) async { + await pump(tester); + await open(tester); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + await open(tester); + expect(server.to('GET', 'api/v1/indexer/categories'), hasLength(1)); + }); + + testWidgets('Search type comes first with Basic picked', + (WidgetTester tester) async { + await pump(tester); + await open(tester); + expect( + tester.getTopLeft(find.text('Search type')).dy, + lessThan(tester.getTopLeft(find.text('Indexers')).dy), + ); + expect( + tester.widget(find.widgetWithText(ChoiceChip, 'Basic')) + .selected, + isTrue, + ); + }); + + testWidgets('picking Movie sets the type and the badge', + (WidgetTester tester) async { + await pump(tester); + await open(tester); + await tester.tap(find.widgetWithText(ChoiceChip, 'Movie')); + await tester.pump(); + expect(filter.value.type, ProwlarrSearchType.movie); + expect( + tester.widget(find.widgetWithText(ChoiceChip, 'Movie')) + .selected, + isTrue, + ); + expect( + find.descendant(of: find.byType(Badge), matching: find.text('1')), + findsOneWidget, + ); + }); + + testWidgets('Clear resets the type', (WidgetTester tester) async { + filter.value = const ProwlarrSearchFilter(type: ProwlarrSearchType.movie); + await pump(tester); + await open(tester); + await tester.tap(find.text('Clear')); + await tester.pump(); + expect(filter.value.type, ProwlarrSearchType.basic); + }); +} diff --git a/services/service_prowlarr/test/prowlarr_search_api_test.dart b/services/service_prowlarr/test/prowlarr_search_api_test.dart new file mode 100644 index 00000000..ce223863 --- /dev/null +++ b/services/service_prowlarr/test/prowlarr_search_api_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_prowlarr/service_prowlarr.dart'; + +import 'support/fake_prowlarr.dart'; + +void main() { + late FakeProwlarr server; + + setUp(() => server = FakeProwlarr()); + + test('getCategories reads the parent and subcategory tree', () async { + final List tree = + await ProwlarrApi(dioFor(server)).getCategories(); + expect(tree.map((ProwlarrCategory c) => c.id), [2000, 5000]); + expect( + tree.first.subCategories.map((ProwlarrCategory c) => c.id), + [2040, 2045], + ); + expect(tree.first.subCategories.first.shortName, 'HD'); + }); + + test('search sends each indexer and category as its own parameter', + () async { + await ProwlarrApi(dioFor(server)) + .search('dune', indexerIds: [-2, 5], categories: [2000]); + final Uri uri = server.requests.last.uri; + expect(uri.queryParametersAll['indexerIds'], ['-2', '5']); + expect(uri.queryParametersAll['categories'], ['2000']); + }); + + test('search with no filter sends neither parameter', () async { + await ProwlarrApi(dioFor(server)).search('dune'); + final Uri uri = server.requests.last.uri; + expect(uri.queryParameters.containsKey('indexerIds'), isFalse); + expect(uri.queryParameters.containsKey('categories'), isFalse); + }); + + test('search sends the type, basic by default', () async { + final ProwlarrApi api = ProwlarrApi(dioFor(server)); + await api.search('dune'); + expect(server.requests.last.uri.queryParameters['type'], 'search'); + await api.search('dune', type: 'movie'); + expect(server.requests.last.uri.queryParameters['type'], 'movie'); + }); +} diff --git a/services/service_prowlarr/test/prowlarr_search_filter_test.dart b/services/service_prowlarr/test/prowlarr_search_filter_test.dart new file mode 100644 index 00000000..1c071d5f --- /dev/null +++ b/services/service_prowlarr/test/prowlarr_search_filter_test.dart @@ -0,0 +1,151 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_prowlarr/service_prowlarr.dart'; + +void main() { + test('hint follows the indexer filter', () { + String hint(Set ids) => + prowlarrSearchHint(ProwlarrSearchFilter(indexerIds: ids)); + expect(hint({}), 'Search all indexers...'); + expect(hint({prowlarrAllTorrents}), 'Search all torrents...'); + expect(hint({prowlarrAllUsenet}), 'Search all usenet...'); + expect( + hint({prowlarrAllTorrents, prowlarrAllUsenet}), + 'Search all indexers...', + ); + expect(hint({1}), 'Search 1 indexer...'); + expect(hint({1, 5}), 'Search 2 indexers...'); + expect( + hint({prowlarrAllTorrents, 5}), + 'Search all torrents and 1 indexer...', + ); + }); + + test('categories alone leave the hint at all indexers', () { + expect( + prowlarrSearchHint( + const ProwlarrSearchFilter(categories: {2000}), + ), + 'Search all indexers...', + ); + }); + + test('filters with the same sets are equal', () { + expect( + const ProwlarrSearchFilter(indexerIds: {1, 2}), + const ProwlarrSearchFilter(indexerIds: {2, 1}), + ); + expect( + const ProwlarrSearchFilter(indexerIds: {1}) == + const ProwlarrSearchFilter(), + isFalse, + ); + }); + + test('count is indexers plus categories', () { + expect( + const ProwlarrSearchFilter( + indexerIds: {prowlarrAllTorrents}, + categories: {2000, 5040}, + ).count, + 3, + ); + }); + + test('hint names a typed search', () { + expect( + prowlarrSearchHint( + const ProwlarrSearchFilter(type: ProwlarrSearchType.movie), + ), + 'Movie search, all indexers...', + ); + expect( + prowlarrSearchHint( + const ProwlarrSearchFilter( + type: ProwlarrSearchType.tv, + indexerIds: {prowlarrAllTorrents}, + ), + ), + 'TV search, all torrents...', + ); + expect( + prowlarrSearchHint( + const ProwlarrSearchFilter( + type: ProwlarrSearchType.book, + indexerIds: {1, 5}, + ), + ), + 'Book search, 2 indexers...', + ); + }); + + test('a non-basic type counts once', () { + expect( + const ProwlarrSearchFilter( + type: ProwlarrSearchType.movie, + categories: {2000}, + ).count, + 2, + ); + expect( + const ProwlarrSearchFilter(type: ProwlarrSearchType.movie).isEmpty, + isFalse, + ); + }); + + test('type is part of equality', () { + expect( + const ProwlarrSearchFilter(type: ProwlarrSearchType.movie) == + const ProwlarrSearchFilter(), + isFalse, + ); + }); + + test('tokens per type', () { + expect(ProwlarrSearchType.basic.tokens, isEmpty); + expect(ProwlarrSearchType.tv.tokens, [ + 'ImdbId', + 'TvdbId', + 'TmdbId', + 'TvMazeId', + 'Season', + 'Episode', + 'Year', + ]); + expect( + ProwlarrSearchType.movie.tokens, + ['ImdbId', 'TmdbId', 'TraktId', 'Year'], + ); + expect( + ProwlarrSearchType.audio.tokens, + ['Artist', 'Album', 'Label', 'Year'], + ); + expect( + ProwlarrSearchType.book.tokens, + ['Author', 'Title', 'Publisher', 'Year'], + ); + expect( + ProwlarrSearchType.values.map((ProwlarrSearchType t) => t.apiValue), + ['search', 'tvsearch', 'movie', 'music', 'book'], + ); + }); + + test('insert appends with no selection', () { + final TextEditingValue out = + prowlarrInsertToken(const TextEditingValue(text: 'dune'), 'ImdbId'); + expect(out.text, 'dune{ImdbId:}'); + expect(out.selection, const TextSelection.collapsed(offset: 12)); + }); + + test('insert replaces the selection', () { + final TextEditingValue out = prowlarrInsertToken( + const TextEditingValue( + text: 'ab', + selection: TextSelection(baseOffset: 1, extentOffset: 2), + ), + 'Year', + ); + expect(out.text, 'a{Year:}'); + expect(out.selection, const TextSelection.collapsed(offset: 7)); + }); +} diff --git a/services/service_prowlarr/test/prowlarr_search_pickers_test.dart b/services/service_prowlarr/test/prowlarr_search_pickers_test.dart new file mode 100644 index 00000000..3cef7d94 --- /dev/null +++ b/services/service_prowlarr/test/prowlarr_search_pickers_test.dart @@ -0,0 +1,175 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_prowlarr/service_prowlarr.dart'; + +const List _indexers = [ + ProwlarrIndexer( + id: 1, + name: 'Example Public Tracker', + enable: true, + protocol: 'torrent', + ), + ProwlarrIndexer( + id: 2, + name: 'Example Private Tracker', + enable: true, + protocol: 'torrent', + ), + ProwlarrIndexer(id: 4, name: 'Old Tracker', protocol: 'torrent'), + ProwlarrIndexer( + id: 5, + name: 'Example Usenet Indexer', + enable: true, + protocol: 'usenet', + ), +]; + +const List _tree = [ + ProwlarrCategory( + id: 2000, + name: 'Movies', + subCategories: [ + ProwlarrCategory(id: 2040, name: 'Movies/HD'), + ProwlarrCategory(id: 2045, name: 'Movies/UHD'), + ], + ), + ProwlarrCategory( + id: 5000, + name: 'TV', + subCategories: [ + ProwlarrCategory(id: 5040, name: 'TV/HD'), + ], + ), +]; + +Future _pump(WidgetTester tester, Widget picker) => tester.pumpWidget( + MaterialApp( + home: Scaffold(body: SingleChildScrollView(child: picker)), + ), + ); + +CheckboxListTile _tile(WidgetTester tester, String title) => + tester.widget( + find.widgetWithText(CheckboxListTile, title), + ); + +void main() { + testWidgets('ticking Torrents replaces ticked torrent indexers', + (WidgetTester tester) async { + Set? reported; + await _pump( + tester, + ProwlarrIndexerPicker( + indexers: _indexers, + selected: const {1, 5}, + onChanged: (Set s) => reported = s, + ), + ); + await tester.tap(find.text('Torrents')); + expect(reported, {prowlarrAllTorrents, 5}); + }); + + testWidgets('a ticked group checks and locks its members', + (WidgetTester tester) async { + await _pump( + tester, + ProwlarrIndexerPicker( + indexers: _indexers, + selected: const {prowlarrAllTorrents}, + onChanged: (_) {}, + ), + ); + final CheckboxListTile member = _tile(tester, 'Example Public Tracker'); + expect(member.value, isTrue); + expect(member.onChanged, isNull); + expect(_tile(tester, 'Example Usenet Indexer').onChanged, isNotNull); + }); + + testWidgets('disabled indexers show Disabled and cannot be ticked', + (WidgetTester tester) async { + await _pump( + tester, + ProwlarrIndexerPicker( + indexers: _indexers, + selected: const {}, + onChanged: (_) {}, + ), + ); + expect( + find.descendant( + of: find.widgetWithText(CheckboxListTile, 'Old Tracker'), + matching: find.text('Disabled'), + ), + findsOneWidget, + ); + expect(_tile(tester, 'Old Tracker').onChanged, isNull); + }); + + testWidgets('a protocol with no indexers has no group row', + (WidgetTester tester) async { + await _pump( + tester, + ProwlarrIndexerPicker( + indexers: _indexers.where((ProwlarrIndexer i) => i.id != 5).toList(), + selected: const {}, + onChanged: (_) {}, + ), + ); + expect(find.text('Torrents'), findsOneWidget); + expect(find.text('Usenet'), findsNothing); + }); + + testWidgets('ticking a parent category replaces its ticked subs', + (WidgetTester tester) async { + Set? reported; + await _pump( + tester, + ProwlarrCategoryPicker( + categories: _tree, + selected: const {2040, 5040}, + onChanged: (Set s) => reported = s, + ), + ); + await tester.tap( + find + .descendant( + of: find.widgetWithText(ExpansionTile, 'Movies'), + matching: find.byType(Checkbox), + ) + .first, + ); + expect(reported, {2000, 5040}); + }); + + testWidgets('a ticked parent checks and locks its subs', + (WidgetTester tester) async { + await _pump( + tester, + ProwlarrCategoryPicker( + categories: _tree, + selected: const {2000}, + onChanged: (_) {}, + ), + ); + await tester.tap(find.text('Movies')); + await tester.pumpAndSettle(); + final CheckboxListTile sub = _tile(tester, 'HD'); + expect(sub.value, isTrue); + expect(sub.onChanged, isNull); + }); + + testWidgets('a ticked indexer that became disabled can still be unticked', + (WidgetTester tester) async { + Set? reported; + await _pump( + tester, + ProwlarrIndexerPicker( + indexers: _indexers, + selected: const {4}, + onChanged: (Set s) => reported = s, + ), + ); + await tester.tap(find.text('Old Tracker')); + expect(reported, {}); + }); +} diff --git a/services/service_prowlarr/test/prowlarr_search_screen_test.dart b/services/service_prowlarr/test/prowlarr_search_screen_test.dart new file mode 100644 index 00000000..c6804abd --- /dev/null +++ b/services/service_prowlarr/test/prowlarr_search_screen_test.dart @@ -0,0 +1,279 @@ +import 'dart:async'; + +import 'package:core_networking/core_networking.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_prowlarr/service_prowlarr.dart'; + +import 'support/fake_prowlarr.dart'; +import 'support/prowlarr_test_instance.dart'; + +void main() { + late FakeProwlarr server; + + setUp(() => server = FakeProwlarr()); + + List searches() => server.to('GET', 'api/v1/search'); + + Future pump(WidgetTester tester) => tester.pumpWidget( + ProviderScope( + overrides: [ + instanceDioProvider(prowlarrTestInstance) + .overrideWith((Ref ref) async => dioFor(server)), + ], + child: const MaterialApp( + home: ProwlarrSearchScreen(instance: prowlarrTestInstance), + ), + ), + ); + + /// Lets animations and requests run without waiting for the search + /// spinner, which never settles. + Future run(WidgetTester tester) async { + for (int i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + } + + Future submit(WidgetTester tester, String query) async { + await tester.enterText(find.byType(TextField), query); + await tester.testTextInput.receiveAction(TextInputAction.search); + await run(tester); + } + + /// Opens the filters, taps each of [labels], and presses Done. + Future pick(WidgetTester tester, List labels) async { + await tester.tap(find.byTooltip('Filters')); + await run(tester); + for (final String label in labels) { + final Finder parent = find.widgetWithText(ExpansionTile, label); + final Finder target = parent.evaluate().isEmpty + ? find.text(label) + : find + .descendant(of: parent, matching: find.byType(Checkbox)) + .first; + await tester.ensureVisible(target); + await tester.tap(target); + await tester.pump(); + } + await tester.tap(find.text('Done')); + await run(tester); + } + + /// Opens the filters, picks the search type [label], and presses Done. + Future pickType(WidgetTester tester, String label) async { + await tester.tap(find.byTooltip('Filters')); + await run(tester); + await tester.tap(find.widgetWithText(ChoiceChip, label)); + await tester.pump(); + await tester.tap(find.text('Done')); + await run(tester); + } + + testWidgets('the search sends the chosen filter', + (WidgetTester tester) async { + await pump(tester); + await pick(tester, ['Torrents', 'Movies']); + await submit(tester, 'dune'); + final Uri uri = searches().last.uri; + expect(uri.queryParametersAll['indexerIds'], ['-2']); + expect(uri.queryParametersAll['categories'], ['2000']); + }); + + testWidgets('the hint follows the filter', (WidgetTester tester) async { + await pump(tester); + expect(find.text('Search all indexers...'), findsOneWidget); + await pick(tester, ['Torrents']); + expect(find.text('Search all torrents...'), findsOneWidget); + }); + + testWidgets('changing the filter re-runs the search on screen once', + (WidgetTester tester) async { + await pump(tester); + await submit(tester, 'dune'); + expect(searches(), hasLength(1)); + await pick(tester, ['Torrents', 'Usenet', 'Movies']); + expect(searches(), hasLength(2)); + final Uri uri = searches().last.uri; + expect(uri.queryParametersAll['indexerIds'], ['-2', '-1']); + expect(uri.queryParametersAll['categories'], ['2000']); + }); + + testWidgets('closing the sheet unchanged does not search again', + (WidgetTester tester) async { + await pump(tester); + await submit(tester, 'dune'); + await pick(tester, []); + expect(searches(), hasLength(1)); + }); + + testWidgets('no re-run before the first search', + (WidgetTester tester) async { + await pump(tester); + await pick(tester, ['Torrents']); + expect(searches(), isEmpty); + }); + + testWidgets('the re-run uses the searched query, not edited text', + (WidgetTester tester) async { + await pump(tester); + await submit(tester, 'dune'); + await tester.enterText(find.byType(TextField), 'arrival'); + await pick(tester, ['Torrents']); + expect(searches(), hasLength(2)); + expect(searches().last.uri.queryParameters['query'], 'dune'); + }); + + testWidgets('an older search answer does not replace a newer one', + (WidgetTester tester) async { + final Completer first = Completer(); + int calls = 0; + server.onCall('GET', 'api/v1/search', (RequestOptions _) async { + calls++; + if (calls == 1) { + await first.future; + return [releaseJson('Old answer')]; + } + return [releaseJson('New answer')]; + }); + await pump(tester); + await submit(tester, 'dune'); + await pick(tester, ['Torrents']); + expect(find.text('New answer'), findsOneWidget); + first.complete(); + await run(tester); + expect(find.text('New answer'), findsOneWidget); + expect(find.text('Old answer'), findsNothing); + }); + + testWidgets('Retry searches the query that failed, not the field', + (WidgetTester tester) async { + server.fail('GET', 'api/v1/search', 500); + await pump(tester); + await submit(tester, 'dune'); + expect(find.text('Retry'), findsOneWidget); + await tester.enterText(find.byType(TextField), ''); + server.mend('GET', 'api/v1/search'); + await tester.tap(find.text('Retry')); + await run(tester); + expect(searches(), hasLength(2)); + expect(searches().last.uri.queryParameters['query'], 'dune'); + }); + + testWidgets('chips show for a typed search only', + (WidgetTester tester) async { + await pump(tester); + expect(find.byType(ActionChip), findsNothing); + await pickType(tester, 'Movie'); + expect(find.widgetWithText(ActionChip, 'ImdbId'), findsOneWidget); + expect(find.widgetWithText(ActionChip, 'TraktId'), findsOneWidget); + expect(find.widgetWithText(ActionChip, 'TvdbId'), findsNothing); + await pickType(tester, 'Basic'); + expect(find.byType(ActionChip), findsNothing); + }); + + testWidgets('a chip inserts its token and focuses the field', + (WidgetTester tester) async { + await pump(tester); + await pickType(tester, 'Movie'); + await tester.tap(find.widgetWithText(ActionChip, 'ImdbId')); + await tester.pump(); + final TextEditingController field = + tester.widget(find.byType(TextField)).controller!; + expect(field.text, '{ImdbId:}'); + expect(field.selection, const TextSelection.collapsed(offset: 8)); + expect( + tester.widget(find.byType(EditableText)).focusNode.hasFocus, + isTrue, + ); + }); + + testWidgets('switching back to Basic keeps typed tokens', + (WidgetTester tester) async { + await pump(tester); + await pickType(tester, 'TV'); + await tester.tap(find.widgetWithText(ActionChip, 'Season')); + await tester.pump(); + await pickType(tester, 'Basic'); + expect( + tester.widget(find.byType(TextField)).controller!.text, + '{Season:}', + ); + }); + + testWidgets('the search sends the type', (WidgetTester tester) async { + await pump(tester); + await pickType(tester, 'TV'); + await submit(tester, '{TvdbId:71663}'); + expect(searches().last.uri.queryParameters['type'], 'tvsearch'); + expect(searches().last.uri.queryParameters['query'], '{TvdbId:71663}'); + }); + + testWidgets('changing only the type re-runs the search', + (WidgetTester tester) async { + await pump(tester); + await submit(tester, 'dune'); + await pickType(tester, 'Movie'); + expect(searches(), hasLength(2)); + expect(searches().last.uri.queryParameters['type'], 'movie'); + }); + + testWidgets('the TV chip row scrolls instead of overflowing on a phone', + (WidgetTester tester) async { + tester.view.physicalSize = const Size(360, 780); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await pump(tester); + await pickType(tester, 'TV'); + expect(tester.takeException(), isNull); + expect(find.widgetWithText(ActionChip, 'Year').hitTestable(), findsNothing); + await tester.dragUntilVisible( + find.widgetWithText(ActionChip, 'Year'), + find.ancestor( + of: find.byType(ActionChip).first, + matching: find.byType(Scrollable), + ), + const Offset(-100, 0), + ); + await tester.ensureVisible(find.widgetWithText(ActionChip, 'Year')); + await tester.pumpAndSettle(); + expect( + find.widgetWithText(ActionChip, 'Year').hitTestable(), + findsOneWidget, + ); + }); + + testWidgets('picking a type in the sheet keeps the keyboard down', + (WidgetTester tester) async { + await pump(tester); + await tester.tap(find.byTooltip('Filters')); + await run(tester); + await tester.tap(find.widgetWithText(ChoiceChip, 'Movie')); + await run(tester); + final FocusNode field = + tester.widget(find.byType(EditableText)).focusNode; + expect(field.hasFocus, isFalse); + expect(tester.testTextInput.isVisible, isFalse); + await tester.tap(find.text('Done')); + await run(tester); + expect(field.hasFocus, isFalse); + expect(tester.testTextInput.isVisible, isFalse); + }); + + testWidgets('a chip brings back a keyboard that was put away', + (WidgetTester tester) async { + await pump(tester); + await pickType(tester, 'Movie'); + await tester.tap(find.byType(TextField)); + await tester.pump(); + await SystemChannels.textInput.invokeMethod('TextInput.hide'); + expect(tester.testTextInput.isVisible, isFalse); + await tester.tap(find.widgetWithText(ActionChip, 'ImdbId')); + await tester.pump(); + expect(tester.testTextInput.isVisible, isTrue); + }); +} diff --git a/services/service_prowlarr/test/support/fake_prowlarr.dart b/services/service_prowlarr/test/support/fake_prowlarr.dart new file mode 100644 index 00000000..b0770132 --- /dev/null +++ b/services/service_prowlarr/test/support/fake_prowlarr.dart @@ -0,0 +1,132 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; + +typedef FakeAnswer = FutureOr Function(RequestOptions request); + +/// Prowlarr's `api/v1` as far as the search tests need it. Requests are +/// matched on method and path. +class FakeProwlarr implements HttpClientAdapter { + FakeProwlarr() { + on('GET', 'api/v1/indexer', indexersJson()); + on('GET', 'api/v1/indexer/categories', categoriesJson()); + on('GET', 'api/v1/search', [releaseJson('Dune 1080p')]); + } + + /// Every request that reached the server, in order. + final List requests = []; + + final Map _answers = {}; + final Map _failures = {}; + + /// Answers [method] [path] with [json]. + void on(String method, String path, Object? json) => + _answers['$method $path'] = (RequestOptions _) => json; + + /// Answers [method] [path] from the request itself. + void onCall(String method, String path, FakeAnswer answer) => + _answers['$method $path'] = answer; + + /// Answers [method] [path] with a bare [status]. + void fail(String method, String path, int status) => + _failures['$method $path'] = status; + + /// Answers [method] [path] as before it was made to [fail]. + void mend(String method, String path) => _failures.remove('$method $path'); + + List to(String method, String path) => [ + for (final RequestOptions request in requests) + if (request.method == method && request.path == path) request, + ]; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + requests.add(options); + final String key = '${options.method} ${options.path}'; + final int? failure = _failures[key]; + if (failure != null) { + return ResponseBody.fromString('', failure); + } + final FakeAnswer? answer = _answers[key]; + if (answer == null) { + return ResponseBody.fromString('', 404); + } + final Object? json = await answer(options); + return ResponseBody.fromString( + jsonEncode(json), + 200, + headers: >{ + Headers.contentTypeHeader: [Headers.jsonContentType], + }, + ); + } + + @override + void close({bool force = false}) {} +} + +/// A Dio that talks to [server]. +Dio dioFor(FakeProwlarr server) => + Dio(BaseOptions(baseUrl: 'http://prowlarr.test/')) + ..httpClientAdapter = server; + +List indexersJson() => [ + _indexer(1, 'Example Public Tracker', 'torrent'), + _indexer(2, 'Example Private Tracker', 'torrent'), + _indexer(4, 'Old Tracker', 'torrent', enable: false), + _indexer(5, 'Example Usenet Indexer', 'usenet'), + ]; + +Map _indexer( + int id, + String name, + String protocol, { + bool enable = true, +}) => + { + 'id': id, + 'name': name, + 'enable': enable, + 'protocol': protocol, + 'privacy': 'public', + 'priority': 25, + 'tags': [], + }; + +List categoriesJson() => [ + _category(2000, 'Movies', [ + _category(2040, 'Movies/HD'), + _category(2045, 'Movies/UHD'), + ]), + _category(5000, 'TV', [_category(5040, 'TV/HD')]), + ]; + +Map _category( + int id, + String name, [ + List subs = const [], +]) => + {'id': id, 'name': name, 'subCategories': subs}; + +Map releaseJson(String title) => { + 'guid': 'fake-$title', + 'indexerId': 1, + 'indexer': 'Example Public Tracker', + 'title': title, + 'size': 1500000000, + 'seeders': 50, + 'leechers': 1, + 'age': 0, + 'ageHours': 0.0, + 'protocol': 'torrent', + 'categories': [ + {'id': 2040, 'name': 'Movies/HD'}, + ], + 'publishDate': '2026-11-20T10:00:00Z', + }; diff --git a/services/service_prowlarr/test/support/prowlarr_test_instance.dart b/services/service_prowlarr/test/support/prowlarr_test_instance.dart new file mode 100644 index 00000000..d3d7336c --- /dev/null +++ b/services/service_prowlarr/test/support/prowlarr_test_instance.dart @@ -0,0 +1,11 @@ +import 'package:core_models/core_models.dart'; + +const Instance prowlarrTestInstance = Instance( + id: 'prowlarr-test', + name: 'Prowlarr', + kind: ServiceKind.prowlarr, + localUrl: 'http://prowlarr.test', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'not-a-secret'), +); diff --git a/services/service_qbittorrent/lib/src/qbittorrent_action_utils.dart b/services/service_qbittorrent/lib/src/qbittorrent_action_utils.dart index 032a4105..469c9a7b 100644 --- a/services/service_qbittorrent/lib/src/qbittorrent_action_utils.dart +++ b/services/service_qbittorrent/lib/src/qbittorrent_action_utils.dart @@ -3,6 +3,7 @@ import 'package:core_ui/core_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'models/qbit_torrent.dart'; import 'qbittorrent_client.dart'; import 'qbittorrent_providers.dart'; @@ -69,38 +70,73 @@ class QbittorrentActionUtils { } } + /// Picks a category for [selectedHashes] and sets it. + /// + /// The current category is ticked when every selected torrent shares one, + /// None included. A refused change is reported, and on success the + /// torrents' properties are refreshed too: with Automatic Torrent + /// Management a new category also moves the save path. static Future editCategory( BuildContext context, WidgetRef ref, Instance instance, Set selectedHashes, ) async { + final Set held = { + for (final QbitTorrent t in ref + .read(qbitRawTorrentsProvider(instance)) + .value ?? + const []) + if (selectedHashes.contains(t.hash)) t.category, + }; + final String? current = held.length == 1 ? held.single : null; final List cats = await ref.read(qbitCategoriesProvider(instance).future); if (!context.mounted) return; + + Widget option(BuildContext context, String value, String label) => + SimpleDialogOption( + onPressed: () => Navigator.of(context).pop(value), + child: Row( + children: [ + Expanded(child: Text(label)), + if (value == current) + Icon( + Icons.check, + size: 20, + color: Theme.of(context).colorScheme.primary, + ), + ], + ), + ); + final String? chosen = await showDialog( context: context, builder: (BuildContext context) => SimpleDialog( title: const Text('Set category'), children: [ - SimpleDialogOption( - onPressed: () => Navigator.of(context).pop(''), - child: const Text('None'), - ), - for (final String c in cats) - SimpleDialogOption( - onPressed: () => Navigator.of(context).pop(c), - child: Text(c), - ), + option(context, '', 'None'), + for (final String c in cats) option(context, c, c), ], ), ); - if (chosen != null) { + if (chosen == null) return; + try { await run( ref, instance, (QbittorrentClient c) => c.setCategory(selectedHashes.toList(), chosen), ); + } on Object { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Could not set category')), + ); + } + return; + } + for (final String hash in selectedHashes) { + ref.invalidate(qbitPropertiesProvider((instance, hash))); } } diff --git a/services/service_qbittorrent/lib/src/qbittorrent_home.dart b/services/service_qbittorrent/lib/src/qbittorrent_home.dart index c0f0d7a4..9ad98773 100644 --- a/services/service_qbittorrent/lib/src/qbittorrent_home.dart +++ b/services/service_qbittorrent/lib/src/qbittorrent_home.dart @@ -1068,6 +1068,16 @@ class _TorrentTileState extends ConsumerState<_TorrentTile> { final bool complete = progress >= 1.0; final bool dlActive = torrent.dlspeed > 0; final bool upActive = torrent.upspeed > 0; + // Sorted by a session total, the card shows the figure it is sorted by. + final QbitSortField sortField = ref.watch( + qbitSortProvider(widget.instance) + .select((QbitSortConfig c) => c.field), + ); + final (IconData, int)? session = switch (sortField) { + QbitSortField.sessionUp => (Icons.north, torrent.uploadedSession), + QbitSortField.sessionDl => (Icons.south, torrent.downloadedSession), + _ => null, + }; final Widget tile = Material( color: isSelected ? cs.primaryContainer : cs.surfaceContainerHigh, @@ -1190,6 +1200,34 @@ class _TorrentTileState extends ConsumerState<_TorrentTile> { : cs.onSurfaceVariant, ), ), + if (session case (final IconData icon, final int bytes)) + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: 12, + color: isSelected + ? cs.onPrimaryContainer + : cs.onSurfaceVariant, + ), + const SizedBox(width: 2), + // Bounded, so large text wraps inside + // the card rather than running off it. + Flexible( + child: Text( + '${fmtBytes(bytes)} this session', + style: + theme.textTheme.bodySmall?.copyWith( + color: isSelected + ? cs.onPrimaryContainer + .withValues(alpha: 0.8) + : cs.onSurfaceVariant, + ), + ), + ), + ], + ), ], ), ], @@ -1224,44 +1262,78 @@ class _TorrentTileState extends ConsumerState<_TorrentTile> { ], ), const SizedBox(height: Insets.md), - Row( - children: [ - _SpeedPill( - icon: Icons.south, - label: '${fmtBytes(torrent.dlspeed)}/s', - color: cs.primary, - active: dlActive, - ), - const SizedBox(width: Insets.sm), - _SpeedPill( - icon: Icons.north, - label: '${fmtBytes(torrent.upspeed)}/s', - color: cs.tertiary, - active: upActive, - ), - const Spacer(), - Icon(Icons.swap_vert, size: 14, color: cs.onSurfaceVariant), - const SizedBox(width: 2), - Text( - torrent.ratio.toStringAsFixed(2), - style: theme.textTheme.labelSmall - ?.copyWith(color: cs.onSurfaceVariant), - ), - if (!complete) ...[ - const SizedBox(width: Insets.sm), - Icon( - Icons.schedule, - size: 14, - color: cs.onSurfaceVariant, + // Speeds on the left, ratio and ETA on the right. Where one + // line cannot hold both, as on a narrow phone with large text, + // the ratio and ETA move under the speeds instead of running + // off the card. + SizedBox( + width: double.infinity, + child: Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: Insets.sm, + runSpacing: Insets.xs, + children: [ + Wrap( + spacing: Insets.sm, + runSpacing: Insets.xs, + children: [ + _SpeedPill( + icon: Icons.south, + label: '${fmtBytes(torrent.dlspeed)}/s', + color: cs.primary, + active: dlActive, + ), + _SpeedPill( + icon: Icons.north, + label: '${fmtBytes(torrent.upspeed)}/s', + color: cs.tertiary, + active: upActive, + ), + ], ), - const SizedBox(width: 2), - Text( - _formatEta(torrent.eta), - style: theme.textTheme.labelSmall - ?.copyWith(color: cs.onSurfaceVariant), + Wrap( + spacing: Insets.sm, + runSpacing: Insets.xs, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.swap_vert, + size: 14, + color: cs.onSurfaceVariant, + ), + const SizedBox(width: 2), + Text( + torrent.ratio.toStringAsFixed(2), + style: theme.textTheme.labelSmall + ?.copyWith(color: cs.onSurfaceVariant), + ), + ], + ), + if (!complete) + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.schedule, + size: 14, + color: cs.onSurfaceVariant, + ), + const SizedBox(width: 2), + Text( + _formatEta(torrent.eta), + style: theme.textTheme.labelSmall + ?.copyWith(color: cs.onSurfaceVariant), + ), + ], + ), + ], ), ], - ], + ), ), ], ), diff --git a/services/service_qbittorrent/lib/src/torrent_detail_screen.dart b/services/service_qbittorrent/lib/src/torrent_detail_screen.dart index c6724a26..bf144b43 100644 --- a/services/service_qbittorrent/lib/src/torrent_detail_screen.dart +++ b/services/service_qbittorrent/lib/src/torrent_detail_screen.dart @@ -9,6 +9,7 @@ import 'package:progress_indicator_m3e/progress_indicator_m3e.dart'; import 'models/qbit_detail.dart'; import 'models/qbit_torrent.dart'; import 'qbit_tracker_edit.dart'; +import 'qbittorrent_action_utils.dart'; import 'qbittorrent_client.dart'; import 'qbittorrent_home.dart' show fmtBytes, friendlyState; import 'qbittorrent_providers.dart'; @@ -656,8 +657,17 @@ class _OverviewTab extends ConsumerWidget { _SectionCard( title: 'Transfer', rows: <(String, String)>[ - ('Downloaded', fmtBytes(p.totalDownloaded)), - ('Uploaded', fmtBytes(p.totalUploaded)), + // All time, then since qBittorrent last started. + ( + 'Downloaded', + '${fmtBytes(p.totalDownloaded)} ' + '(${fmtBytes(torrent.downloadedSession)} this session)', + ), + ( + 'Uploaded', + '${fmtBytes(p.totalUploaded)} ' + '(${fmtBytes(torrent.uploadedSession)} this session)', + ), ('Ratio', p.shareRatio.toStringAsFixed(2)), ('Seeds', '${p.seeds} connected (${p.seedsTotal} total)'), ('Peers', '${p.peers} connected (${p.peersTotal} total)'), @@ -670,12 +680,22 @@ class _OverviewTab extends ConsumerWidget { const SizedBox(height: Insets.md), _SectionCard( title: 'Info', + editable: { + 'Category': () => QbittorrentActionUtils.editCategory( + context, + ref, + instance, + {torrent.hash}, + ), + }, rows: <(String, String)>[ ('Save path', p.savePath), ('Added', date(p.additionDate)), ('Completed', date(p.completionDate)), - if (torrent.category.isNotEmpty) - ('Category', torrent.category), + ( + 'Category', + torrent.category.isEmpty ? 'None' : torrent.category, + ), if (p.comment.isNotEmpty) ('Comment', p.comment), ], ), @@ -728,11 +748,18 @@ class _MiniPill extends StatelessWidget { } class _SectionCard extends StatelessWidget { - const _SectionCard({required this.title, required this.rows}); + const _SectionCard({ + required this.title, + required this.rows, + this.editable = const {}, + }); final String title; final List<(String, String)> rows; + /// Rows that can be changed, by label, with what a tap on them does. + final Map editable; + @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); @@ -754,28 +781,46 @@ class _SectionCard extends StatelessWidget { ), const SizedBox(height: Insets.sm), for (final (String label, String value) in rows) - Padding( - padding: const EdgeInsets.symmetric(vertical: Insets.xs), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox( - width: 104, - child: Text( - label, - style: theme.textTheme.labelMedium - ?.copyWith(color: cs.onSurfaceVariant), - ), - ), - Expanded( - child: Text(value, style: theme.textTheme.bodyMedium), - ), - ], - ), + _row(theme, cs, label, value, editable[label]), + ], + ), + ); + } + + Widget _row( + ThemeData theme, + ColorScheme cs, + String label, + String value, + VoidCallback? onEdit, + ) { + final Widget row = Padding( + padding: const EdgeInsets.symmetric(vertical: Insets.xs), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 104, + child: Text( + label, + style: theme.textTheme.labelMedium + ?.copyWith(color: cs.onSurfaceVariant), ), + ), + Expanded( + child: Text(value, style: theme.textTheme.bodyMedium), + ), + if (onEdit != null) + Icon(Icons.edit_outlined, size: 18, color: cs.onSurfaceVariant), ], ), ); + if (onEdit == null) return row; + return InkWell( + onTap: onEdit, + borderRadius: BorderRadius.circular(8), + child: Semantics(button: true, hint: 'Change', child: row), + ); } } diff --git a/services/service_qbittorrent/test/qbit_card_layout_test.dart b/services/service_qbittorrent/test/qbit_card_layout_test.dart new file mode 100644 index 00000000..a663ea4d --- /dev/null +++ b/services/service_qbittorrent/test/qbit_card_layout_test.dart @@ -0,0 +1,91 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_qbittorrent/service_qbittorrent.dart'; + +import 'support/qbit_fixtures.dart'; + +const Instance _instance = Instance( + id: 'test-qbit', + name: 'Test qBittorrent', + kind: ServiceKind.qbittorrent, + localUrl: 'http://localhost', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'k'), +); + +/// A torrent part way down, so the card shows both speeds, the ratio and +/// the ETA: the fullest bottom row a card has. +Map _downloading() => torrentRowJson( + state: 'downloading', + progress: 0.42, + dlspeed: 12 * 1024 * 1024, + upspeed: 640 * 1024, + eta: 3 * 3600 + 25 * 60, + ); + +Future _openList( + WidgetTester tester, { + required double width, + double textScale = 1, +}) async { + tester.view.physicalSize = Size(width, 891); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + tester.platformDispatcher.textScaleFactorTestValue = textScale; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + await tester.pumpWidget( + ProviderScope( + overrides: [ + qbitRawTorrentsProvider(_instance).overrideWith( + (Ref ref) async => + [QbitTorrent.fromJson(_downloading())], + ), + qbitTransferProvider(_instance) + .overrideWith((Ref ref) async => const QbitTransferInfo()), + ], + child: MaterialApp( + theme: AtriumTheme.light(null), + home: const QbittorrentHome(instance: _instance), + ), + ), + ); + await tester.pump(); + await tester.pump(); +} + +void main() { + // The test font draws every letter as a wide block, so a phone width + // would wrap here where Roboto fits. A wide screen stands in for "it fits". + testWidgets('the bottom row stays on one line when it fits', + (WidgetTester tester) async { + await _openList(tester, width: 1000); + final Rect down = tester.getRect(find.text('12.0 MB/s')); + final Rect ratio = tester.getRect(find.text('0.00')); + // Same line, with the ratio over at the right of the card. + expect((ratio.center.dy - down.center.dy).abs(), lessThan(4)); + expect(ratio.left, greaterThan(1000 * 3 / 4)); + }); + + // Only the list's own layout counts here: at these sizes the test font + // also trips the settings tab, which a real font does not. + for (final double scale in [1.5, 2]) { + testWidgets('the card fits a narrow phone at ${scale}x text', + (WidgetTester tester) async { + final List errors = []; + final void Function(FlutterErrorDetails)? report = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails d) => errors.add('$d'); + await _openList(tester, width: 320, textScale: scale); + FlutterError.onError = report; + expect( + errors.where((String e) => e.contains('qbittorrent_home.dart')), + isEmpty, + ); + expect(find.text('0.00'), findsOneWidget); + }); + } +} diff --git a/services/service_qbittorrent/test/qbit_category_edit_test.dart b/services/service_qbittorrent/test/qbit_category_edit_test.dart new file mode 100644 index 00000000..a594629c --- /dev/null +++ b/services/service_qbittorrent/test/qbit_category_edit_test.dart @@ -0,0 +1,266 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:cookie_jar/cookie_jar.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_qbittorrent/service_qbittorrent.dart'; +import 'package:service_qbittorrent/src/qbittorrent_action_utils.dart'; + +import 'support/qbit_fixtures.dart'; + +const String _other = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; + +/// A qBittorrent with two categories and two torrents. Setting a category +/// moves the torrent's save path to the category's, as Automatic Torrent +/// Management does. [failNext] makes the next change answer 409. +class _FakeQbit implements HttpClientAdapter { + _FakeQbit({String first = 'movies', String second = 'movies'}) + : category = {qbitFixtureHash: first, _other: second}; + + static const Map paths = { + 'movies': '/data/movies', + 'tv': '/data/tv', + }; + + final Map category; + final List> sets = >[]; + bool failNext = false; + + String savePath(String hash) => paths[category[hash]] ?? '/data/torrents'; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + final String path = options.path; + if (path.endsWith('torrents/categories')) { + return _json({ + for (final MapEntry e in paths.entries) + e.key: {'name': e.key, 'savePath': e.value}, + }); + } + if (path.endsWith('torrents/setCategory')) { + if (failNext) { + failNext = false; + return ResponseBody.fromString('Incorrect category name', 409); + } + final Map form = + Map.from(options.data as Map); + sets.add(form); + for (final String h in (form['hashes'] as String).split('|')) { + category[h] = form['category'] as String; + } + return _json(''); + } + return _json([]); + } + + ResponseBody _json(Object data) => ResponseBody.fromString( + jsonEncode(data), + 200, + headers: >{ + Headers.contentTypeHeader: [Headers.jsonContentType], + }, + ); + + @override + void close({bool force = false}) {} +} + +const Instance _instance = Instance( + id: 'test-qbit', + name: 'Test qBittorrent', + kind: ServiceKind.qbittorrent, + localUrl: 'http://qbit.test', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'k'), +); + +QbitTorrent _row(_FakeQbit server, String hash) => QbitTorrent.fromJson( + { + ...torrentRowJson(hash: hash), + 'category': server.category[hash], + 'save_path': server.savePath(hash), + }, + ); + +List _overrides(_FakeQbit server) { + final QbittorrentClient client = QbittorrentClient( + dio: Dio(BaseOptions(baseUrl: 'http://qbit.test/')) + ..httpClientAdapter = server, + cookies: CookieJar(), + username: '', + password: '', + apiKey: 'k', + ); + return [ + qbittorrentClientProvider(_instance).overrideWith((Ref ref) async => client), + qbitRawTorrentsProvider(_instance).overrideWith( + (Ref ref) async => [ + _row(server, qbitFixtureHash), + _row(server, _other), + ], + ), + qbitPropertiesProvider((_instance, qbitFixtureHash)).overrideWith( + (Ref ref) async => QbitTorrentProperties.fromJson({ + ...torrentPropertiesJson(), + 'save_path': server.savePath(qbitFixtureHash), + }), + ), + ]; +} + +Future _openDetail(WidgetTester tester, _FakeQbit server) async { + tester.view.physicalSize = const Size(411, 1800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: _overrides(server), + child: MaterialApp( + theme: AtriumTheme.light(null), + home: TorrentDetailScreen( + instance: _instance, + torrent: _row(server, qbitFixtureHash), + ), + ), + ), + ); + await tester.pumpAndSettle(); +} + +/// The Info card's Category row. +Finder get _categoryRow => find + .ancestor(of: find.text('Category'), matching: find.byType(InkWell)) + .first; + +Finder _inRow(String text) => + find.descendant(of: _categoryRow, matching: find.text(text)); + +Finder _option(String label) => + find.widgetWithText(SimpleDialogOption, label); + +Finder _ticked(String label) => + find.descendant(of: _option(label), matching: find.byIcon(Icons.check)); + +Future _openPicker(WidgetTester tester) async { + await tester.ensureVisible(_categoryRow); + await tester.tap(_categoryRow); + await tester.pumpAndSettle(); +} + +Future _choose(WidgetTester tester, String label) async { + await tester.tap(_option(label)); + await tester.pumpAndSettle(); +} + +void main() { + group('the detail screen', () { + testWidgets('shows None for a torrent without a category', + (WidgetTester tester) async { + await _openDetail(tester, _FakeQbit(first: '')); + expect(_inRow('None'), findsOneWidget); + }); + + testWidgets('ticks the current category in the picker', + (WidgetTester tester) async { + await _openDetail(tester, _FakeQbit()); + await _openPicker(tester); + expect(find.text('Set category'), findsOneWidget); + expect(_ticked('movies'), findsOneWidget); + expect(_ticked('tv'), findsNothing); + expect(_ticked('None'), findsNothing); + }); + + testWidgets('ticks None when there is no category', + (WidgetTester tester) async { + await _openDetail(tester, _FakeQbit(first: '')); + await _openPicker(tester); + expect(_ticked('None'), findsOneWidget); + expect(_ticked('movies'), findsNothing); + }); + + testWidgets('sets the chosen category and the row follows', + (WidgetTester tester) async { + final _FakeQbit server = _FakeQbit(); + await _openDetail(tester, server); + await _openPicker(tester); + await _choose(tester, 'tv'); + expect(server.sets, >[ + {'hashes': qbitFixtureHash, 'category': 'tv'}, + ]); + expect(_inRow('tv'), findsOneWidget); + }); + + testWidgets('the save path follows a category that moves it', + (WidgetTester tester) async { + await _openDetail(tester, _FakeQbit()); + expect(find.text('/data/movies'), findsOneWidget); + await _openPicker(tester); + await _choose(tester, 'tv'); + expect(find.text('/data/tv'), findsOneWidget); + expect(find.text('/data/movies'), findsNothing); + }); + + testWidgets('a refused change says so and keeps the old value', + (WidgetTester tester) async { + final _FakeQbit server = _FakeQbit()..failNext = true; + await _openDetail(tester, server); + await _openPicker(tester); + await _choose(tester, 'tv'); + expect(find.text('Could not set category'), findsOneWidget); + expect(_inRow('movies'), findsOneWidget); + }); + + testWidgets('dismissing the picker changes nothing', + (WidgetTester tester) async { + final _FakeQbit server = _FakeQbit(); + await _openDetail(tester, server); + await _openPicker(tester); + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + expect(server.sets, isEmpty); + expect(_inRow('movies'), findsOneWidget); + }); + }); + + testWidgets('a mixed selection ticks nothing', (WidgetTester tester) async { + await tester.pumpWidget( + ProviderScope( + overrides: _overrides(_FakeQbit(second: 'tv')), + child: MaterialApp( + home: Consumer( + builder: (BuildContext context, WidgetRef ref, _) { + // Read once so the list is loaded when the picker opens, as it + // always is behind the list screen's selection. + ref.watch(qbitRawTorrentsProvider(_instance)); + return TextButton( + onPressed: () => QbittorrentActionUtils.editCategory( + context, + ref, + _instance, + {qbitFixtureHash, _other}, + ), + child: const Text('open'), + ); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.byIcon(Icons.check), findsNothing); + }); +} diff --git a/services/service_qbittorrent/test/qbit_session_totals_test.dart b/services/service_qbittorrent/test/qbit_session_totals_test.dart new file mode 100644 index 00000000..d69c0248 --- /dev/null +++ b/services/service_qbittorrent/test/qbit_session_totals_test.dart @@ -0,0 +1,167 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_qbittorrent/service_qbittorrent.dart'; + +import 'support/qbit_fixtures.dart'; + +const Instance _instance = Instance( + id: 'test-qbit', + name: 'Test qBittorrent', + kind: ServiceKind.qbittorrent, + localUrl: 'http://localhost', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'k'), +); + +const int _sessionUp = 1610612736; // 1.5 GB +const int _sessionDown = 536870912; // 512 MB + +/// A seeding torrent that has moved some data since qBittorrent started. +Map _row() => { + ...torrentRowJson(), + 'uploaded_session': _sessionUp, + 'downloaded_session': _sessionDown, + }; + +void _phone(WidgetTester tester) { + tester.view.physicalSize = const Size(411, 891); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); +} + +Future _openList(WidgetTester tester) async { + _phone(tester); + await tester.pumpWidget( + ProviderScope( + overrides: [ + qbitRawTorrentsProvider(_instance).overrideWith( + (Ref ref) async => [QbitTorrent.fromJson(_row())], + ), + qbitTransferProvider(_instance) + .overrideWith((Ref ref) async => const QbitTransferInfo()), + ], + child: MaterialApp( + theme: AtriumTheme.light(null), + home: const QbittorrentHome(instance: _instance), + ), + ), + ); + await tester.pump(); + await tester.pump(); + return ProviderScope.containerOf( + tester.element(find.byType(QbittorrentHome)), + ); +} + +Future _sortBy( + WidgetTester tester, + ProviderContainer container, + QbitSortField field, +) async { + await container.read(qbitSortProvider(_instance).notifier).setField(field); + await tester.pump(); +} + +Future _openDetail(WidgetTester tester) async { + _phone(tester); + final QbitTorrent row = QbitTorrent.fromJson(_row()); + await tester.pumpWidget( + ProviderScope( + overrides: [ + qbitRawTorrentsProvider(_instance) + .overrideWith((Ref ref) async => [row]), + qbitPropertiesProvider((_instance, row.hash)).overrideWith( + (Ref ref) async => QbitTorrentProperties.fromJson( + { + ...torrentPropertiesJson(), + 'total_uploaded': 51539607552, // 48.0 GB + }, + ), + ), + ], + child: MaterialApp( + theme: AtriumTheme.light(null), + home: TorrentDetailScreen(instance: _instance, torrent: row), + ), + ), + ); + await tester.pump(); + await tester.pump(); +} + +void main() { + group('the torrent card', () { + testWidgets('keeps to its usual figures under the default sort', + (WidgetTester tester) async { + await _openList(tester); + expect(find.textContaining('this session'), findsNothing); + }); + + testWidgets('shows the session upload when sorted by it', + (WidgetTester tester) async { + final ProviderContainer c = await _openList(tester); + await _sortBy(tester, c, QbitSortField.sessionUp); + expect(find.text('1.5 GB this session'), findsOneWidget); + expect(find.text('512 MB this session'), findsNothing); + }); + + testWidgets('shows the session download when sorted by it', + (WidgetTester tester) async { + final ProviderContainer c = await _openList(tester); + await _sortBy(tester, c, QbitSortField.sessionDl); + expect(find.text('512 MB this session'), findsOneWidget); + expect(find.text('1.5 GB this session'), findsNothing); + }); + + testWidgets('keeps the session line inside a narrow card at large text', + (WidgetTester tester) async { + final ProviderContainer c = await _openList(tester); + tester.view.physicalSize = const Size(320, 891); + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + // Set aside here: overflow, since the card's speed row overflows at + // this size on its own and the session line is measured below; and + // the settings tab, built alongside the list, which the wide test font + // trips at this size where Roboto does not. Any other error from the + // list still reports. + final void Function(FlutterErrorDetails)? report = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails d) { + final String text = '$d'; + if (text.contains('qbittorrent_home.dart') && + !text.contains('A RenderFlex overflowed')) { + report?.call(d); + } + }; + try { + await _sortBy(tester, c, QbitSortField.sessionUp); + await tester.pump(); + } finally { + FlutterError.onError = report; + } + final Rect line = tester.getRect(find.textContaining('this session')); + expect(line.right, lessThanOrEqualTo(320)); + }); + + testWidgets('drops it again for another sort', + (WidgetTester tester) async { + final ProviderContainer c = await _openList(tester); + await _sortBy(tester, c, QbitSortField.sessionUp); + await _sortBy(tester, c, QbitSortField.name); + expect(find.textContaining('this session'), findsNothing); + }); + }); + + group('the detail screen', () { + testWidgets('puts the session beside the all-time totals', + (WidgetTester tester) async { + await _openDetail(tester); + expect(find.text('48.0 GB (1.5 GB this session)'), findsOneWidget); + expect(find.textContaining('(512 MB this session)'), findsOneWidget); + }); + }); +} diff --git a/services/service_radarr/lib/src/radarr_api.dart b/services/service_radarr/lib/src/radarr_api.dart index df64818e..0869cb7c 100644 --- a/services/service_radarr/lib/src/radarr_api.dart +++ b/services/service_radarr/lib/src/radarr_api.dart @@ -189,8 +189,8 @@ class RadarrApi { } } - /// Absolute, authenticated URL for a movie image, suitable for - /// `CachedNetworkImage`. + /// Absolute URL for a movie image, for `AtriumNetworkImage`, which adds + /// the api key as a header. String? posterUrl( RadarrImage image, { int? width, @@ -230,8 +230,9 @@ class RadarrApi { pathOrUrl.substring(coverIdx + '/MediaCover'.length); pathOrUrl = '$_base/mediacover$tail'; } - final String separator = pathOrUrl.contains('?') ? '&' : '?'; - return base.resolve('$pathOrUrl${separator}apikey=$apiKey').toString(); + // No key in the URL: a reverse proxy logs the full request line. + // Artwork carries it as an X-Api-Key header, from ArtworkHeaders. + return base.resolve(pathOrUrl).toString(); } return upstream; } diff --git a/services/service_radarr/test/radarr_poster_url_test.dart b/services/service_radarr/test/radarr_poster_url_test.dart index 4bc01e7a..e23bde86 100644 --- a/services/service_radarr/test/radarr_poster_url_test.dart +++ b/services/service_radarr/test/radarr_poster_url_test.dart @@ -45,4 +45,20 @@ void main() { expect(url, contains('/radarr/api/v3/mediacover/87/')); }); }); + + test('the api key stays out of the url', () { + // A reverse proxy writes the full request line to its access log, so a + // key in the query ends up there. Artwork sends it as a header instead, + // from ArtworkHeaders in core_ui. + final String? url = _apiFor('https://example.com/').posterUrl( + const RadarrImage( + coverType: 'poster', + url: '/MediaCover/87/poster.jpg?lastWrite=639', + ), + ); + expect( + url, + 'https://example.com/api/v3/mediacover/87/poster-500.jpg?lastWrite=639', + ); + }); } diff --git a/services/service_rtorrent/lib/service_rtorrent.dart b/services/service_rtorrent/lib/service_rtorrent.dart index be48a68c..ad165c76 100644 --- a/services/service_rtorrent/lib/service_rtorrent.dart +++ b/services/service_rtorrent/lib/service_rtorrent.dart @@ -8,6 +8,7 @@ export 'src/models/rtorrent_torrent.dart'; export 'src/rtorrent_add_sheet.dart'; export 'src/rtorrent_api.dart'; export 'src/rtorrent_detail_screen.dart'; +export 'src/rtorrent_endpoint.dart'; export 'src/rtorrent_format.dart'; export 'src/rtorrent_home.dart'; export 'src/rtorrent_providers.dart'; diff --git a/services/service_rtorrent/lib/src/rtorrent_api.dart b/services/service_rtorrent/lib/src/rtorrent_api.dart index d16af58d..06c9344e 100644 --- a/services/service_rtorrent/lib/src/rtorrent_api.dart +++ b/services/service_rtorrent/lib/src/rtorrent_api.dart @@ -25,8 +25,10 @@ import 'xmlrpc.dart'; /// the shared [AuthInterceptor]. /// /// The endpoint is whatever URL the user configured: `host:8000` for a direct -/// XML-RPC port, or something like `host/RPC2` when ruTorrent's nginx fronts -/// it. Both are just "POST to the base URL" as far as this client cares. +/// XML-RPC port, `host/RPC2` when a web server mounts it, or +/// `.../rutorrent/plugins/httprpc/action.php` on a seedbox where only +/// ruTorrent's httprpc plugin reaches it. All are just "POST to the address +/// itself" as far as this client cares. class RtorrentApi { RtorrentApi(this._dio, {Dio? fetchDio}) : _fetchDio = fetchDio ?? Dio(); @@ -208,6 +210,12 @@ class RtorrentApi { return dir.isEmpty ? const [] : ['d.directory.set="$dir"']; } + // ------------------------------------------------------------------ misc + + /// rTorrent's version string; the cheapest call there is. + Future clientVersion() async => + '${await _call('system.client_version', const [])}'; + // ---------------------------------------------------------------- limits /// Global caps in **bytes per second**; 0 clears the limit. @@ -222,7 +230,8 @@ class RtorrentApi { Future _call(String method, List params) async { try { final Response resp = await _dio.post( - '', + // The endpoint is the address itself, never `.../action.php/`. + selfPath(_dio.options.baseUrl), data: XmlRpc.buildCall(method, params), options: Options( contentType: 'text/xml', @@ -254,9 +263,11 @@ class RtorrentApi { throw NetworkServerException('rTorrent: ${e.message}', status: 200); } on FormatException catch (e) { throw NetworkBadResponseException( - 'rTorrent did not return XML-RPC (${e.message}). Point the URL at the ' - 'SCGI/XML-RPC endpoint - often port 8000, or /RPC2 when ruTorrent is ' - 'in front - rather than at the web UI.', + 'rTorrent did not return XML-RPC (${e.message}), so the address ' + 'points somewhere else, such as the ruTorrent web page. Behind ' + 'ruTorrent, as on most seedboxes, add /plugins/httprpc/action.php to ' + 'the ruTorrent address. Otherwise rTorrent is usually at /RPC2 or on ' + 'port 8000.', status: 200, ); } on DioException catch (e) { diff --git a/services/service_rtorrent/lib/src/rtorrent_endpoint.dart b/services/service_rtorrent/lib/src/rtorrent_endpoint.dart new file mode 100644 index 00000000..7f4f8656 --- /dev/null +++ b/services/service_rtorrent/lib/src/rtorrent_endpoint.dart @@ -0,0 +1,64 @@ +import 'package:core_networking/core_networking.dart'; +import 'package:dio/dio.dart'; + +import 'rtorrent_api.dart'; + +/// What answered when rTorrent's XML-RPC was asked for at an address. +enum RtorrentEndpointAnswer { + /// rTorrent itself: the call came back as XML-RPC. + xmlRpc, + + /// The proxy in front refused the credentials. + refused, + + /// Something answered, but not with XML-RPC: a web page such as ruTorrent's + /// own, a 404, or a proxy error. + notXmlRpc, + + /// Nothing answered at all. + unreachable, +} + +/// Where rTorrent's XML-RPC usually lives beneath the address a user types. +/// +/// Most seedboxes run ruTorrent in front of rTorrent and reach it only through +/// ruTorrent's httprpc plugin, which passes XML-RPC straight through. The +/// address people have to hand is the ruTorrent page, or the box's root with +/// ruTorrent under it. Self-hosted setups more often mount it at `/RPC2`. +const List rtorrentEndpointGuesses = [ + 'plugins/httprpc/action.php', + 'rutorrent/plugins/httprpc/action.php', + 'RPC2', +]; + +/// Asks the XML-RPC at [dio]'s base URL for rTorrent's version. +Future checkRtorrentEndpoint(Dio dio) async { + try { + await RtorrentApi(dio).clientVersion(); + return RtorrentEndpointAnswer.xmlRpc; + } on NetworkAuthException { + return RtorrentEndpointAnswer.refused; + } on NetworkServerException catch (e) { + // A fault rides inside a 200, and only rTorrent sends one. + return e.status == 200 + ? RtorrentEndpointAnswer.xmlRpc + : RtorrentEndpointAnswer.notXmlRpc; + } on NetworkBadResponseException { + return RtorrentEndpointAnswer.notXmlRpc; + } on NetworkNotFoundException { + return RtorrentEndpointAnswer.notXmlRpc; + } on NetworkException { + return RtorrentEndpointAnswer.unreachable; + } +} + +/// [url] with [path] appended, or null when [url] already points at an +/// endpoint and there is nothing to look for beneath it. +String? rtorrentGuessUrl(String url, String path) { + final String base = url.trim().replaceFirst(RegExp(r'/+$'), ''); + final String last = base.split('/').last.toLowerCase(); + if (last.endsWith('.php') || last == 'rpc2') { + return null; + } + return '$base/$path'; +} diff --git a/services/service_rtorrent/test/rtorrent_endpoint_test.dart b/services/service_rtorrent/test/rtorrent_endpoint_test.dart new file mode 100644 index 00000000..343ba568 --- /dev/null +++ b/services/service_rtorrent/test/rtorrent_endpoint_test.dart @@ -0,0 +1,180 @@ +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_rtorrent/service_rtorrent.dart'; + +class _Answer implements HttpClientAdapter { + _Answer(this.status, this.body, {this.contentType = 'text/xml'}); + + final int status; + final String body; + final String contentType; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async => + ResponseBody.fromString( + body, + status, + headers: >{ + Headers.contentTypeHeader: [contentType], + }, + ); + + @override + void close({bool force = false}) {} +} + +class _Recording implements HttpClientAdapter { + final List uris = []; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + uris.add(options.uri); + return ResponseBody.fromString( + '' + '0.16.22', + 200, + ); + } + + @override + void close({bool force = false}) {} +} + +Future _answering( + int status, + String body, { + String contentType = 'text/xml', +}) => + checkRtorrentEndpoint( + Dio(BaseOptions(baseUrl: 'http://box.test/')) + ..httpClientAdapter = _Answer(status, body, contentType: contentType), + ); + +void main() { + group('checkRtorrentEndpoint', () { + test('a methodResponse is rTorrent', () async { + expect( + await _answering( + 200, + '' + '0.9.8', + ), + RtorrentEndpointAnswer.xmlRpc, + ); + }); + + test('a fault is rTorrent too', () async { + expect( + await _answering( + 200, + '' + 'faultCode-506' + 'faultStringMethod not ' + 'defined' + '', + ), + RtorrentEndpointAnswer.xmlRpc, + ); + }); + + test('the ruTorrent page is not', () async { + expect( + await _answering( + 200, + 'ruTorrent', + contentType: 'text/html', + ), + RtorrentEndpointAnswer.notXmlRpc, + ); + }); + + test('a 404 or a proxy error is not', () async { + expect( + await _answering(404, 'Not Found'), + RtorrentEndpointAnswer.notXmlRpc, + ); + expect( + await _answering(502, 'Bad Gateway'), + RtorrentEndpointAnswer.notXmlRpc, + ); + }); + + test('a 401 is refused credentials', () async { + expect( + await _answering(401, 'Unauthorized'), + RtorrentEndpointAnswer.refused, + ); + }); + }); + + group('rtorrentGuessUrl', () { + test('appends beneath the address, with or without a trailing slash', () { + expect( + rtorrentGuessUrl('https://box.test/rutorrent/', 'RPC2'), + 'https://box.test/rutorrent/RPC2', + ); + expect( + rtorrentGuessUrl(' https://box.test/rutorrent ', 'RPC2'), + 'https://box.test/rutorrent/RPC2', + ); + }); + + test('does not look beneath an address that is already an endpoint', () { + expect( + rtorrentGuessUrl( + 'https://box.test/rutorrent/plugins/httprpc/action.php', + 'RPC2', + ), + isNull, + ); + expect(rtorrentGuessUrl('http://box.test/RPC2/', 'RPC2'), isNull); + }); + }); + + test('calls go to an httprpc address without a trailing slash', () async { + // nginx answers `.../action.php/` with a 404. + final _Recording adapter = _Recording(); + await RtorrentApi( + Dio( + BaseOptions( + baseUrl: 'https://box.test/rutorrent/plugins/httprpc/action.php/', + ), + )..httpClientAdapter = adapter, + ).clientVersion(); + expect( + '${adapter.uris.single}', + 'https://box.test/rutorrent/plugins/httprpc/action.php', + ); + }); + + test('the error for a web page says where rTorrent usually is', () async { + final RtorrentApi api = RtorrentApi( + Dio(BaseOptions(baseUrl: 'http://box.test/')) + ..httpClientAdapter = _Answer( + 200, + '', + contentType: 'text/html', + ), + ); + await expectLater( + api.getTorrents(), + throwsA( + isA().having( + (Exception e) => e.toString(), + 'message', + contains('/plugins/httprpc/action.php'), + ), + ), + ); + }); +} diff --git a/services/service_sonarr/lib/src/sonarr_api.dart b/services/service_sonarr/lib/src/sonarr_api.dart index 4997e301..1dd35147 100644 --- a/services/service_sonarr/lib/src/sonarr_api.dart +++ b/services/service_sonarr/lib/src/sonarr_api.dart @@ -163,8 +163,8 @@ class SonarrApi { } } - /// Absolute, authenticated URL for a series image, suitable for - /// `CachedNetworkImage`. + /// Absolute URL for a series image, for `AtriumNetworkImage`, which adds + /// the api key as a header. String? posterUrl( SonarrImage image, { int? width, @@ -205,8 +205,9 @@ class SonarrApi { pathOrUrl.substring(coverIdx + '/MediaCover'.length); pathOrUrl = '$_base/mediacover$tail'; } - final String separator = pathOrUrl.contains('?') ? '&' : '?'; - return base.resolve('$pathOrUrl${separator}apikey=$apiKey').toString(); + // No key in the URL: a reverse proxy logs the full request line. + // Artwork carries it as an X-Api-Key header, from ArtworkHeaders. + return base.resolve(pathOrUrl).toString(); } return upstream; } diff --git a/services/service_sonarr/test/sonarr_poster_url_test.dart b/services/service_sonarr/test/sonarr_poster_url_test.dart index c27849ce..e77422b8 100644 --- a/services/service_sonarr/test/sonarr_poster_url_test.dart +++ b/services/service_sonarr/test/sonarr_poster_url_test.dart @@ -45,4 +45,20 @@ void main() { expect(url, contains('/sonarr/api/v3/mediacover/87/')); }); }); + + test('the api key stays out of the url', () { + // A reverse proxy writes the full request line to its access log, so a + // key in the query ends up there. Artwork sends it as a header instead, + // from ArtworkHeaders in core_ui. + final String? url = _apiFor('https://example.com/').posterUrl( + const SonarrImage( + coverType: 'poster', + url: '/MediaCover/87/poster.jpg?lastWrite=639', + ), + ); + expect( + url, + 'https://example.com/api/v3/mediacover/87/poster.jpg?lastWrite=639', + ); + }); } diff --git a/site/src/components/hero.html b/site/src/components/hero.html index feed3d83..b0576e73 100644 --- a/site/src/components/hero.html +++ b/site/src/components/hero.html @@ -1,7 +1,7 @@
-
v1.11.0 Release
+
v1.12.0 Release

Your self-hosted media, unified.

One premium Android app that fronts Sonarr, Radarr, Plex, Jellyfin, qBittorrent, and more. Material 3 Expressive, multi-instance, and fully secure.