From 1a68b1aead492b50d824bde99fb1f30e1360ed26 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Wed, 20 May 2026 23:34:37 +0300 Subject: Add DioClient with auth interceptors and refactor PlayerApiClient (ma) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduces dio_client.dart with _AuthInterceptor (guards Bearer token injection with containsKey so callers can override Authorization) and _UnauthorizedInterceptor (private fields, 401 → login redirect). PlayerApiClient is refactored to accept a pre-configured Dio instance instead of raw credentials; adds dio + flutter_secure_storage deps. Fixes review issues: Auth header comment/behavior corrected, private fields on _UnauthorizedInterceptor, unused import removed. Co-Authored-By: Claude Sonnet 4.6 --- player-android/lib/api/dio_client.dart | 152 +++++++++++++++ player-android/lib/api/player_api_client.dart | 269 +++++++++++++++++++++++--- 2 files changed, 389 insertions(+), 32 deletions(-) create mode 100644 player-android/lib/api/dio_client.dart (limited to 'player-android/lib') diff --git a/player-android/lib/api/dio_client.dart b/player-android/lib/api/dio_client.dart new file mode 100644 index 0000000..35db589 --- /dev/null +++ b/player-android/lib/api/dio_client.dart @@ -0,0 +1,152 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +// Storage key under which the bearer token is persisted across app restarts. +const _kTokenKey = 'bearer_token'; + +/// Abstraction over the secure token store so the interceptor can be tested +/// without platform code (Liskov substitution / dependency inversion). +abstract interface class TokenStorage { + Future readToken(); + Future writeToken(String token); + Future deleteToken(); +} + +/// Production implementation backed by [FlutterSecureStorage]. +/// +/// Uses AES encryption on Android and the iOS Keychain on Apple platforms. +class SecureTokenStorage implements TokenStorage { + SecureTokenStorage({FlutterSecureStorage? storage}) + : _storage = storage ?? const FlutterSecureStorage(); + + final FlutterSecureStorage _storage; + + @override + Future readToken() => _storage.read(key: _kTokenKey); + + @override + Future writeToken(String token) => + _storage.write(key: _kTokenKey, value: token); + + @override + Future deleteToken() => _storage.delete(key: _kTokenKey); +} + +/// Interceptor that attaches a Bearer token to every outgoing request. +/// +/// The token is read lazily from [TokenStorage] so that changes (login / +/// logout) are picked up without restarting the Dio instance. +class _AuthInterceptor extends Interceptor { + _AuthInterceptor(this._storage); + + final TokenStorage _storage; + + @override + Future onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) async { + final token = await _storage.readToken(); + if (token != null && token.isNotEmpty) { + // Only attach the bearer token when no Authorization header has been set + // explicitly by the caller (e.g. public endpoints may supply their own + // credentials and must not be overwritten). + if (!options.headers.containsKey('Authorization')) { + options.headers['Authorization'] = 'Bearer $token'; + } + } + handler.next(options); + } +} + +/// Interceptor that intercepts 401 Unauthorized responses and redirects the +/// user to the login route via the supplied [NavigatorKey]. +/// +/// On 401, the stored token is removed (it is no longer valid) and the +/// navigator pushes a named replacement so that the back-stack cannot return +/// the user to an authenticated screen. +class _UnauthorizedInterceptor extends Interceptor { + _UnauthorizedInterceptor({ + required TokenStorage storage, + required GlobalKey navigatorKey, + String loginRoute = '/login', + }) : _storage = storage, + _navigatorKey = navigatorKey, + _loginRoute = loginRoute; + + // Private fields consistent with _AuthInterceptor naming conventions. + final TokenStorage _storage; + final GlobalKey _navigatorKey; + final String _loginRoute; + + @override + Future onError( + DioException err, + ErrorInterceptorHandler handler, + ) async { + if (err.response?.statusCode == 401) { + // Purge the stale token so subsequent requests start unauthenticated. + await _storage.deleteToken(); + + // Use the navigator key to redirect without needing a BuildContext. + _navigatorKey.currentState + ?.pushNamedAndRemoveUntil(_loginRoute, (_) => false); + } + handler.next(err); + } +} + +/// Factory that assembles a fully configured [Dio] instance wired with: +/// - bearer-token injection on every request, and +/// - global 401 → login redirect. +/// +/// Callers own the returned [Dio] and may add further interceptors on top. +/// Separating construction from usage (SRP) keeps this class testable. +class DioClient { + DioClient({ + required Uri baseUrl, + required TokenStorage storage, + required GlobalKey navigatorKey, + String loginRoute = '/login', + BaseOptions? baseOptions, + }) : _dio = _buildDio( + baseUrl: baseUrl, + storage: storage, + navigatorKey: navigatorKey, + loginRoute: loginRoute, + baseOptions: baseOptions, + ); + + final Dio _dio; + + /// Exposes the underlying [Dio] so that [PlayerApiClient] can issue typed + /// requests without re-implementing the interceptor plumbing. + Dio get dio => _dio; + + static Dio _buildDio({ + required Uri baseUrl, + required TokenStorage storage, + required GlobalKey navigatorKey, + required String loginRoute, + BaseOptions? baseOptions, + }) { + final options = (baseOptions ?? BaseOptions()).copyWith( + baseUrl: baseUrl.toString(), + // JSON is the wire format for all API endpoints. + contentType: 'application/json', + responseType: ResponseType.json, + ); + + return Dio(options) + ..interceptors.addAll([ + // Auth must run before the 401 handler so the token is attached first. + _AuthInterceptor(storage), + _UnauthorizedInterceptor( + storage: storage, + navigatorKey: navigatorKey, + loginRoute: loginRoute, + ), + ]); + } +} diff --git a/player-android/lib/api/player_api_client.dart b/player-android/lib/api/player_api_client.dart index eb438f4..9e987c2 100644 --- a/player-android/lib/api/player_api_client.dart +++ b/player-android/lib/api/player_api_client.dart @@ -1,64 +1,269 @@ import 'dart:typed_data'; +import 'package:dio/dio.dart'; + import '../models/models.dart'; +/// High-level API surface that maps 1-to-1 with the player-server REST API +/// (see player-server/docs/api.md for the authoritative contract). +/// +/// Each method corresponds to a single HTTP endpoint. All HTTP plumbing +/// (bearer-token injection, 401 → login redirect, base-URL configuration) is +/// handled by the [Dio] instance provided at construction time. +/// +/// In production, create the [Dio] via [DioClient] which wires up the auth +/// and 401-redirect interceptors. In tests, pass a plain or mocked [Dio]. +/// +/// Concrete implementations of the stub methods will be added incrementally as +/// features are built. class PlayerApiClient { - final Uri baseUrl; - final String bearerToken; + /// Creates a client backed by [dio]. + /// + /// Prefer creating [dio] via [DioClient] in production to get bearer-token + /// injection and 401 → login redirect out of the box. + PlayerApiClient({required Dio dio}) : _dio = dio; + + // The configured Dio instance with auth/401 interceptors already applied. + final Dio _dio; + + // --------------------------------------------------------------------------- + // Auth + // --------------------------------------------------------------------------- - // Normal (non-const) constructor: Uri is not const-constructable, so the - // constructor must not be declared const. - PlayerApiClient({required this.baseUrl, required this.bearerToken}); + Future bootstrap({ + required String username, + required String password, + }) => + throw UnimplementedError(); + + Future login({ + required String username, + required String password, + }) => + throw UnimplementedError(); - Future bootstrap({required String username, required String password}) => throw UnimplementedError(); - Future login({required String username, required String password}) => throw UnimplementedError(); Future logout() => throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Health + // --------------------------------------------------------------------------- + Future healthz() => throw UnimplementedError(); Future readyz() => throw UnimplementedError(); - Future getSharedMediaPage(String token) => throw UnimplementedError(); - Future streamSharedMedia(String token, {String? range}) => throw UnimplementedError(); - Future getSharedThumbnail(String token) => throw UnimplementedError(); - Future downloadSharedMedia(String token) => throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Shared / public endpoints (no auth required) + // --------------------------------------------------------------------------- + + Future getSharedMediaPage(String token) => + throw UnimplementedError(); + + Future streamSharedMedia(String token, {String? range}) => + throw UnimplementedError(); + + Future getSharedThumbnail(String token) => + throw UnimplementedError(); + + Future downloadSharedMedia(String token) => + throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Config + // --------------------------------------------------------------------------- + Future> getConfig() => throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Sets + // --------------------------------------------------------------------------- + Future> listSets() => throw UnimplementedError(); - Future> browseSet(int setId, {String? parent}) => throw UnimplementedError(); - Future getSetCover(int setId, {String? folder}) => throw UnimplementedError(); - Future updateSetCover(int setId, {String? folder}) => throw UnimplementedError(); - Future uploadToSet(int setId, {required String fileName, required List bytes}) => throw UnimplementedError(); - Future> listMedia({String? search, int? setId, List? setIds, String? type, bool? favorites, List? tags, double? minDuration, double? maxDuration, int? fileSizeMin, int? fileSizeMax, String? sort, int? limit, int? offset, String? folder, String? parent}) => throw UnimplementedError(); + + Future> browseSet(int setId, {String? parent}) => + throw UnimplementedError(); + + Future getSetCover(int setId, {String? folder}) => + throw UnimplementedError(); + + Future updateSetCover(int setId, {String? folder}) => + throw UnimplementedError(); + + Future uploadToSet( + int setId, { + required String fileName, + required List bytes, + }) => + throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Media + // --------------------------------------------------------------------------- + + Future> listMedia({ + String? search, + int? setId, + List? setIds, + String? type, + bool? favorites, + List? tags, + double? minDuration, + double? maxDuration, + int? fileSizeMin, + int? fileSizeMax, + String? sort, + int? limit, + int? offset, + String? folder, + String? parent, + }) => + throw UnimplementedError(); + Future getMedia(int mediaId) => throw UnimplementedError(); - Future streamMedia(int mediaId, {String? range}) => throw UnimplementedError(); + + Future streamMedia(int mediaId, {String? range}) => + throw UnimplementedError(); + Future downloadMedia(int mediaId) => throw UnimplementedError(); + Future getThumbnail(int mediaId) => throw UnimplementedError(); + Future regenerateThumbnail(int mediaId) => throw UnimplementedError(); + Future toggleFavorite(int mediaId) => throw UnimplementedError(); + + Future deleteMedia(int mediaId) => throw UnimplementedError(); + + Future restoreMedia(int mediaId) => throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Tags + // --------------------------------------------------------------------------- + Future> listTags() => throw UnimplementedError(); + Future addTag(int mediaId, String tag) => throw UnimplementedError(); - Future removeTag(int mediaId, String tag) => throw UnimplementedError(); - Future createShare(int mediaId, {DateTime? expiresAt, int? maxUses}) => throw UnimplementedError(); - Future> listSharesForMedia(int mediaId) => throw UnimplementedError(); + + Future removeTag(int mediaId, String tag) => + throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Shares + // --------------------------------------------------------------------------- + + Future createShare( + int mediaId, { + DateTime? expiresAt, + int? maxUses, + }) => + throw UnimplementedError(); + + Future> listSharesForMedia(int mediaId) => + throw UnimplementedError(); + Future> listMyShares() => throw UnimplementedError(); + Future revokeShare(String token) => throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Notes + // --------------------------------------------------------------------------- + Future getNote(int mediaId) => throw UnimplementedError(); - Future upsertNote(int mediaId, String content) => throw UnimplementedError(); + + Future upsertNote(int mediaId, String content) => + throw UnimplementedError(); + Future deleteNote(int mediaId) => throw UnimplementedError(); - Future updateProgress({required int mediaId, required double positionSeconds}) => throw UnimplementedError(); - Future updateProgressStatus({required int mediaId, required String status}) => throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Progress + // --------------------------------------------------------------------------- + + Future updateProgress({ + required int mediaId, + required double positionSeconds, + }) => + throw UnimplementedError(); + + Future updateProgressStatus({ + required int mediaId, + required String status, + }) => + throw UnimplementedError(); + Future> listInProgress() => throw UnimplementedError(); - Future deleteMedia(int mediaId) => throw UnimplementedError(); - Future restoreMedia(int mediaId) => throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Podcasts + // --------------------------------------------------------------------------- + Future> listPodcasts() => throw UnimplementedError(); - Future> listEpisodes(int podcastSetId, {int? limit, int? offset}) => throw UnimplementedError(); + + Future> listEpisodes( + int podcastSetId, { + int? limit, + int? offset, + }) => + throw UnimplementedError(); + Future downloadEpisode(int episodeId) => throw UnimplementedError(); - Future toggleEpisodeComplete(int episodeId) => throw UnimplementedError(); - Future subscribePodcast({required String feedUrl, String? setName}) => throw UnimplementedError(); + + Future toggleEpisodeComplete(int episodeId) => + throw UnimplementedError(); + + Future subscribePodcast({ + required String feedUrl, + String? setName, + }) => + throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Admin – Users + // --------------------------------------------------------------------------- + Future> listUsers() => throw UnimplementedError(); - Future createUser({required String username, required String password, required bool isAdmin}) => throw UnimplementedError(); + + Future createUser({ + required String username, + required String password, + required bool isAdmin, + }) => + throw UnimplementedError(); + Future deleteUser(int userId) => throw UnimplementedError(); - Future>> listPermissions() => throw UnimplementedError(); - Future grantPermission({required int setId, required int userId, required String role}) => throw UnimplementedError(); - Future revokePermission({required int setId, required int userId}) => throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Admin – Permissions + // --------------------------------------------------------------------------- + + Future>> listPermissions() => + throw UnimplementedError(); + + Future grantPermission({ + required int setId, + required int userId, + required String role, + }) => + throw UnimplementedError(); + + Future revokePermission({ + required int setId, + required int userId, + }) => + throw UnimplementedError(); + + // --------------------------------------------------------------------------- + // Admin – Scanner + // --------------------------------------------------------------------------- + Future triggerRescan() => throw UnimplementedError(); + Future> getScanProgress() => throw UnimplementedError(); + Future> listTrash() => throw UnimplementedError(); + + // Expose the underlying Dio for advanced callers (e.g. binary streaming). + // This should not be used for ordinary JSON requests; prefer the typed + // methods above. + Dio get rawDio => _dio; } -- cgit v1.2.3