Add Supa account and search changes

This commit is contained in:
Fabian Freund
2026-05-22 18:10:22 +02:00
parent 3a19865b2e
commit 51289f1266
374 changed files with 54061 additions and 5013 deletions
@@ -0,0 +1,238 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'dart:math';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:search_client/search_client.dart';
import 'package:uuid/uuid.dart';
import 'package:weblibre/features/account/domain/repositories/account_auth.dart';
import 'package:weblibre/features/search_credits/data/token_stash.dart';
import 'package:weblibre/features/search_credits/domain/providers.dart';
import 'package:weblibre/features/search_credits/domain/repositories/search_credits_repository.dart';
import 'package:weblibre/features/search_credits/domain/repositories/search_token_stash_repository.dart';
import 'package:weblibre/features/user/data/providers.dart';
part 'search_token_issuance_controller.g.dart';
sealed class SearchTokenIssuanceState {
const SearchTokenIssuanceState();
}
class SearchTokenIssuanceIdle extends SearchTokenIssuanceState {
const SearchTokenIssuanceIdle();
}
class SearchTokenIssuanceRequesting extends SearchTokenIssuanceState {
final int count;
final String idempotencyKey;
const SearchTokenIssuanceRequesting({
required this.count,
required this.idempotencyKey,
});
}
class SearchTokenIssuanceNeedsPurchase extends SearchTokenIssuanceState {
final int remainingCredits;
const SearchTokenIssuanceNeedsPurchase({required this.remainingCredits});
}
class SearchTokenIssuanceNeedsReauth extends SearchTokenIssuanceState {
const SearchTokenIssuanceNeedsReauth();
}
class SearchTokenIssuanceFailed extends SearchTokenIssuanceState {
final Object error;
final StackTrace stackTrace;
const SearchTokenIssuanceFailed(this.error, this.stackTrace);
}
@Riverpod(keepAlive: true)
class SearchTokenIssuanceController extends _$SearchTokenIssuanceController {
Future<IssuanceResult>? _pending;
@override
SearchTokenIssuanceState build() => const SearchTokenIssuanceIdle();
/// Request `count` tokens. Single-flight — a second call while `Requesting`
/// returns the same pending future. If a retry follows a failure, the same
/// idempotency key is reused so the server can replay the prior result.
Future<IssuanceResult?> issue({required int count}) async {
final pending = _pending;
if (pending != null) return pending;
final authState = ref.read(accountAuthRepositoryProvider).value;
final client = authState?.client;
if (authState == null || !authState.isSignedIn || client == null) {
state = const SearchTokenIssuanceNeedsReauth();
return null;
}
final session = client.auth.currentSession;
final accessToken = session?.accessToken;
if (accessToken == null) {
state = const SearchTokenIssuanceNeedsReauth();
return null;
}
// Always generate a fresh idempotency key per attempt. The SDK
// re-blinds the token_request on every call — reusing a key with a
// new blinded request would trigger IdempotencyKeyReusedError on the
// backend rather than a safe replay. Retries after a failure must
// therefore start a new reservation from scratch.
final idempotencyKey = const Uuid().v4();
state = SearchTokenIssuanceRequesting(
count: count,
idempotencyKey: idempotencyKey,
);
final future = _runIssuance(
accessToken: accessToken,
idempotencyKey: idempotencyKey,
count: count,
);
_pending = future;
try {
final result = await future;
state = const SearchTokenIssuanceIdle();
unawaited(ref.read(searchCreditsRepositoryProvider.notifier).refresh());
ref.invalidate(searchTokenStashCountProvider);
return result;
} on InsufficientCreditsError catch (e) {
state = SearchTokenIssuanceNeedsPurchase(
remainingCredits: e.remainingCredits,
);
return null;
} catch (e, s) {
state = SearchTokenIssuanceFailed(e, s);
return null;
} finally {
_pending = null;
}
}
Future<IssuanceResult> _runIssuance({
required String accessToken,
required String idempotencyKey,
required int count,
}) async {
final issuance = ref.read(issuanceClientProvider);
// Fetch the public key explicitly so we can tag the stash rows that
// `issueAndStash` will write with the exact key version the issuer
// signed against — `DriftTokenStash.add` would otherwise have no way
// to know it. `IssuanceClient` caches the result, so this is free
// after the first call.
final key = await issuance.fetchPublicKey();
final db = ref.read(userDatabaseProvider);
final stash = DriftTokenStash(
db.searchTokensDao,
issuerKeyVersion: key.version,
);
return issuance.issueAndStash(
supabaseAccessToken: accessToken,
idempotencyKey: idempotencyKey,
count: count,
stash: stash,
);
}
void reset() {
if (_pending != null) return;
state = const SearchTokenIssuanceIdle();
}
}
/// Result of an opportunistic token top-up attempt.
enum TokenTopUpOutcome {
/// New tokens were issued and are now in the stash.
issued,
/// User has zero available credits — needs to purchase more.
noCredits,
/// Issuance failed (network, auth, server) — see controller state for
/// the surfaced error.
issuanceFailed,
}
/// Result of ensuring at least one token is available for a search.
enum TokenAvailabilityOutcome {
/// A token is available in the local stash.
available,
/// The account has no remaining credits to issue tokens from.
noCredits,
/// Credits may exist, but token issuance failed and should be retried.
issuanceFailed,
}
/// Helpers around the token stash + issuance flow. Lives as a plain class
/// rather than a Notifier because the operations are one-shot async calls
/// with no state to publish back to listeners — the relevant state is
/// already in `searchTokenIssuanceControllerProvider` /
/// `searchCreditsRepositoryProvider` / `searchTokenStashCountProvider`.
class SearchTokenAvailability {
final Ref ref;
SearchTokenAvailability(this.ref);
/// Ensure the stash has at least one token, topping up from the server when
/// possible. Distinguishes real zero-credit balances from retryable issuance
/// failures so callers can show the right recovery path.
Future<TokenAvailabilityOutcome> ensureAvailable() async {
final stash = ref.read(searchTokenStashProvider);
if (await stash.count() > 0) return TokenAvailabilityOutcome.available;
final outcome = await topUp();
switch (outcome) {
case TokenTopUpOutcome.issued:
return (await stash.count()) > 0
? TokenAvailabilityOutcome.available
: TokenAvailabilityOutcome.issuanceFailed;
case TokenTopUpOutcome.noCredits:
return TokenAvailabilityOutcome.noCredits;
case TokenTopUpOutcome.issuanceFailed:
return TokenAvailabilityOutcome.issuanceFailed;
}
}
/// Opportunistically request a fresh batch of tokens (capped at 10 per
/// the server's batch limit) when the stash runs dry. Used by both the
/// meta-search submit flow and the sandbox capture flow.
Future<TokenTopUpOutcome> topUp({int desired = 10}) async {
final status = await ref.read(searchCreditsRepositoryProvider.future);
if (status.availableCredits <= 0) return TokenTopUpOutcome.noCredits;
final requestCount = min(desired, status.availableCredits);
final result = await ref
.read(searchTokenIssuanceControllerProvider.notifier)
.issue(count: requestCount);
return result != null
? TokenTopUpOutcome.issued
: TokenTopUpOutcome.issuanceFailed;
}
}
@Riverpod(keepAlive: true)
SearchTokenAvailability searchTokenAvailability(Ref ref) =>
SearchTokenAvailability(ref);
@@ -0,0 +1,118 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'search_token_issuance_controller.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(SearchTokenIssuanceController)
final searchTokenIssuanceControllerProvider =
SearchTokenIssuanceControllerProvider._();
final class SearchTokenIssuanceControllerProvider
extends
$NotifierProvider<
SearchTokenIssuanceController,
SearchTokenIssuanceState
> {
SearchTokenIssuanceControllerProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchTokenIssuanceControllerProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchTokenIssuanceControllerHash();
@$internal
@override
SearchTokenIssuanceController create() => SearchTokenIssuanceController();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(SearchTokenIssuanceState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<SearchTokenIssuanceState>(value),
);
}
}
String _$searchTokenIssuanceControllerHash() =>
r'fa821704ab80a12f4649b78bf50060acfd4b5544';
abstract class _$SearchTokenIssuanceController
extends $Notifier<SearchTokenIssuanceState> {
SearchTokenIssuanceState build();
@$mustCallSuper
@override
void runBuild() {
final ref =
this.ref as $Ref<SearchTokenIssuanceState, SearchTokenIssuanceState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<SearchTokenIssuanceState, SearchTokenIssuanceState>,
SearchTokenIssuanceState,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@ProviderFor(searchTokenAvailability)
final searchTokenAvailabilityProvider = SearchTokenAvailabilityProvider._();
final class SearchTokenAvailabilityProvider
extends
$FunctionalProvider<
SearchTokenAvailability,
SearchTokenAvailability,
SearchTokenAvailability
>
with $Provider<SearchTokenAvailability> {
SearchTokenAvailabilityProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchTokenAvailabilityProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchTokenAvailabilityHash();
@$internal
@override
$ProviderElement<SearchTokenAvailability> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
SearchTokenAvailability create(Ref ref) {
return searchTokenAvailability(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(SearchTokenAvailability value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<SearchTokenAvailability>(value),
);
}
}
String _$searchTokenAvailabilityHash() =>
r'4125c2f267684ee6adcd7a174a3d1570a01643a6';
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:logger/logger.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:search_client/search_client.dart';
import 'package:weblibre/features/search_credits/data/search_backend_config.dart';
import 'package:weblibre/features/search_credits/domain/providers/proxy_client.dart';
import 'package:weblibre/features/search_credits/domain/repositories/web_search_settings.dart';
part 'providers.g.dart';
@Riverpod(keepAlive: true)
BackendEndpoints searchBackendEndpoints(Ref ref) {
final routeThroughTor = ref.watch(
webSearchSettingsControllerProvider.select((s) => s.routeThroughTor),
);
return BackendEndpoints.fromOrigin(
routeThroughTor
? SearchBackendConfig.torOriginUri
: SearchBackendConfig.originUri,
);
}
@Riverpod(keepAlive: true)
Logger searchClientLogger(Ref ref) => Logger();
@Riverpod(keepAlive: true)
IssuanceClient issuanceClient(Ref ref) {
return IssuanceClient(
endpoints: ref.watch(searchBackendEndpointsProvider),
logger: ref.watch(searchClientLoggerProvider),
httpClient: ref.watch(searchProxyHttpClientProvider),
);
}
@@ -0,0 +1,140 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'providers.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(searchBackendEndpoints)
final searchBackendEndpointsProvider = SearchBackendEndpointsProvider._();
final class SearchBackendEndpointsProvider
extends
$FunctionalProvider<
BackendEndpoints,
BackendEndpoints,
BackendEndpoints
>
with $Provider<BackendEndpoints> {
SearchBackendEndpointsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchBackendEndpointsProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchBackendEndpointsHash();
@$internal
@override
$ProviderElement<BackendEndpoints> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
BackendEndpoints create(Ref ref) {
return searchBackendEndpoints(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(BackendEndpoints value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<BackendEndpoints>(value),
);
}
}
String _$searchBackendEndpointsHash() =>
r'f7249075bdf7a83271f7f9030dd12a3a9d2bd483';
@ProviderFor(searchClientLogger)
final searchClientLoggerProvider = SearchClientLoggerProvider._();
final class SearchClientLoggerProvider
extends $FunctionalProvider<Logger, Logger, Logger>
with $Provider<Logger> {
SearchClientLoggerProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchClientLoggerProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchClientLoggerHash();
@$internal
@override
$ProviderElement<Logger> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
Logger create(Ref ref) {
return searchClientLogger(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Logger value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Logger>(value),
);
}
}
String _$searchClientLoggerHash() =>
r'58d85a104431de5005a3fd7521afbbbd7a8672f2';
@ProviderFor(issuanceClient)
final issuanceClientProvider = IssuanceClientProvider._();
final class IssuanceClientProvider
extends $FunctionalProvider<IssuanceClient, IssuanceClient, IssuanceClient>
with $Provider<IssuanceClient> {
IssuanceClientProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'issuanceClientProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$issuanceClientHash();
@$internal
@override
$ProviderElement<IssuanceClient> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
IssuanceClient create(Ref ref) {
return issuanceClient(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(IssuanceClient value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<IssuanceClient>(value),
);
}
}
String _$issuanceClientHash() => r'4ef1f8f5a062ffa0f0f0fa3ebfa70c09efac778f';
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:socks5_proxy/socks_client.dart';
import 'package:weblibre/features/search_credits/domain/repositories/web_search_settings.dart';
import 'package:weblibre/features/tor/domain/services/tor_proxy.dart';
part 'proxy_client.g.dart';
/// Resolved Tor SOCKS5 port for search traffic, or `null` when search should
/// route directly. Returns non-null only when the user has enabled the
/// "route search through Tor" toggle AND Tor is currently running with a
/// known SOCKS port.
@Riverpod(keepAlive: true)
int? searchProxyPort(Ref ref) {
final route = ref.watch(
webSearchSettingsControllerProvider.select((s) => s.routeThroughTor),
);
if (!route) return null;
final status = ref.watch(torProxyServiceProvider).value;
if (status == null || !status.isRunning || status.bootstrapProgress < 100) {
return null;
}
return status.socksPort;
}
/// HttpClient used by both WebSocket (via `IOWebSocketChannel.customClient`)
/// and HTTP-based search clients. SOCKS5-routed when Tor toggle is on, plain
/// otherwise. Rebuilt when the proxy port changes.
@Riverpod(keepAlive: true)
HttpClient searchHttpClient(Ref ref) {
final port = ref.watch(searchProxyPortProvider);
final client = HttpClient()
// The default HttpClient has no connection timeout, so a search service
// that is unreachable can stall the UI for ~minute(s) before failing.
// Cap the TCP/TLS handshake at a few seconds so the user sees an error
// quickly and can retry; the WebSocket session itself imposes no
// ceiling on long-running streams once connected.
..connectionTimeout = const Duration(seconds: 25);
if (port != null) {
SocksTCPClient.assignToHttpClient(client, [
ProxySettings(InternetAddress.loopbackIPv4, port),
]);
}
ref.onDispose(() => client.close(force: true));
return client;
}
/// `package:http` Client wrapping [searchHttpClientProvider]. Use for the
/// non-WebSocket parts of the search flow (token issuance, one-shot capture,
/// capture artifact downloads).
@Riverpod(keepAlive: true)
http.Client searchProxyHttpClient(Ref ref) {
final httpClient = ref.watch(searchHttpClientProvider);
// IOClient does not own the HttpClient lifetime here — the underlying
// HttpClient is closed by the searchHttpClientProvider's onDispose. Don't
// close the IOClient on dispose to avoid prematurely tearing down the
// shared HttpClient on rebuild.
return IOClient(httpClient);
}
@@ -0,0 +1,169 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'proxy_client.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Resolved Tor SOCKS5 port for search traffic, or `null` when search should
/// route directly. Returns non-null only when the user has enabled the
/// "route search through Tor" toggle AND Tor is currently running with a
/// known SOCKS port.
@ProviderFor(searchProxyPort)
final searchProxyPortProvider = SearchProxyPortProvider._();
/// Resolved Tor SOCKS5 port for search traffic, or `null` when search should
/// route directly. Returns non-null only when the user has enabled the
/// "route search through Tor" toggle AND Tor is currently running with a
/// known SOCKS port.
final class SearchProxyPortProvider
extends $FunctionalProvider<int?, int?, int?>
with $Provider<int?> {
/// Resolved Tor SOCKS5 port for search traffic, or `null` when search should
/// route directly. Returns non-null only when the user has enabled the
/// "route search through Tor" toggle AND Tor is currently running with a
/// known SOCKS port.
SearchProxyPortProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchProxyPortProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchProxyPortHash();
@$internal
@override
$ProviderElement<int?> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
int? create(Ref ref) {
return searchProxyPort(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(int? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<int?>(value),
);
}
}
String _$searchProxyPortHash() => r'759420a65b9a1375ff9595de2a0dcbf174ae3e79';
/// HttpClient used by both WebSocket (via `IOWebSocketChannel.customClient`)
/// and HTTP-based search clients. SOCKS5-routed when Tor toggle is on, plain
/// otherwise. Rebuilt when the proxy port changes.
@ProviderFor(searchHttpClient)
final searchHttpClientProvider = SearchHttpClientProvider._();
/// HttpClient used by both WebSocket (via `IOWebSocketChannel.customClient`)
/// and HTTP-based search clients. SOCKS5-routed when Tor toggle is on, plain
/// otherwise. Rebuilt when the proxy port changes.
final class SearchHttpClientProvider
extends $FunctionalProvider<HttpClient, HttpClient, HttpClient>
with $Provider<HttpClient> {
/// HttpClient used by both WebSocket (via `IOWebSocketChannel.customClient`)
/// and HTTP-based search clients. SOCKS5-routed when Tor toggle is on, plain
/// otherwise. Rebuilt when the proxy port changes.
SearchHttpClientProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchHttpClientProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchHttpClientHash();
@$internal
@override
$ProviderElement<HttpClient> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
HttpClient create(Ref ref) {
return searchHttpClient(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(HttpClient value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<HttpClient>(value),
);
}
}
String _$searchHttpClientHash() => r'b3aa4b658e99fb580031ac412fabfbeece5fe830';
/// `package:http` Client wrapping [searchHttpClientProvider]. Use for the
/// non-WebSocket parts of the search flow (token issuance, one-shot capture,
/// capture artifact downloads).
@ProviderFor(searchProxyHttpClient)
final searchProxyHttpClientProvider = SearchProxyHttpClientProvider._();
/// `package:http` Client wrapping [searchHttpClientProvider]. Use for the
/// non-WebSocket parts of the search flow (token issuance, one-shot capture,
/// capture artifact downloads).
final class SearchProxyHttpClientProvider
extends $FunctionalProvider<http.Client, http.Client, http.Client>
with $Provider<http.Client> {
/// `package:http` Client wrapping [searchHttpClientProvider]. Use for the
/// non-WebSocket parts of the search flow (token issuance, one-shot capture,
/// capture artifact downloads).
SearchProxyHttpClientProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchProxyHttpClientProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchProxyHttpClientHash();
@$internal
@override
$ProviderElement<http.Client> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
http.Client create(Ref ref) {
return searchProxyHttpClient(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(http.Client value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<http.Client>(value),
);
}
}
String _$searchProxyHttpClientHash() =>
r'08acee399abc5c6960a82365219af6b5a44ba5bd';
@@ -0,0 +1,57 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/account/domain/repositories/account_auth.dart';
import 'package:weblibre/features/search_credits/data/models/search_credits_status.dart';
part 'search_credits_repository.g.dart';
@Riverpod(keepAlive: true)
class SearchCreditsRepository extends _$SearchCreditsRepository {
@override
Future<SearchCreditsStatus> build() async {
final authState = ref.watch(accountAuthRepositoryProvider).value;
if (authState == null || !authState.isSignedIn) {
// Signed-out is not an error; it's a known zero-credit state.
return SearchCreditsStatus.empty;
}
// Don't swallow RPC failures as `SearchCreditsStatus.empty` — that
// renders identically to a real zero balance and would prompt the
// user to "buy more" when the actual fix is to retry. Let errors
// propagate so the AsyncValue carries them and consumers can show an
// error state with a retry CTA.
final client = authState.client!;
final response = await client.rpc('get_my_search_balance').single();
return SearchCreditsStatus.fromJson(response);
}
Future<void> refresh() async {
ref.invalidateSelf();
// Swallow the propagated error — `refresh()` is fire-and-forget from
// pull-to-refresh / lifecycle hooks. The new state (success or error)
// is what consumers re-render from via `ref.watch`.
try {
await future;
} catch (_) {
// intentionally ignored — see comment above
}
}
}
@@ -0,0 +1,58 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'search_credits_repository.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(SearchCreditsRepository)
final searchCreditsRepositoryProvider = SearchCreditsRepositoryProvider._();
final class SearchCreditsRepositoryProvider
extends
$AsyncNotifierProvider<SearchCreditsRepository, SearchCreditsStatus> {
SearchCreditsRepositoryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchCreditsRepositoryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchCreditsRepositoryHash();
@$internal
@override
SearchCreditsRepository create() => SearchCreditsRepository();
}
String _$searchCreditsRepositoryHash() =>
r'e351ac000fa2da31e513f5a9817ac81897199df5';
abstract class _$SearchCreditsRepository
extends $AsyncNotifier<SearchCreditsStatus> {
FutureOr<SearchCreditsStatus> build();
@$mustCallSuper
@override
void runBuild() {
final ref =
this.ref as $Ref<AsyncValue<SearchCreditsStatus>, SearchCreditsStatus>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<SearchCreditsStatus>, SearchCreditsStatus>,
AsyncValue<SearchCreditsStatus>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,41 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/search_credits/data/token_stash.dart';
import 'package:weblibre/features/user/data/providers.dart';
part 'search_token_stash_repository.g.dart';
/// Read-only-shaped stash for the search session: only reserve / commit /
/// release / count / take / clear are safe to call. The issuance controller
/// constructs its own stash with the freshly-fetched `key.version` before
/// calling `stash.add` so token rows are tagged with the exact key the
/// issuer signed against — see [searchTokenIssuanceControllerProvider].
@Riverpod(keepAlive: true)
DriftTokenStash searchTokenStash(Ref ref) {
final db = ref.watch(userDatabaseProvider);
return DriftTokenStash(db.searchTokensDao);
}
@Riverpod(keepAlive: true)
Stream<int> searchTokenStashCount(Ref ref) {
final db = ref.watch(userDatabaseProvider);
return db.searchTokensDao.watchCount();
}
@@ -0,0 +1,102 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'search_token_stash_repository.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Read-only-shaped stash for the search session: only reserve / commit /
/// release / count / take / clear are safe to call. The issuance controller
/// constructs its own stash with the freshly-fetched `key.version` before
/// calling `stash.add` so token rows are tagged with the exact key the
/// issuer signed against — see [searchTokenIssuanceControllerProvider].
@ProviderFor(searchTokenStash)
final searchTokenStashProvider = SearchTokenStashProvider._();
/// Read-only-shaped stash for the search session: only reserve / commit /
/// release / count / take / clear are safe to call. The issuance controller
/// constructs its own stash with the freshly-fetched `key.version` before
/// calling `stash.add` so token rows are tagged with the exact key the
/// issuer signed against — see [searchTokenIssuanceControllerProvider].
final class SearchTokenStashProvider
extends
$FunctionalProvider<DriftTokenStash, DriftTokenStash, DriftTokenStash>
with $Provider<DriftTokenStash> {
/// Read-only-shaped stash for the search session: only reserve / commit /
/// release / count / take / clear are safe to call. The issuance controller
/// constructs its own stash with the freshly-fetched `key.version` before
/// calling `stash.add` so token rows are tagged with the exact key the
/// issuer signed against — see [searchTokenIssuanceControllerProvider].
SearchTokenStashProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchTokenStashProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchTokenStashHash();
@$internal
@override
$ProviderElement<DriftTokenStash> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
DriftTokenStash create(Ref ref) {
return searchTokenStash(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(DriftTokenStash value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<DriftTokenStash>(value),
);
}
}
String _$searchTokenStashHash() => r'e761b254b778f7c4cc7475e0034aa7bec8e126de';
@ProviderFor(searchTokenStashCount)
final searchTokenStashCountProvider = SearchTokenStashCountProvider._();
final class SearchTokenStashCountProvider
extends $FunctionalProvider<AsyncValue<int>, int, Stream<int>>
with $FutureModifier<int>, $StreamProvider<int> {
SearchTokenStashCountProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchTokenStashCountProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchTokenStashCountHash();
@$internal
@override
$StreamProviderElement<int> $createElement($ProviderPointer pointer) =>
$StreamProviderElement(pointer);
@override
Stream<int> create(Ref ref) {
return searchTokenStashCount(ref);
}
}
String _$searchTokenStashCountHash() =>
r'0cef046aad0dc7e0a6e0f717fe1896f8f546d852';
@@ -0,0 +1,66 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:riverpod/experimental/persist.dart';
import 'package:riverpod_annotation/experimental/json_persist.dart';
import 'package:riverpod_annotation/experimental/persist.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:search_backend/search_backend.dart';
import 'package:weblibre/features/search_credits/data/models/web_search_settings.dart';
import 'package:weblibre/features/user/data/providers.dart';
part 'web_search_settings.g.dart';
@Riverpod(keepAlive: true)
@JsonPersist()
class WebSearchSettingsController extends _$WebSearchSettingsController {
void setRouteThroughTor(bool value) {
state = state.copyWith(routeThroughTor: value);
}
void setSearchMode(SearchMode mode) {
state = state.copyWith(searchMode: mode);
}
void setLanguage(String? language) {
state = state.copyWith(language: language);
}
void setRegion(String? region) {
state = state.copyWith(region: region);
}
void setSafeSearch(SafeSearch? safeSearch) {
state = state.copyWith(safeSearch: safeSearch);
}
void setTimeRange(TimeRange? timeRange) {
state = state.copyWith(timeRange: timeRange);
}
@override
WebSearchSettings build() {
persist(
ref.watch(riverpodDatabaseStorageProvider),
key: 'WebSearchSettings',
);
return stateOrNull ?? WebSearchSettings.withDefaults();
}
}
@@ -0,0 +1,106 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'web_search_settings.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(WebSearchSettingsController)
@JsonPersist()
final webSearchSettingsControllerProvider =
WebSearchSettingsControllerProvider._();
@JsonPersist()
final class WebSearchSettingsControllerProvider
extends $NotifierProvider<WebSearchSettingsController, WebSearchSettings> {
WebSearchSettingsControllerProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'webSearchSettingsControllerProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$webSearchSettingsControllerHash();
@$internal
@override
WebSearchSettingsController create() => WebSearchSettingsController();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(WebSearchSettings value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<WebSearchSettings>(value),
);
}
}
String _$webSearchSettingsControllerHash() =>
r'f21a6203fdb8b21c28b0ddd23f1b48768673138e';
@JsonPersist()
abstract class _$WebSearchSettingsControllerBase
extends $Notifier<WebSearchSettings> {
WebSearchSettings build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<WebSearchSettings, WebSearchSettings>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<WebSearchSettings, WebSearchSettings>,
WebSearchSettings,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
// **************************************************************************
// JsonGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
abstract class _$WebSearchSettingsController
extends _$WebSearchSettingsControllerBase {
/// The default key used by [persist].
String get key {
const resolvedKey = "WebSearchSettingsController";
return resolvedKey;
}
/// A variant of [persist], for JSON-specific encoding.
///
/// You can override [key] to customize the key used for storage.
PersistResult persist(
FutureOr<Storage<String, String>> storage, {
String? key,
String Function(WebSearchSettings state)? encode,
WebSearchSettings Function(String encoded)? decode,
StorageOptions options = const StorageOptions(),
}) {
return NotifierPersistX(this).persist<String, String>(
storage,
key: key ?? this.key,
encode: encode ?? $jsonCodex.encode,
decode:
decode ??
(encoded) {
final e = $jsonCodex.decode(encoded);
return WebSearchSettings.fromJson(e as Map<String, Object?>);
},
options: options,
);
}
}