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,62 @@
/*
* 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:fast_equatable/fast_equatable.dart';
class SearchCreditsStatus with FastEquatable {
final int availableCredits;
final int monthlyAllowance;
final DateTime? lastResetAt;
final DateTime? lastIssuanceAt;
final DateTime? currentPeriodEnd;
SearchCreditsStatus({
required this.availableCredits,
this.monthlyAllowance = 0,
this.lastResetAt,
this.lastIssuanceAt,
this.currentPeriodEnd,
});
factory SearchCreditsStatus.fromJson(Map<String, dynamic> json) {
DateTime? parse(Object? v) => (v is String) ? DateTime.parse(v) : null;
return SearchCreditsStatus(
availableCredits: (json['available_credits'] as num?)?.toInt() ?? 0,
monthlyAllowance: (json['monthly_allowance'] as num?)?.toInt() ?? 0,
lastResetAt: parse(json['last_reset_at']),
lastIssuanceAt: parse(json['last_issuance_at']),
currentPeriodEnd: parse(json['current_period_end']),
);
}
// Not `const` because `FastEquatable` carries a cached-hash field that
// disallows const construction. Value-equality from the mixin means
// `SearchCreditsStatus(availableCredits: 0) == SearchCreditsStatus.empty`
// still holds, which is what Riverpod's `select` dedupe cares about.
static final empty = SearchCreditsStatus(availableCredits: 0);
@override
List<Object?> get hashParameters => [
availableCredits,
monthlyAllowance,
lastResetAt,
lastIssuanceAt,
currentPeriodEnd,
];
}
@@ -0,0 +1,80 @@
/*
* 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:copy_with_extension/copy_with_extension.dart';
import 'package:fast_equatable/fast_equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:search_backend/search_backend.dart';
part 'web_search_settings.g.dart';
@CopyWith()
@JsonSerializable(includeIfNull: true, constructor: 'withDefaults')
class WebSearchSettings with FastEquatable {
final bool routeThroughTor;
final SearchMode searchMode;
/// ISO 639-1 language code (e.g. `en`, `de`). `null` means "use backend
/// default" (currently English).
final String? language;
/// ISO 3166-1 alpha-2 region/country code (e.g. `US`, `DE`). `null`
/// means "no region preference" — engines won't apply region boosts.
final String? region;
/// Safe-search level. `null` defers to the server default (moderate).
final SafeSearch? safeSearch;
/// Freshness filter. `null` means "any time".
final TimeRange? timeRange;
WebSearchSettings({
required this.routeThroughTor,
required this.searchMode,
required this.language,
required this.region,
required this.safeSearch,
required this.timeRange,
});
WebSearchSettings.withDefaults({
bool? routeThroughTor,
SearchMode? searchMode,
this.language,
this.region,
this.safeSearch,
this.timeRange,
}) : routeThroughTor = routeThroughTor ?? false,
searchMode = searchMode ?? SearchMode.general;
factory WebSearchSettings.fromJson(Map<String, dynamic> json) =>
_$WebSearchSettingsFromJson(json);
Map<String, dynamic> toJson() => _$WebSearchSettingsToJson(this);
@override
List<Object?> get hashParameters => [
routeThroughTor,
searchMode,
language,
region,
safeSearch,
timeRange,
];
}
@@ -0,0 +1,165 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'web_search_settings.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$WebSearchSettingsCWProxy {
WebSearchSettings routeThroughTor(bool routeThroughTor);
WebSearchSettings searchMode(SearchMode searchMode);
WebSearchSettings language(String? language);
WebSearchSettings region(String? region);
WebSearchSettings safeSearch(SafeSearch? safeSearch);
WebSearchSettings timeRange(TimeRange? timeRange);
/// Creates a new instance with the provided field values.
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `WebSearchSettings(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// WebSearchSettings(...).copyWith(id: 12, name: "My name")
/// ```
WebSearchSettings call({
bool routeThroughTor,
SearchMode searchMode,
String? language,
String? region,
SafeSearch? safeSearch,
TimeRange? timeRange,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfWebSearchSettings.copyWith(...)` or call `instanceOfWebSearchSettings.copyWith.fieldName(value)` for a single field.
class _$WebSearchSettingsCWProxyImpl implements _$WebSearchSettingsCWProxy {
const _$WebSearchSettingsCWProxyImpl(this._value);
final WebSearchSettings _value;
@override
WebSearchSettings routeThroughTor(bool routeThroughTor) =>
call(routeThroughTor: routeThroughTor);
@override
WebSearchSettings searchMode(SearchMode searchMode) =>
call(searchMode: searchMode);
@override
WebSearchSettings language(String? language) => call(language: language);
@override
WebSearchSettings region(String? region) => call(region: region);
@override
WebSearchSettings safeSearch(SafeSearch? safeSearch) =>
call(safeSearch: safeSearch);
@override
WebSearchSettings timeRange(TimeRange? timeRange) =>
call(timeRange: timeRange);
@override
/// Creates a new instance with the provided field values.
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `WebSearchSettings(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// WebSearchSettings(...).copyWith(id: 12, name: "My name")
/// ```
WebSearchSettings call({
Object? routeThroughTor = const $CopyWithPlaceholder(),
Object? searchMode = const $CopyWithPlaceholder(),
Object? language = const $CopyWithPlaceholder(),
Object? region = const $CopyWithPlaceholder(),
Object? safeSearch = const $CopyWithPlaceholder(),
Object? timeRange = const $CopyWithPlaceholder(),
}) {
return WebSearchSettings(
routeThroughTor:
routeThroughTor == const $CopyWithPlaceholder() ||
routeThroughTor == null
? _value.routeThroughTor
// ignore: cast_nullable_to_non_nullable
: routeThroughTor as bool,
searchMode:
searchMode == const $CopyWithPlaceholder() || searchMode == null
? _value.searchMode
// ignore: cast_nullable_to_non_nullable
: searchMode as SearchMode,
language: language == const $CopyWithPlaceholder()
? _value.language
// ignore: cast_nullable_to_non_nullable
: language as String?,
region: region == const $CopyWithPlaceholder()
? _value.region
// ignore: cast_nullable_to_non_nullable
: region as String?,
safeSearch: safeSearch == const $CopyWithPlaceholder()
? _value.safeSearch
// ignore: cast_nullable_to_non_nullable
: safeSearch as SafeSearch?,
timeRange: timeRange == const $CopyWithPlaceholder()
? _value.timeRange
// ignore: cast_nullable_to_non_nullable
: timeRange as TimeRange?,
);
}
}
extension $WebSearchSettingsCopyWith on WebSearchSettings {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfWebSearchSettings.copyWith(...)` or `instanceOfWebSearchSettings.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$WebSearchSettingsCWProxy get copyWith =>
_$WebSearchSettingsCWProxyImpl(this);
}
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
WebSearchSettings _$WebSearchSettingsFromJson(Map<String, dynamic> json) =>
WebSearchSettings.withDefaults(
routeThroughTor: json['routeThroughTor'] as bool?,
searchMode: $enumDecodeNullable(_$SearchModeEnumMap, json['searchMode']),
language: json['language'] as String?,
region: json['region'] as String?,
safeSearch: $enumDecodeNullable(_$SafeSearchEnumMap, json['safeSearch']),
timeRange: $enumDecodeNullable(_$TimeRangeEnumMap, json['timeRange']),
);
Map<String, dynamic> _$WebSearchSettingsToJson(WebSearchSettings instance) =>
<String, dynamic>{
'routeThroughTor': instance.routeThroughTor,
'searchMode': _$SearchModeEnumMap[instance.searchMode]!,
'language': instance.language,
'region': instance.region,
'safeSearch': _$SafeSearchEnumMap[instance.safeSearch],
'timeRange': _$TimeRangeEnumMap[instance.timeRange],
};
const _$SearchModeEnumMap = {
SearchMode.general: 'general',
SearchMode.independentWeb: 'independentWeb',
SearchMode.smallWeb: 'smallWeb',
};
const _$SafeSearchEnumMap = {
SafeSearch.none: 'none',
SafeSearch.moderate: 'moderate',
SafeSearch.strict: 'strict',
};
const _$TimeRangeEnumMap = {
TimeRange.day: 'day',
TimeRange.week: 'week',
TimeRange.month: 'month',
TimeRange.year: 'year',
};
@@ -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/>.
*/
abstract final class SearchBackendConfig {
/// Clearnet origin used when the user has not opted to route search through
/// Tor. Must be a normal HTTPS URL (or HTTP for dev).
static const searchBackendOrigin = String.fromEnvironment(
'SEARCH_BACKEND_ORIGIN',
defaultValue: 'https://search.weblibre.eu',
);
/// Origin used when the user opts to route search through Tor. Should be
/// the WebLibre search service's onion address so the Tor circuit
/// terminates inside the Tor network instead of exiting back to the
/// clearnet. Falls back to the clearnet origin when no onion address is
/// configured at build time.
static const searchBackendOriginTor = String.fromEnvironment(
'SEARCH_BACKEND_ORIGIN_TOR',
defaultValue:
'http://eyipgwt32zaejr2xwblaswp2ur4qikapofunbqus5dklvf7jxkncirad.onion',
);
static Uri get originUri => Uri.parse(searchBackendOrigin);
static Uri get torOriginUri => Uri.parse(searchBackendOriginTor);
}
@@ -0,0 +1,77 @@
/*
* 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:typed_data';
import 'package:search_client/search_client.dart';
import 'package:weblibre/features/user/data/database/daos/search_tokens.dart';
/// Drift-backed [TokenStash]. The optional [issuerKeyVersion] is only used
/// by [add], and only the issuance controller is supposed to call that.
/// Read-only consumers (the search session: reserve / commit / release /
/// count / clear) can leave it null; calling [add] on a stash constructed
/// without a key version is a programmer error and throws.
class DriftTokenStash implements TokenStash {
final SearchTokensDao dao;
final String? issuerKeyVersion;
DriftTokenStash(this.dao, {this.issuerKeyVersion});
@override
Future<void> add(List<Uint8List> tokens) {
final version = issuerKeyVersion;
if (version == null) {
throw StateError(
'DriftTokenStash.add called without an issuerKeyVersion — '
'construct a stash with the version returned by '
'IssuanceClient.fetchPublicKey() before issuing tokens.',
);
}
return dao.addTokens(tokens, issuerKeyVersion: version);
}
@override
Future<ReservedStashToken?> reserveOne() async {
final reserved = await dao.reserveOne();
if (reserved == null) return null;
return ReservedStashToken(id: reserved.id, token: reserved.token);
}
@override
Future<void> commitReserved(int id) => dao.commitReserved(id);
@override
Future<void> releaseReserved(int id) => dao.releaseReserved(id);
@override
Future<Uint8List?> takeOne() async {
final reserved = await reserveOne();
if (reserved == null) return null;
await commitReserved(reserved.id);
return reserved.token;
}
@override
Future<int> count() => dao.count();
@override
Future<void> clear() async {
await dao.clear();
}
}
@@ -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,
);
}
}
@@ -0,0 +1,202 @@
/*
* 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:math';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:timeago/timeago.dart' as timeago;
import 'package:url_launcher/url_launcher.dart';
import 'package:weblibre/features/account/data/supabase_config.dart';
import 'package:weblibre/features/search_credits/domain/controllers/search_token_issuance_controller.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/settings/presentation/widgets/settings_content_card.dart';
class SearchCreditsSection extends HookConsumerWidget {
final bool embedded;
const SearchCreditsSection({super.key, this.embedded = false});
@override
Widget build(BuildContext context, WidgetRef ref) {
final theme = Theme.of(context);
final creditsAsync = ref.watch(searchCreditsRepositoryProvider);
final stashAsync = ref.watch(searchTokenStashCountProvider);
final issuance = ref.watch(searchTokenIssuanceControllerProvider);
// Refresh the credits balance whenever the app returns to the
// foreground. `launchUrl` for the checkout flow returns immediately,
// long before the purchase completes, so refreshing right after the
// tap would just re-read a stale 0. The user coming back into the
// app is the signal that something may have changed.
useOnAppLifecycleStateChange((previous, current) async {
if (current == AppLifecycleState.resumed) {
await ref.read(searchCreditsRepositoryProvider.notifier).refresh();
}
});
final creditsValue = creditsAsync.value;
final creditsError = creditsAsync.hasError && !creditsAsync.isLoading;
final credits = creditsValue?.availableCredits ?? 0;
final monthlyAllowance = creditsValue?.monthlyAllowance ?? 0;
final stash = stashAsync.value ?? 0;
final lastIssuanceAt = creditsValue?.lastIssuanceAt;
final currentPeriodEnd = creditsValue?.currentPeriodEnd;
final isRequesting = issuance is SearchTokenIssuanceRequesting;
final canIssue =
credits > 0 &&
(issuance is SearchTokenIssuanceIdle ||
issuance is SearchTokenIssuanceFailed);
Future<void> openBuyMore() async {
final uri = Uri.parse('${SupabaseConfig.accountWebUrl}?view=search-pack');
// No refresh here — launchUrl returns as soon as the browser opens,
// not when the user finishes checkout. The app-lifecycle listener
// above handles the refresh on return.
await launchUrl(uri, mode: LaunchMode.inAppBrowserView);
}
Future<void> onIssue() async {
final count = min(25, credits);
await ref
.read(searchTokenIssuanceControllerProvider.notifier)
.issue(count: count);
}
final isEmpty = credits == 0 && stash == 0;
final content = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListTile(
leading: Icon(
creditsError ? Icons.error_outline : Icons.search,
color: creditsError
? theme.colorScheme.error
: theme.colorScheme.primary,
),
title: Text(
creditsError ? 'Could not load credits' : 'Search credits',
),
subtitle: creditsError
? const Text('Check your connection and tap refresh to retry.')
: isEmpty
? const Text('Buy a search pack to get started')
: Text(
monthlyAllowance > 0
? 'Credits: $credits / $monthlyAllowance · '
'Stashed tokens: $stash'
: 'Credits: $credits · Stashed tokens: $stash',
),
trailing: IconButton(
icon: const Icon(Icons.refresh),
tooltip: 'Refresh',
onPressed: () async {
await ref
.read(searchCreditsRepositoryProvider.notifier)
.refresh();
},
),
),
if (currentPeriodEnd != null && monthlyAllowance > 0)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
child: Text(
'Resets on '
'${DateFormat.yMMMd().format(currentPeriodEnd.toLocal())}',
style: theme.textTheme.bodySmall,
),
),
if (lastIssuanceAt != null)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text(
'Last issuance: ${timeago.format(lastIssuanceAt)} '
'(${DateFormat.yMMMd().add_Hm().format(lastIssuanceAt.toLocal())})',
style: theme.textTheme.bodySmall,
),
),
if (isRequesting)
const Padding(
padding: EdgeInsets.fromLTRB(16, 0, 16, 12),
child: Row(
children: [
SizedBox(
height: 16,
width: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
SizedBox(width: 12),
Text('Requesting tokens...'),
],
),
),
if (issuance is SearchTokenIssuanceFailed)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
child: Text(
'Token issuance failed: ${issuance.error}',
style: TextStyle(color: theme.colorScheme.error),
),
),
if (issuance is SearchTokenIssuanceNeedsReauth)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
child: Text(
'Please sign in again to request tokens.',
style: TextStyle(color: theme.colorScheme.error),
),
),
const Divider(height: 1),
if (isEmpty)
ListTile(
leading: const Icon(Icons.shopping_cart_outlined),
title: const Text('Buy a search pack'),
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
onTap: openBuyMore,
)
else ...[
ListTile(
leading: const Icon(Icons.download_for_offline_outlined),
enabled: canIssue,
title: const Text('Get tokens'),
subtitle: credits > 0
? Text('Request ${min(25, credits)} tokens')
: const Text('No credits remaining'),
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
onTap: canIssue ? onIssue : null,
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.shopping_cart_outlined),
title: const Text('Buy more'),
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
onTap: openBuyMore,
),
],
],
);
return SettingsContentCard(embedded: embedded, child: content);
}
}