Merge upstream/dev (86 commits) into tth
build / ci-image (push) Successful in 10s
build / build (push) Failing after 4m27s

Upstream redesigned the chat composer (bubble, round +/send button,
ChatComposerQuote for the reply preview); our terminal theme had tweaked
the old layout. Took upstream's structure and re-applied the terminal
look to the new widgets: compact panel padding, square bubble, square
button, square and one-line-low reply quote. The terminal reply padding
in channel_chat_screen now lives in ChatComposerQuote, so DMs get it too.

Also fixed for the merge:
- mesh_ui: AvatarCircle uses upstream's avatarInitials() (nullable); the
  terminal glyph falls back to the person icon like upstream does;
- chat_screen: upstream split maxMessageRetries into direct/flood limits,
  the terminal line now shows the bubble's maxSendAttempts;
- test/screens/copy_messages_test.dart: the 1x1 PNG had a bad IDAT CRC.
  Its async decode failure leaked into the next test; upstream's real
  flutter_langdetect hides that by timing, our stub (instant init) does
  not, so the DM test failed ~3 of 5 runs. Replaced with a valid PNG.

Checked in the CI image (Flutter 3.47.9): flutter analyze lib test clean;
flutter test all green except settings_reveal_test "hides Image Messages
sub-options", which fails the same way on plain upstream/dev.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-23 12:43:57 +01:00
commit 63907cb17d
210 files changed
+47623 -4900

No files matched your search

+50 -3
View File
@@ -1,8 +1,11 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../models/app_settings.dart';
import '../models/custom_theme.dart';
import '../models/send_attempt_plan.dart';
import '../models/holiday_schedule.dart';
import '../models/image_codec_support.dart';
import '../models/translation_support.dart';
@@ -135,6 +138,10 @@ class AppSettingsService extends ChangeNotifier {
await updateSettings(_settings.copyWith(regionOnHopsLine: value));
}
Future<void> setShowCompressionIndicator(bool value) async {
await updateSettings(_settings.copyWith(showCompressionIndicator: value));
}
Future<void> setMapCacheBounds(Map<String, double>? value) async {
await updateSettings(_settings.copyWith(mapCacheBounds: value));
}
@@ -228,8 +235,30 @@ class AppSettingsService extends ChangeNotifier {
);
}
Future<void> setMaxMessageRetries(int value) async {
await updateSettings(_settings.copyWith(maxMessageRetries: value));
Future<void> setDirectRetries(int value) async {
await updateSettings(
_settings.copyWith(directRetries: SendAttemptPlan.clampDirect(value)),
);
}
Future<void> setFloodRetries(int value) async {
await updateSettings(
_settings.copyWith(floodRetries: SendAttemptPlan.clampFlood(value)),
);
}
Future<void> setLoginAttempts(int value) async {
await updateSettings(
_settings.copyWith(loginAttempts: SendAttemptPlan.clampLogin(value)),
);
}
Future<void> setClockSyncAfterLogin(bool value) async {
await updateSettings(_settings.copyWith(clockSyncAfterLogin: value));
}
Future<void> setLoginPasswordAutofocus(bool value) async {
await updateSettings(_settings.copyWith(loginPasswordAutofocus: value));
}
Future<void> setChannelMinHopsEnabled(bool value) async {
@@ -714,13 +743,31 @@ class AppSettingsService extends ChangeNotifier {
Future<void> resetRoutingSettingsToDefault() async {
await updateSettings(
_settings.copyWith(
clearPathOnMaxRetry: false,
autoRouteRotationEnabled: true,
maxRouteWeight: AppSettings.defaultMaxRouteWeight,
initialRouteWeight: AppSettings.defaultInitialRouteWeight,
routeWeightSuccessIncrement:
AppSettings.defaultRouteWeightSuccessIncrement,
routeWeightFailureDecrement:
AppSettings.defaultRouteWeightFailureDecrement,
maxMessageRetries: AppSettings.defaultMaxMessageRetries,
directRetries: AppSettings.defaultDirectRetries,
floodRetries: AppSettings.defaultFloodRetries,
channelMinHopsEnabled: false,
channelMinHops: 2,
channelMinHopsRetries: 1,
channelMinHopsCountRepeaters: false,
),
);
}
Future<void> resetRepeaterRoomSettingsToDefault() async {
await updateSettings(
_settings.copyWith(
clockSyncAfterLogin: false,
loginPasswordAutofocus: false,
autoFetchRepeaterSettings: false,
loginAttempts: AppSettings.defaultLoginAttempts,
),
);
}
+22 -10
View File
@@ -6,6 +6,27 @@ import '../l10n/locale_tag.dart';
import '../utils/platform_info.dart';
class BackgroundService {
/// Options for the service that keeps the radio link alive in the
/// background.
///
/// The radio link lives in the app process; once the user swipes the app
/// away it is gone, so a lingering "connected" notification (or an
/// automatic restart) would only be misleading. Swiping away stops the
/// service through `android:stopWithTask="true"` in AndroidManifest.xml.
///
/// `stopWithTask` must stay unset here: in flutter_foreground_task (9.2 to
/// 11.0 at least) the option does not watch the task but stops the service
/// as soon as no activity is resumed, which is every time the app goes to
/// the background or the screen turns off. Android then caches and freezes
/// the process, the Bluetooth link drops and the low-memory killer ends it.
@visibleForTesting
static final ForegroundTaskOptions taskOptions = ForegroundTaskOptions(
eventAction: ForegroundTaskEventAction.repeat(5000),
autoRunOnBoot: false,
allowWifiLock: false,
allowAutoRestart: false,
);
bool _initialized = false;
String? Function()? _languageOverrideProvider;
@@ -30,16 +51,7 @@ class BackgroundService {
showNotification: false,
playSound: false,
),
foregroundTaskOptions: ForegroundTaskOptions(
eventAction: ForegroundTaskEventAction.repeat(5000),
autoRunOnBoot: false,
allowWifiLock: false,
// The radio link lives in the app process; once the user swipes the
// app away it is gone, so a lingering "connected" notification (or
// an automatic restart) would only be misleading.
allowAutoRestart: false,
stopWithTask: true,
),
foregroundTaskOptions: taskOptions,
);
_initialized = true;
}
+3 -1
View File
@@ -23,6 +23,7 @@ const String _encryptedBackupFormat = 'meshcore-open-encrypted-backup';
const List<String> _contactPreferencePrefixes = [
'contacts',
'contact_groups',
'contact_added_at_',
'contact_smaz_',
'contact_cyr2lat_',
'contact_url_images_',
@@ -1094,7 +1095,8 @@ class BackupService {
return true;
}
if (items.contains(BackupItem.contacts) &&
key.startsWith('contacts$devicePrefix')) {
(key.startsWith('contacts$devicePrefix') ||
key.startsWith('contact_added_at_$devicePrefix'))) {
return true;
}
if (items.contains(BackupItem.perContactSettings) &&
+24 -5
View File
@@ -871,14 +871,33 @@ class ImageCodecCancelled implements Exception {
String toString() => 'Image processing stopped.';
}
/// Whether this build can run the image codec at all.
///
/// False on web and in a build made with `scripts/onnx.sh off`, where
/// `flutter_onnxruntime` is the pure-Dart stub whose [OnnxRuntime] constructor
/// throws [UnsupportedError]. The real constructor has no side effects.
final bool imageCodecRuntimeAvailable = _probeOnnxRuntime();
bool _probeOnnxRuntime() {
if (kIsWeb) {
return false;
}
try {
OnnxRuntime();
return true;
} on UnsupportedError {
return false;
}
}
/// Factory used by the codec worker isolate.
///
/// Returns `null` on web, where there is no local model file and no isolate.
/// Everywhere else it returns the real [OnnxImageCodecBackend]; the session
/// turns a `null` here into an [ImageCodecUnimplemented], which the service
/// surfaces as `lastError` and maps to `ImageCodecAvailability.unavailable`.
/// Returns `null` when [imageCodecRuntimeAvailable] is false. Everywhere else
/// it returns the real [OnnxImageCodecBackend]; the session turns a `null`
/// here into an [ImageCodecUnimplemented], which the service surfaces as
/// `lastError` and maps to `ImageCodecAvailability.unavailable`.
ImageCodecBackend? createImageCodecBackend() {
if (kIsWeb) {
if (!imageCodecRuntimeAvailable) {
return null;
}
return OnnxImageCodecBackend();
+9 -3
View File
@@ -8,7 +8,8 @@ import '../models/image_codec_support.dart';
import '../utils/app_logger.dart';
import '../widgets/image_send_codec_binding.dart';
import 'app_settings_service.dart';
import 'image_codec_backend.dart' show kImageCodecBitstreamPathAvailable;
import 'image_codec_backend.dart'
show imageCodecRuntimeAvailable, kImageCodecBitstreamPathAvailable;
import 'image_codec_file_store.dart';
import 'image_codec_session.dart';
import 'image_codec_settings_store.dart';
@@ -177,9 +178,10 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
/// Why [availability] is `unavailable`, or null when it is not.
///
/// EXACTLY THREE CAUSES, all of them permanent properties of the build or the
/// EXACTLY FOUR CAUSES, all of them permanent properties of the build or the
/// platform, none of them fixable by the user:
/// * web, which has no native inference runtime;
/// * a build made without ONNX Runtime ([imageCodecRuntimeAvailable]);
/// * a build compiled without the entropy path
/// ([kImageCodecBitstreamPathAvailable]);
/// * a backend that failed to load.
@@ -194,6 +196,10 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
return 'The image codec needs a native inference runtime, which the web '
'build does not have.';
}
if (!imageCodecRuntimeAvailable) {
return 'This build was made without ONNX Runtime, so it cannot send or '
'show image messages.';
}
if (!kImageCodecBitstreamPathAvailable) {
return 'This build ships the image decoder only. Encoding and decoding a '
'bitstream also needs the entropy-side graph and the rANS coder, '
@@ -510,7 +516,7 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
/// works. [canEncode]/[canDecode] additionally require the entropy path.
bool get canRunInference {
final model = selectedModel;
return !kIsWeb &&
return imageCodecRuntimeAvailable &&
!_backendMissing &&
model != null &&
model.localPath.isNotEmpty;
+66 -14
View File
@@ -1,12 +1,15 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart';
import 'package:crypto/crypto.dart';
import '../connector/meshcore_protocol.dart';
import '../models/contact.dart';
import '../models/message.dart';
import '../models/path_selection.dart';
import '../models/send_attempt_plan.dart';
import 'app_settings_service.dart';
import 'app_debug_log_service.dart';
@@ -58,7 +61,7 @@ class RetryServiceConfig {
final PathSelection? Function(
String contactKey,
int attemptIndex,
int maxRetries,
int directRetries,
List<PathSelection> recentSelections,
)?
selectRetryPath;
@@ -88,8 +91,21 @@ class MessageRetryService extends ChangeNotifier {
/// shared globally; cap at 6 to leave two slots of headroom.
static const int _maxGlobalInFlight = 6;
int _maxRetries = 5;
int get maxRetries => _maxRetries;
int? _directOverride;
int? _floodOverride;
bool? _rotateOverride;
/// Pins both limits and turns rotation off. Tests use this to send a fixed
/// number of attempts on the contact's current path.
void setMaxRetries(int value) {
final attempts = value < 1 ? 1 : value;
_directOverride = attempts;
_floodOverride = attempts.clamp(
SendAttemptPlan.minFloodRetries,
SendAttemptPlan.maxFloodRetries,
);
_rotateOverride = false;
}
final Map<String, Timer> _timeoutTimers = {};
final Map<String, Message> _pendingMessages = {};
@@ -110,6 +126,7 @@ class MessageRetryService extends ChangeNotifier {
final Set<String> _activeMessages = {};
final Set<String> _resolvedMessages = {};
final Map<String, String> _expectedHashToMessageId = {};
final Map<String, int> _attemptLimits = {};
RetryServiceConfig? _config;
@@ -123,8 +140,26 @@ class MessageRetryService extends ChangeNotifier {
_config = config;
}
void setMaxRetries(int value) {
_maxRetries = value.clamp(2, 10);
SendAttemptPlan _planFor(Contact contact) {
final settings = _config?.appSettingsService?.settings;
final direct =
_directOverride ??
settings?.directRetries ??
SendAttemptPlan.defaultDirectRetries;
final flood =
_floodOverride ??
settings?.floodRetries ??
SendAttemptPlan.defaultFloodRetries;
final rotateFlag =
_rotateOverride ?? settings?.autoRouteRotationEnabled ?? true;
return SendAttemptPlan(
directRetries: direct,
floodRetries: flood,
rotateRoutes:
rotateFlag &&
contact.pathOverride == null &&
_config?.selectRetryPath != null,
);
}
/// Compute expected ACK hash using same algorithm as firmware:
@@ -169,6 +204,7 @@ class MessageRetryService extends ChangeNotifier {
String? translationModelId,
Uint8List? pathBytes,
int? pathLength,
bool isSmazCompressed = false,
}) async {
final messageId = const Uuid().v4();
final resolved = resolvePathSelection(contact);
@@ -176,6 +212,9 @@ class MessageRetryService extends ChangeNotifier {
pathBytes ?? Uint8List.fromList(resolved.pathBytes);
final messagePathLength =
pathLength ?? (resolved.useFlood ? -1 : resolved.hopCount);
_attemptLimits[messageId] = _planFor(
contact,
).attemptLimit(floodPath: messagePathLength < 0);
final message = Message(
senderKey: contact.publicKey,
text: text,
@@ -184,6 +223,7 @@ class MessageRetryService extends ChangeNotifier {
translationModelId: translationModelId,
timestamp: DateTime.now(),
isOutgoing: true,
isSmazCompressed: isSmazCompressed,
status: MessageStatus.pending,
messageId: messageId,
retryCount: 0,
@@ -289,23 +329,27 @@ class MessageRetryService extends ChangeNotifier {
PathSelection? _selectPathForAttempt(Message message, Contact contact) {
final config = _config;
if (config == null) return null;
final autoRotationEnabled =
config.appSettingsService?.settings.autoRouteRotationEnabled == true;
if (!autoRotationEnabled ||
contact.pathOverride != null ||
config.selectRetryPath == null) {
final plan = _planFor(contact);
if (!plan.rotateRoutes || config.selectRetryPath == null) {
return null;
}
final floodFrom = plan.floodFromAttempt;
final recentSelections = List<PathSelection>.from(
_attemptPathHistory[message.messageId] ?? const <PathSelection>[],
);
return config.selectRetryPath!(
final selection = config.selectRetryPath!(
contact.publicKeyHex,
message.retryCount,
maxRetries,
floodFrom ?? (1 << 30),
recentSelections,
);
if (floodFrom != null && message.retryCount >= floodFrom) {
return selection != null && selection.useFlood
? selection
: const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
}
return selection;
}
void _recordAttemptPathHistory(String messageId, PathSelection selection) {
@@ -626,6 +670,7 @@ class MessageRetryService extends ChangeNotifier {
_pendingMessages.remove(messageId);
_pendingContacts.remove(messageId);
_attemptPathHistory.remove(messageId);
_attemptLimits.remove(messageId);
_deferredRouteFailures.remove(messageId);
_timeoutTimers.remove(messageId);
_resolvedMessages.remove(messageId);
@@ -657,9 +702,16 @@ class MessageRetryService extends ChangeNotifier {
tag: 'AckHash',
);
if (message.retryCount < maxRetries - 1 &&
final limit =
_attemptLimits[messageId] ??
_planFor(
contact,
).attemptLimit(floodPath: resolvePathSelection(contact).useFlood);
if (message.retryCount < limit - 1 &&
_textFitsAttempt(message, contact, message.retryCount + 1)) {
final backoffMs = 1000 * (1 << message.retryCount);
// Cap the shift so a high retry limit does not wait for minutes.
final shift = message.retryCount.clamp(0, 5);
final backoffMs = 1000 * (1 << shift);
if (selection != null) {
_deferredRouteFailures.putIfAbsent(messageId, () => []).add((
+117 -27
View File
@@ -180,7 +180,9 @@ class NotificationService {
// connection whose async subscription can throw an unhandled
// SocketException when the bus socket is missing (e.g. running as
// root or inside a container without a session bus).
if (PlatformInfo.isLinux && !_isDbusSessionAvailable()) {
if (PlatformInfo.isLinux &&
defaultTargetPlatform == TargetPlatform.linux &&
!_isDbusSessionAvailable()) {
debugPrint('Skipping notification init: D-Bus session bus unavailable');
return;
}
@@ -250,11 +252,97 @@ class NotificationService {
// Cached "are we allowed to post notifications" result. Null = not yet
// determined. Avoids calling _notifications.show() when it would only throw
// "You must request notifications permissions first" (every web build).
// Android denials are never cached so a later grant in system settings is
// picked up without restarting the app.
// Denials are never cached so a later grant in system settings is picked up
// without restarting the app, and [hasNotificationPermission] refreshes or
// clears [_canNotify] whenever live OS permission is checked.
bool? _canNotify;
static const _permissionRequestedKey = 'notification_permission_requested';
@visibleForTesting
Future<bool> Function()? permissionCheckerForTest;
@visibleForTesting
Future<bool> Function()? permissionRequesterForTest;
@visibleForTesting
Future<bool> ensureCanNotifyForTest() => _ensureCanNotify();
@visibleForTesting
bool? get canNotifyCacheForTest => _canNotify;
@visibleForTesting
void resetForTest() {
_canNotify = null;
_isInitialized = false;
permissionCheckerForTest = null;
permissionRequesterForTest = null;
}
T? _resolvePlugin<T extends FlutterLocalNotificationsPlatform>() {
try {
return _notifications.resolvePlatformSpecificImplementation<T>();
} catch (_) {
return null;
}
}
static bool _isDarwinPermissionGranted(NotificationsEnabledOptions? options) {
if (options == null) return false;
return options.isEnabled ||
options.isProvisionalEnabled ||
options.isAlertEnabled ||
options.isSoundEnabled ||
options.isBadgeEnabled;
}
/// Queries the live OS notification permission state without returning a
/// stale cached grant. Updates [_canNotify] so [_ensureCanNotify] reflects
/// permissions revoked in system settings.
Future<bool> hasNotificationPermission() {
final testChecker = permissionCheckerForTest;
if (testChecker != null) {
return testChecker().then((enabled) {
if (!kIsWeb) {
_canNotify = enabled ? true : null;
}
return enabled;
});
}
if (kIsWeb) return SynchronousFuture<bool>(true);
final androidPlugin =
_resolvePlugin<AndroidFlutterLocalNotificationsPlugin>();
if (androidPlugin != null) {
return androidPlugin.areNotificationsEnabled().then((value) {
final enabled = value ?? false;
_canNotify = enabled ? true : null;
return enabled;
});
}
final iosPlugin = _resolvePlugin<IOSFlutterLocalNotificationsPlugin>();
if (iosPlugin != null) {
return iosPlugin.checkPermissions().then((options) {
final enabled = _isDarwinPermissionGranted(options);
_canNotify = enabled ? true : null;
return enabled;
});
}
final macPlugin = _resolvePlugin<MacOSFlutterLocalNotificationsPlugin>();
if (macPlugin != null) {
return macPlugin.checkPermissions().then((options) {
final enabled = _isDarwinPermissionGranted(options);
_canNotify = enabled ? true : null;
return enabled;
});
}
_canNotify = true;
return SynchronousFuture<bool>(true);
}
Future<bool> _ensureCanNotify() async {
if (!await _ensureInitialized()) return false;
final cached = _canNotify;
@@ -264,50 +352,52 @@ class NotificationService {
// Skip silently instead of logging an error per incoming message.
if (kIsWeb) return _canNotify = false;
// On Android 13+ notifications require an explicit grant; reflect the real
// OS state so we don't spam failed show() calls when denied.
final androidPlugin = _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
if (androidPlugin != null) {
final enabled = await androidPlugin.areNotificationsEnabled() ?? false;
if (enabled) _canNotify = true;
return enabled;
}
// iOS/macOS request permission during initialize(); desktop has no gate.
return _canNotify = true;
return hasNotificationPermission();
}
Future<bool> requestPermissions() async {
final testRequester = permissionRequesterForTest;
if (testRequester != null) {
final granted = await testRequester();
if (!kIsWeb) {
_canNotify = granted ? true : null;
}
return granted;
}
if (!_isInitialized) {
await initialize();
}
// Request Android 13+ notification permission
final androidPlugin = _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
final androidPlugin =
_resolvePlugin<AndroidFlutterLocalNotificationsPlugin>();
if (androidPlugin != null) {
final granted = await androidPlugin.requestNotificationsPermission();
if (granted == true) _canNotify = true;
_canNotify = (granted == true) ? true : null;
return granted ?? false;
}
// iOS permissions are requested during initialization
final iosPlugin = _notifications
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>();
final iosPlugin = _resolvePlugin<IOSFlutterLocalNotificationsPlugin>();
if (iosPlugin != null) {
final granted = await iosPlugin.requestPermissions(
alert: true,
badge: true,
sound: true,
);
if (granted == true) _canNotify = true;
_canNotify = (granted == true) ? true : null;
return granted ?? false;
}
final macPlugin = _resolvePlugin<MacOSFlutterLocalNotificationsPlugin>();
if (macPlugin != null) {
final granted = await macPlugin.requestPermissions(
alert: true,
badge: true,
sound: true,
);
_canNotify = (granted == true) ? true : null;
return granted ?? false;
}
+7 -6
View File
@@ -259,18 +259,19 @@ class PathHistoryService extends ChangeNotifier {
/// Route for one send attempt of a message to [contactPubKeyHex].
///
/// The last attempt always floods. Otherwise a known route is drawn by
/// Thompson sampling over faded delivery stats, weighted by how well it
/// fits [context]; routes used for this message's recent attempts score
/// lower so retries usually try something different.
/// Attempts before [directRetries] draw a known route by Thompson sampling
/// over faded delivery stats, weighted by how well it fits [context];
/// routes used for this message's recent attempts score lower so retries
/// usually try something different. From [directRetries] on, the attempt
/// floods. [directRetries] of 0 floods immediately.
PathSelection selectPathForAttempt(
String contactPubKeyHex, {
required int attemptIndex,
required int maxRetries,
required int directRetries,
List<PathSelection> recentSelections = const [],
RouteContext context = RouteContext.unknown,
}) {
if (maxRetries <= 0 || attemptIndex >= maxRetries - 1) {
if (directRetries <= 0 || attemptIndex >= directRetries) {
return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
}
+82 -10
View File
@@ -6,6 +6,13 @@ import '../storage/prefs_manager.dart';
import '../storage/history_store.dart';
import '../utils/app_logger.dart';
/// Per-repeater clock sync, on top of the app-wide default.
///
/// A missing entry follows the Repeaters and Rooms setting. `true` and
/// `false` in the saved map are explicit On and Off from before that choice
/// existed, and they keep winning over the global default.
enum RepeaterClockSyncOverride { followDefault, on, off }
class StorageService {
static const String _pathHistoryPrefix = 'path_history_';
static const String _pendingMessagesKey = 'pending_messages';
@@ -29,36 +36,101 @@ class StorageService {
? '$_pathHistoryPrefix$contactPubKeyHex'
: '$_pathHistoryPrefix${_publicKeyHex}_$contactPubKeyHex';
Future<Map<String, bool>> _loadRepeaterAutoClockSyncAfterLogin() async {
Future<Map<String, RepeaterClockSyncOverride>>
_loadRepeaterClockSyncOverrides() async {
final prefs = PrefsManager.instance;
final jsonStr = prefs.getString(_repeaterAutoClockSyncAfterLoginKey);
if (jsonStr == null) return {};
try {
final json = jsonDecode(jsonStr) as Map<String, dynamic>;
return json.map((key, value) => MapEntry(key, value == true));
final overrides = <String, RepeaterClockSyncOverride>{};
for (final entry in json.entries) {
final override = switch (entry.value) {
true || 'on' => RepeaterClockSyncOverride.on,
false || 'off' => RepeaterClockSyncOverride.off,
_ => RepeaterClockSyncOverride.followDefault,
};
if (override != RepeaterClockSyncOverride.followDefault) {
overrides[entry.key] = override;
}
}
return overrides;
} catch (e) {
return {};
}
}
Future<void> _saveRepeaterClockSyncOverrides(
Map<String, RepeaterClockSyncOverride> overrides,
) async {
final prefs = PrefsManager.instance;
final stored = <String, bool>{
for (final entry in overrides.entries)
if (entry.value == RepeaterClockSyncOverride.on)
entry.key: true
else if (entry.value == RepeaterClockSyncOverride.off)
entry.key: false,
};
if (stored.isEmpty) {
await prefs.remove(_repeaterAutoClockSyncAfterLoginKey);
return;
}
await prefs.setString(
_repeaterAutoClockSyncAfterLoginKey,
jsonEncode(stored),
);
}
Future<RepeaterClockSyncOverride> getRepeaterClockSyncOverride(
String repeaterPubKeyHex,
) async {
final overrides = await _loadRepeaterClockSyncOverrides();
return overrides[repeaterPubKeyHex] ??
RepeaterClockSyncOverride.followDefault;
}
/// Whether this repeater should receive `clock sync` after login.
///
/// An explicit per-repeater choice wins. Otherwise [globalDefault] applies.
Future<bool> repeaterClockSyncAfterLogin(
String repeaterPubKeyHex, {
required bool globalDefault,
}) async {
return switch (await getRepeaterClockSyncOverride(repeaterPubKeyHex)) {
RepeaterClockSyncOverride.followDefault => globalDefault,
RepeaterClockSyncOverride.on => true,
RepeaterClockSyncOverride.off => false,
};
}
Future<void> setRepeaterClockSyncOverride(
String repeaterPubKeyHex,
RepeaterClockSyncOverride override,
) async {
final overrides = await _loadRepeaterClockSyncOverrides();
if (override == RepeaterClockSyncOverride.followDefault) {
overrides.remove(repeaterPubKeyHex);
} else {
overrides[repeaterPubKeyHex] = override;
}
await _saveRepeaterClockSyncOverrides(overrides);
}
Future<bool> getRepeaterAutoClockSyncAfterLoginEnabled(
String repeaterPubKeyHex,
) async {
final settings = await _loadRepeaterAutoClockSyncAfterLogin();
return settings[repeaterPubKeyHex] ?? false;
return repeaterClockSyncAfterLogin(repeaterPubKeyHex, globalDefault: false);
}
Future<void> setRepeaterAutoClockSyncAfterLoginEnabled(
String repeaterPubKeyHex,
bool enabled,
) async {
final prefs = PrefsManager.instance;
final settings = await _loadRepeaterAutoClockSyncAfterLogin();
settings[repeaterPubKeyHex] = enabled;
final jsonStr = jsonEncode(settings);
await prefs.setString(_repeaterAutoClockSyncAfterLoginKey, jsonStr);
await setRepeaterClockSyncOverride(
repeaterPubKeyHex,
enabled ? RepeaterClockSyncOverride.on : RepeaterClockSyncOverride.off,
);
}
Future<void> savePathHistory(
+100 -16
View File
@@ -39,11 +39,14 @@ class TranslationDownloadCancelled implements Exception {
class TranslationService extends ChangeNotifier {
final AppSettingsService _appSettingsService;
final TranslationFileStore _fileStore;
final http.Client Function() _newClient;
TranslationService(
this._appSettingsService, {
TranslationFileStore? fileStore,
}) : _fileStore = fileStore ?? TranslationFileStore() {
http.Client Function()? clientFactory,
}) : _fileStore = fileStore ?? TranslationFileStore(),
_newClient = clientFactory ?? http.Client.new {
// Initialize langdetect once at service construction.
_langDetectInit = initLangDetect();
}
@@ -61,6 +64,13 @@ class TranslationService extends ChangeNotifier {
int _downloadedBytes = 0;
int? _downloadTotalBytes;
String? _downloadFileName;
String? _downloadTargetFileName;
String? _downloadSourceUrl;
String? _downloadModelId;
String? _failedDownloadError;
String? _failedDownloadSourceUrl;
String? _failedDownloadFileName;
String? _failedDownloadModelId;
bool get isBusy => _isBusy;
bool get isDownloading => _isDownloading;
@@ -68,6 +78,29 @@ class TranslationService extends ChangeNotifier {
int get downloadedBytes => _downloadedBytes;
int? get downloadTotalBytes => _downloadTotalBytes;
String? get downloadFileName => _downloadFileName;
/// File being fetched. Stays set while chunks are merged, when
/// [downloadFileName] is replaced with the merge status.
String? get downloadTargetFileName => _downloadTargetFileName;
/// URL of the download in progress. Settings can rebuild the row after
/// the page that started the download has been disposed.
String? get downloadSourceUrl => _downloadSourceUrl;
/// Preset id when the download was started as a preset, otherwise null.
String? get downloadModelId => _downloadModelId;
/// Error message from the most recent failed download, if any.
String? get failedDownloadError => _failedDownloadError;
/// URL of the most recent failed download, if any.
String? get failedDownloadSourceUrl => _failedDownloadSourceUrl;
/// Resolved filename of the most recent failed download, if any.
String? get failedDownloadFileName => _failedDownloadFileName;
/// Preset id of the most recent failed download, if it was a preset.
String? get failedDownloadModelId => _failedDownloadModelId;
double? get downloadProgress {
final total = _downloadTotalBytes;
if (!_isDownloading || total == null || total <= 0) {
@@ -195,22 +228,26 @@ class TranslationService extends ChangeNotifier {
}
return _runExclusive(() async {
_setBusy(true);
_setDownloading(true);
_lastError = null;
_clearFailedDownload();
final resolvedFileName =
fileName ??
_sanitizeFileName(
uri.pathSegments.isNotEmpty
? uri.pathSegments.last
: 'translation-model.gguf',
);
_downloadSourceUrl = sourceUrl;
_downloadModelId = id;
_downloadTargetFileName = resolvedFileName;
_downloadFileName = resolvedFileName;
_downloadedBytes = 0;
_downloadTotalBytes = null;
_cancelDownloadRequested = false;
_setDownloading(true);
try {
final resolvedFileName =
fileName ??
_sanitizeFileName(
uri.pathSegments.isNotEmpty
? uri.pathSegments.last
: 'translation-model.gguf',
);
_downloadFileName = resolvedFileName;
_downloadedBytes = 0;
_cancelDownloadRequested = false;
// HEAD request to check size and range support.
final headClient = http.Client();
final headClient = _newClient();
int? totalSize;
bool supportsRange = false;
try {
@@ -223,6 +260,10 @@ class TranslationService extends ChangeNotifier {
headClient.close();
}
if (_cancelDownloadRequested) {
throw const TranslationDownloadCancelled();
}
_downloadTotalBytes = totalSize;
_notify();
@@ -260,6 +301,15 @@ class TranslationService extends ChangeNotifier {
await _appSettingsService.setTranslationModelSourceUrl(sourceUrl);
_failedModelPath = null;
return record;
} on TranslationDownloadCancelled {
rethrow;
} catch (error) {
_lastError = '$error';
_failedDownloadError = '$error';
_failedDownloadSourceUrl = sourceUrl;
_failedDownloadFileName = resolvedFileName;
_failedDownloadModelId = id;
rethrow;
} finally {
_setDownloading(false);
}
@@ -270,7 +320,7 @@ class TranslationService extends ChangeNotifier {
required Uri uri,
required String fileName,
}) async {
final client = http.Client();
final client = _newClient();
try {
final response = await client.send(http.Request('GET', uri));
if (response.statusCode < 200 || response.statusCode >= 300) {
@@ -314,7 +364,7 @@ class TranslationService extends ChangeNotifier {
if (start >= totalSize) break;
final chunkPath = await _fileStore.chunkFilePath(fileName, i);
chunkPaths.add(chunkPath);
final client = http.Client();
final client = _newClient();
clients.add(client);
futures.add(
_downloadRange(
@@ -701,6 +751,37 @@ class TranslationService extends ChangeNotifier {
_notify();
}
void _clearFailedDownload() {
_failedDownloadError = null;
_failedDownloadSourceUrl = null;
_failedDownloadFileName = null;
_failedDownloadModelId = null;
}
/// Puts the service in the same state [downloadModel] publishes while a
/// fetch is running, so settings can be rebuilt without a network call.
@visibleForTesting
void debugSetActiveDownload({
required String sourceUrl,
String? fileName,
String? modelId,
String? displayedFileName,
int downloadedBytes = 0,
int? totalBytes,
}) {
_lastError = null;
_clearFailedDownload();
_downloadSourceUrl = sourceUrl;
_downloadModelId = modelId;
_downloadTargetFileName = fileName;
_downloadFileName = displayedFileName ?? fileName;
_downloadedBytes = downloadedBytes;
_downloadTotalBytes = totalBytes;
_isBusy = true;
_isDownloading = true;
_notify();
}
void _setDownloading(bool value) {
_isDownloading = value;
if (!value) {
@@ -708,6 +789,9 @@ class TranslationService extends ChangeNotifier {
_downloadedBytes = 0;
_downloadTotalBytes = null;
_downloadFileName = null;
_downloadTargetFileName = null;
_downloadSourceUrl = null;
_downloadModelId = null;
}
_notify();
}