Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Prune Auth and Locker comments

Manav Rathid4fdeae8f1f5
diff --git a/mobile/apps/auth/lib/models/code.dart b/mobile/apps/auth/lib/models/code.dart
index a8af147a54..a603fa401a 100644
--- a/mobile/apps/auth/lib/models/code.dart
+++ b/mobile/apps/auth/lib/models/code.dart
@@ -18,7 +18,7 @@ class Code {
final Algorithm algorithm;
final Type type;
- /// otpauth url in the code
+ // Original otpauth URL.
final String rawData;
final int counter;
bool? hasSynced;
@@ -33,18 +33,7 @@ class Code {
final Object? err;
bool get hasError => err != null;
- /// Stable identifier for UI selection state and other transient UI features.
- ///
- /// This key ensures selection consistency across sync operations and local changes:
- /// - Uses [generatedID] when available (after code is persisted to database)
- /// - Falls back to [rawData] for unpersisted codes (before first save)
- ///
- /// The fallback strategy ensures that:
- /// 1. Selections survive the transition from local-only to synced codes
- /// 2. Each persisted code has a unique, stable identifier
- /// 3. UI state reconciliation can map old keys to new keys during sync
- ///
- /// See [CodeDisplayStore.reconcileSelections] for selection state management.
+ // Unsaved codes use rawData until sync assigns generatedID.
String get selectionKey => generatedID?.toString() ?? rawData;
String get issuerAccount =>
diff --git a/mobile/apps/auth/lib/models/code_display.dart b/mobile/apps/auth/lib/models/code_display.dart
index 63073ff5c4..2cb8688208 100644
--- a/mobile/apps/auth/lib/models/code_display.dart
+++ b/mobile/apps/auth/lib/models/code_display.dart
@@ -3,7 +3,6 @@ import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
-/// Used to store the display settings of a code.
class CodeDisplay {
final bool pinned;
final bool trashed;
@@ -81,9 +80,6 @@ class CodeDisplay {
);
}
- /// Converts the [CodeDisplay] to a json object.
- /// When [safeParsing] is true, the json will be parsed safely.
- /// If we fail to parse the json, we will return an empty [CodeDisplay].
static CodeDisplay? fromUri(Uri uri, {bool safeParsing = false}) {
if (!uri.queryParameters.containsKey("codeDisplay")) return null;
final String codeDisplay = uri.queryParameters['codeDisplay']!.replaceAll(
diff --git a/mobile/apps/auth/lib/services/local_backup_service.dart b/mobile/apps/auth/lib/services/local_backup_service.dart
index 379847e811..19b43d96a2 100644
--- a/mobile/apps/auth/lib/services/local_backup_service.dart
+++ b/mobile/apps/auth/lib/services/local_backup_service.dart
@@ -32,8 +32,6 @@ class LocalBackupService {
});
}
- /// Clear backup password on fresh install (like lock screen does).
- /// Only clears if not logged in and not in offline mode.
Future<void> _clearBackupPasswordIfFreshInstall(
bool hasOptedForOfflineMode,
) async {
@@ -92,8 +90,7 @@ class LocalBackupService {
return triggerAutomaticBackup();
}
- /// Write backup to a directory that we already have scoped access to.
- /// Used on iOS where security-scoped access is held by caller.
+ // The caller must hold security-scoped access on iOS.
Future<bool> writeBackupToDirectory(String directoryPath) async {
try {
final String? password = await _readPassword();
diff --git a/mobile/apps/auth/lib/services/security_bookmark_service.dart b/mobile/apps/auth/lib/services/security_bookmark_service.dart
index 5b3c041a6c..7f825f383e 100644
--- a/mobile/apps/auth/lib/services/security_bookmark_service.dart
+++ b/mobile/apps/auth/lib/services/security_bookmark_service.dart
@@ -2,10 +2,7 @@ import 'dart:io';
import 'package:scoped_dir_access/scoped_dir_access.dart';
-/// Service for managing iOS security-scoped bookmarks.
-///
-/// This is a thin wrapper around [DirUtils] for backward compatibility.
-/// You can use [DirUtils.instance] directly if you prefer.
+// Backward-compatible wrapper; new code can use DirUtils directly.
class SecurityBookmarkService {
SecurityBookmarkService._();
@@ -13,11 +10,7 @@ class SecurityBookmarkService {
final _dirUtils = DirUtils.instance;
- /// Opens native iOS directory picker and creates a bookmark immediately.
- ///
- /// Returns a [DirectoryPickResult] with both path and bookmark, or null if cancelled.
- /// This is the preferred method on iOS as it creates the bookmark while we still
- /// have the security-scoped URL from the picker.
+ // Create the bookmark while the picker still owns the security-scoped URL.
Future<DirectoryPickResult?> pickDirectoryAndCreateBookmark() async {
if (!Platform.isIOS) return null;
@@ -30,12 +23,7 @@ class SecurityBookmarkService {
);
}
- /// Starts accessing a security-scoped resource using a stored bookmark.
- ///
- /// Returns a [BookmarkAccessResult] containing the success status,
- /// resolved path, and whether the bookmark is stale.
- ///
- /// You MUST call [stopAccessingBookmark] when done to balance the call.
+ // Each successful call must be balanced with stopAccessingBookmark.
Future<BookmarkAccessResult?> startAccessingBookmark(String bookmark) async {
if (!Platform.isIOS) return null;
@@ -50,10 +38,6 @@ class SecurityBookmarkService {
);
}
- /// Stops accessing a security-scoped resource.
- ///
- /// Always call this after you're done with file operations to
- /// balance the [startAccessingBookmark] call.
Future<bool> stopAccessingBookmark(String bookmark) async {
if (!Platform.isIOS) return true;
diff --git a/mobile/apps/auth/lib/store/code_display_store.dart b/mobile/apps/auth/lib/store/code_display_store.dart
index baf71829e8..ae2934f485 100644
--- a/mobile/apps/auth/lib/store/code_display_store.dart
+++ b/mobile/apps/auth/lib/store/code_display_store.dart
@@ -37,30 +37,7 @@ class CodeDisplayStore {
isSelectionModeActive.value = false;
}
- /// Reconciles current selections with the provided list of codes.
- ///
- /// This ensures selection state remains valid when:
- /// - Codes transition from local to synced (rawData β†’ generatedID)
- /// - Codes are deleted or removed from the list
- /// - Codes are marked with errors and become invalid for selection
- ///
- /// **How it works:**
- /// 1. Builds a set of valid selection keys from non-error codes
- /// 2. Creates a remapping table for old keys (rawData, old generatedID) β†’ new keys
- /// 3. Updates current selection by keeping valid keys and remapping changed keys
- /// 4. Removes selections for codes that no longer exist or have errors
- ///
- /// **Performance:** O(n + m) where n = number of codes, m = number of selected items
- ///
- /// **Example scenario:**
- /// ```dart
- /// // User selects code with rawData="abc123" (not yet synced)
- /// selectedCodeIds = {"abc123"}
- ///
- /// // After sync, code gets generatedID=42
- /// // reconcileSelections maps "abc123" β†’ "42"
- /// selectedCodeIds = {"42"} // Selection preserved!
- /// ```
+ // Preserve selections when sync replaces rawData keys with generated IDs.
void reconcileSelections(Iterable<Code> codes) {
final currentSelection = selectedCodeIds.value;
if (currentSelection.isEmpty) {
diff --git a/mobile/apps/auth/lib/ui/code_widget.dart b/mobile/apps/auth/lib/ui/code_widget.dart
index bcad58fab2..7ae137d360 100644
--- a/mobile/apps/auth/lib/ui/code_widget.dart
+++ b/mobile/apps/auth/lib/ui/code_widget.dart
@@ -616,7 +616,6 @@ class _CodeWidgetState extends State<CodeWidget> {
return entries;
}
- /// Adds menu items for non-trashed codes (share, QR, tag, notes, pin).
void _addNonTrashedMenuItems(
List<ContextMenuEntry> entries,
StringsLocalizations l10n,
@@ -675,7 +674,6 @@ class _CodeWidgetState extends State<CodeWidget> {
}
}
- /// Adds edit menu item for non-trashed codes or restore for trashed codes.
void _addEditOrRestoreMenuItem(
List<ContextMenuEntry> entries,
StringsLocalizations l10n,
@@ -699,7 +697,6 @@ class _CodeWidgetState extends State<CodeWidget> {
}
}
- /// Adds delete (forever) or trash menu item based on code state.
void _addDeleteOrTrashMenuItem(
List<ContextMenuEntry> entries,
StringsLocalizations l10n,
@@ -744,7 +741,6 @@ class _CodeWidgetState extends State<CodeWidget> {
return entries.isEmpty ? null : entries;
}
- /// Adds menu items for multi-selected trashed codes (restore, delete).
void _addTrashedMultiSelectMenuItems(
List<ContextMenuEntry> entries,
StringsLocalizations l10n,
@@ -765,7 +761,6 @@ class _CodeWidgetState extends State<CodeWidget> {
);
}
- /// Adds pin/unpin menu items based on selection pin state.
void _addPinMenuItems(
List<ContextMenuEntry> entries,
StringsLocalizations l10n,
@@ -803,7 +798,6 @@ class _CodeWidgetState extends State<CodeWidget> {
}
}
- /// Adds tag and trash menu items for multi-selection.
void _addTagAndTrashMenuItems(
List<ContextMenuEntry> entries,
StringsLocalizations l10n,
diff --git a/mobile/apps/auth/lib/ui/components/action_sheet_widget.dart b/mobile/apps/auth/lib/ui/components/action_sheet_widget.dart
index 4826b292e6..c8e5b38bc0 100644
--- a/mobile/apps/auth/lib/ui/components/action_sheet_widget.dart
+++ b/mobile/apps/auth/lib/ui/components/action_sheet_widget.dart
@@ -10,11 +10,7 @@ import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
enum ActionSheetType { defaultActionSheet, iconOnly }
-/// Compatibility adapter for legacy Auth action sheets.
-///
-/// Existing callers keep their [ButtonWidget] result contract while the sheet
-/// renders through Ente components. New surfaces should use
-/// [BottomSheetComponent] directly.
+// Legacy adapter. New surfaces should use BottomSheetComponent directly.
Future<ButtonResult?> showActionSheet({
required BuildContext context,
required List<ButtonWidget> buttons,
diff --git a/mobile/apps/auth/lib/ui/components/auth_selection_action_button.dart b/mobile/apps/auth/lib/ui/components/auth_selection_action_button.dart
index ed50ed577a..cf0e22e86a 100644
--- a/mobile/apps/auth/lib/ui/components/auth_selection_action_button.dart
+++ b/mobile/apps/auth/lib/ui/components/auth_selection_action_button.dart
@@ -1,7 +1,6 @@
import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
-/// Auth-local selection action composed from Ente design tokens.
class AuthSelectionActionButton extends StatelessWidget {
const AuthSelectionActionButton({
super.key,
diff --git a/mobile/apps/auth/lib/ui/components/buttons/button_component_adapter.dart b/mobile/apps/auth/lib/ui/components/buttons/button_component_adapter.dart
index 335718f00f..b8aec96837 100644
--- a/mobile/apps/auth/lib/ui/components/buttons/button_component_adapter.dart
+++ b/mobile/apps/auth/lib/ui/components/buttons/button_component_adapter.dart
@@ -11,7 +11,7 @@ import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
const _loadingSurfaceDelay = Duration(milliseconds: 300);
const _successDisplayDuration = Duration(seconds: 1);
-/// Preserves legacy Auth button behavior while rendering an Ente component.
+// Legacy adapter for existing ButtonWidget callers.
class ButtonComponentAdapter extends StatelessWidget {
const ButtonComponentAdapter({required this.button, super.key});
diff --git a/mobile/apps/auth/lib/ui/components/dialog_widget.dart b/mobile/apps/auth/lib/ui/components/dialog_widget.dart
index 1d7e1781f3..80eaa97eec 100644
--- a/mobile/apps/auth/lib/ui/components/dialog_widget.dart
+++ b/mobile/apps/auth/lib/ui/components/dialog_widget.dart
@@ -9,7 +9,6 @@ import 'package:ente_ui/components/buttons/models/button_result.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-///Will return null if dismissed by tapping outside
Future<ButtonResult?> showDialogWidget({
required BuildContext context,
required String title,
diff --git a/mobile/apps/auth/lib/ui/components/selection_action_button.dart b/mobile/apps/auth/lib/ui/components/selection_action_button.dart
index b12cbfe16d..2f97d2add3 100644
--- a/mobile/apps/auth/lib/ui/components/selection_action_button.dart
+++ b/mobile/apps/auth/lib/ui/components/selection_action_button.dart
@@ -4,7 +4,6 @@ import "package:ente_auth/theme/ente_theme.dart";
import "package:flutter/material.dart";
import "package:flutter_svg/svg.dart";
-/// Pass icon or asset path of svg
class SelectionActionButton extends StatelessWidget {
final String labelText;
final IconData? icon;
diff --git a/mobile/apps/auth/lib/ui/home/widgets/home_search_field.dart b/mobile/apps/auth/lib/ui/home/widgets/home_search_field.dart
index 8810634f3c..5ef0900f97 100644
--- a/mobile/apps/auth/lib/ui/home/widgets/home_search_field.dart
+++ b/mobile/apps/auth/lib/ui/home/widgets/home_search_field.dart
@@ -1,7 +1,6 @@
import 'package:flutter/material.dart';
-/// Focuses the persistent search field and leaves the triggering key event for
-/// the platform text input system to process.
+// Return false so the platform text input also receives the triggering key.
bool activateHomeSearchFromKeyEvent({
required VoidCallback showSearch,
required FocusNode focusNode,
@@ -12,7 +11,6 @@ bool activateHomeSearchFromKeyEvent({
return false;
}
-/// Keeps the search input attached and programmatically focusable while hidden.
class PersistentSearchField extends StatelessWidget {
const PersistentSearchField({
super.key,
diff --git a/mobile/apps/auth/lib/ui/settings/components/auth_settings_page_scaffold.dart b/mobile/apps/auth/lib/ui/settings/components/auth_settings_page_scaffold.dart
index e64cf15141..cfdae88301 100644
--- a/mobile/apps/auth/lib/ui/settings/components/auth_settings_page_scaffold.dart
+++ b/mobile/apps/auth/lib/ui/settings/components/auth_settings_page_scaffold.dart
@@ -3,7 +3,6 @@ import 'dart:math' as math;
import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
-/// Applies Auth's left-aligned desktop content width to the shared scaffold.
class AuthSettingsPageScaffold extends StatelessWidget {
const AuthSettingsPageScaffold({
super.key,
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
index b2c7b33693..7377abbc41 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
@@ -151,8 +151,7 @@ Future<int?> _processAndOTPFile(
return saveImportedCodes(parsedCodes);
}
-/// Top-level function for decrypting andOTP backup in a separate isolate.
-/// Must be top-level (not a method or closure) to work with compute().
+// Must remain top-level for compute().
String _decryptAndOTPBackup(_DecryptParams params) {
final Uint8List fileBytes = params.fileBytes;
final String password = params.password;
diff --git a/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart b/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart
index 61fc342653..fe8d004ab1 100644
--- a/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart
@@ -794,7 +794,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
}
- /// iOS/macOS: Persist location with pre-created bookmark
Future<bool> _persistLocationWithBookmark(
String path,
String bookmark, {
@@ -981,11 +980,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
).showSnackBar(SnackBar(content: Text(message)));
}
- /// Check if the selected iOS path is the device root ("On My iPhone").
- ///
- /// "On My iPhone" root cannot store files directly - user must select
- /// or create a folder inside it. Only the actual iOS File Provider Storage
- /// root (AppGroup/UUID/File Provider Storage) is invalid.
bool _isInvalidIosPath(String path) {
if (!Platform.isIOS) return false;
if (path.isEmpty) return true;
diff --git a/mobile/apps/auth/lib/utils/debug_code_deep_link.dart b/mobile/apps/auth/lib/utils/debug_code_deep_link.dart
index b92d2fd46d..cdb20c3cd3 100644
--- a/mobile/apps/auth/lib/utils/debug_code_deep_link.dart
+++ b/mobile/apps/auth/lib/utils/debug_code_deep_link.dart
@@ -9,11 +9,8 @@ class DebugCodeDeepLink {
final String codeUri;
}
-/// Parses debug-only code links used by offline UI automation.
-///
-/// iOS may route `otpauth://` links to the system Passwords app, even when
-/// Ente Auth is installed. Wrapping the URI in Ente Auth's own scheme keeps
-/// deterministic Maestro setup and visual previews out of release builds.
+// iOS routes otpauth:// to Passwords, so debug automation wraps it in Ente
+// Auth's own scheme.
DebugCodeDeepLink? parseDebugCodeDeepLink(String link) {
if (!kDebugMode) return null;
diff --git a/mobile/apps/auth/lib/utils/dialog_util.dart b/mobile/apps/auth/lib/utils/dialog_util.dart
index 1240edbc5c..5bfbc23bb6 100644
--- a/mobile/apps/auth/lib/utils/dialog_util.dart
+++ b/mobile/apps/auth/lib/utils/dialog_util.dart
@@ -21,7 +21,6 @@ import 'package:flutter/material.dart';
typedef DialogBuilder = DialogWidget Function(BuildContext context);
-///Will return null if dismissed by tapping outside
Future<ButtonResult?> showErrorDialog(
BuildContext context,
String title,
@@ -141,7 +140,6 @@ String parseErrorForUI(
}
}
-///Will return null if dismissed by tapping outside
Future<ButtonResult?> showGenericErrorDialog({
required BuildContext context,
bool isDismissible = true,
@@ -236,7 +234,6 @@ DialogWidget choiceDialog({
return DialogWidget(title: title, body: body, buttons: buttons, icon: icon);
}
-///Will return null if dismissed by tapping outside
Future<ButtonResult?> showChoiceDialog(
BuildContext context, {
required String title,
@@ -280,7 +277,6 @@ Future<ButtonResult?> showChoiceDialog(
);
}
-///Will return null if dismissed by tapping outside
Future<ButtonResult?> showChoiceActionSheet(
BuildContext context, {
required String title,
diff --git a/mobile/apps/auth/lib/utils/gallery_import_util.dart b/mobile/apps/auth/lib/utils/gallery_import_util.dart
index 75e1ed73b7..9ce0cced0f 100644
--- a/mobile/apps/auth/lib/utils/gallery_import_util.dart
+++ b/mobile/apps/auth/lib/utils/gallery_import_util.dart
@@ -142,8 +142,6 @@ GalleryImportResult parseQrImportPayload(String qrCodeData) {
return GalleryImportResult.code(Code.fromOTPAuthUrl(qrCodeData));
}
-/// Prompts the user to pick an image and tries to extract auth codes from it.
-/// Returns the parsed QR import result when successful, otherwise null.
Future<GalleryImportResult?> pickCodeFromImage(
BuildContext context, {
Logger? logger,
diff --git a/mobile/apps/auth/lib/utils/share_utils.dart b/mobile/apps/auth/lib/utils/share_utils.dart
index 9376f89479..7362898dbb 100644
--- a/mobile/apps/auth/lib/utils/share_utils.dart
+++ b/mobile/apps/auth/lib/utils/share_utils.dart
@@ -62,8 +62,6 @@ Rect _sharePosOrigin(BuildContext? context, GlobalKey? key) {
return rect;
}
-/// Returns the rect of button if context and key are not null
-/// If key is null, returned rect will be at the center of the screen
Rect shareButtonRect(BuildContext context, GlobalKey? shareButtonKey) {
Size size = MediaQuery.sizeOf(context);
final RenderObject? renderObject = shareButtonKey?.currentContext
diff --git a/mobile/apps/locker/lib/events/user_details_refresh_event.dart b/mobile/apps/locker/lib/events/user_details_refresh_event.dart
index 3e25bd083b..3a7c7e1982 100644
--- a/mobile/apps/locker/lib/events/user_details_refresh_event.dart
+++ b/mobile/apps/locker/lib/events/user_details_refresh_event.dart
@@ -1,9 +1,3 @@
import "package:ente_events/models/event.dart";
-/// Event fired when user details (like file count, storage) need to be refreshed from the server.
-///
-/// Fired in the following scenarios:
-/// - File uploads complete (PDF/text files or info items)
-/// - Files are moved to trash
-/// - Files are restored from trash
class UserDetailsRefreshEvent extends Event {}
diff --git a/mobile/apps/locker/lib/extensions/collection_extension.dart b/mobile/apps/locker/lib/extensions/collection_extension.dart
index c841f5fb51..0a61f52dc2 100644
--- a/mobile/apps/locker/lib/extensions/collection_extension.dart
+++ b/mobile/apps/locker/lib/extensions/collection_extension.dart
@@ -1,9 +1,6 @@
import "package:locker/services/collections/models/collection.dart";
extension CollectionDisplayExtension on Collection {
- /// Returns the display name for the collection.
- /// For favorites collections, always returns "Important" regardless of the stored name.
- /// For other collections, returns the stored name or null.
String? get displayName {
if (type == CollectionType.favorites) {
return "Important";
diff --git a/mobile/apps/locker/lib/services/collections/collections_service.dart b/mobile/apps/locker/lib/services/collections/collections_service.dart
index 3e0fffcdd0..b8484317e6 100644
--- a/mobile/apps/locker/lib/services/collections/collections_service.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_service.dart
@@ -287,7 +287,6 @@ class CollectionService {
}
}
- /// Removes orphaned files that exist in files but have no collection mappings.
Future<void> cleanupOrphanedFiles() async {
try {
await _db.cleanupOrphanedFiles();
@@ -298,9 +297,6 @@ class CollectionService {
}
}
- /// Adds a file to a collection. By default this triggers a full sync to
- /// update local state. Set [runSync] to false to delay syncing (useful when
- /// adding the same file to multiple collections during an upload).
Future<void> addToCollection(
Collection collection,
EnteFile file, {
@@ -538,13 +534,7 @@ class CollectionService {
}
}
- /// Trash an empty collection directly without moving files.
- /// The server will verify that the collection is actually empty before
- /// deleting. If keepFiles is set as False and the collection is not empty,
- /// then the files in the collection will be moved to trash.
- ///
- /// [isBulkDelete] - During bulk deletion, this event is not fired to avoid
- /// quick refresh of the collection gallery
+ // The server rejects this path unless the collection is empty.
Future<void> trashEmptyCollection(
Collection collection, {
bool isBulkDelete = false,
@@ -793,8 +783,6 @@ class CollectionService {
return createCollection("Documents", type: CollectionType.folder);
}
- /// Returns one random collection name that doesn't already exist
- /// If all names are used, returns "Documents"
Future<String> getRandomUnusedCollectionName() async {
try {
final existingCollections = await getCollections();
@@ -868,13 +856,6 @@ class CollectionService {
.toList();
}
- /// Returns Contacts(Users) that are relevant to the account owner.
- /// Note: "User" refers to the account owner in the points below.
- /// This includes:
- /// - Collaborators and viewers of collections owned by user
- /// - Owners of collections shared to user.
- /// - All collaborators of collections in which user is a collaborator or
- /// a viewer.
List<UserSuggestion> getRelevantContacts() {
final int ownerID = Configuration.instance.getUserID()!;
final String ownerEmail = Configuration.instance.getEmail()!;
diff --git a/mobile/apps/locker/lib/services/collections/models/collection_view_type.dart b/mobile/apps/locker/lib/services/collections/models/collection_view_type.dart
index cd3b71b3eb..1264899dce 100644
--- a/mobile/apps/locker/lib/services/collections/models/collection_view_type.dart
+++ b/mobile/apps/locker/lib/services/collections/models/collection_view_type.dart
@@ -12,7 +12,6 @@ enum CollectionViewType {
favorite,
}
-/// Extension methods to determine which actions are available for each view type
extension CollectionViewTypeActions on CollectionViewType {
bool get isIncomingShare =>
this == CollectionViewType.sharedCollectionViewer ||
diff --git a/mobile/apps/locker/lib/services/db/locker_db.dart b/mobile/apps/locker/lib/services/db/locker_db.dart
index 858431cac2..701102e1dc 100644
--- a/mobile/apps/locker/lib/services/db/locker_db.dart
+++ b/mobile/apps/locker/lib/services/db/locker_db.dart
@@ -532,7 +532,6 @@ class LockerDB extends EnteBaseDatabase {
return files;
}
- /// Removes orphaned files that exist in files but have no collection mappings.
Future<void> cleanupOrphanedFiles() async {
final orphanedFiles = await _db.rawQuery('''
SELECT f.uploaded_file_id
diff --git a/mobile/apps/locker/lib/services/files/download/file_downloader.dart b/mobile/apps/locker/lib/services/files/download/file_downloader.dart
index dfae16fccb..1fc440d0f3 100644
--- a/mobile/apps/locker/lib/services/files/download/file_downloader.dart
+++ b/mobile/apps/locker/lib/services/files/download/file_downloader.dart
@@ -23,8 +23,6 @@ String _getTemporaryDecryptedFilePath(EnteFile file) {
return "$tempDir${file.uploadedFileID}_$safeDisplayName";
}
-/// Returns the encrypted offline blob for this device, downloading it only when
-/// a usable local copy does not already exist.
Future<File> ensureEncryptedOfflineCopy(
EnteFile file, {
ProgressCallback? progressCallback,
diff --git a/mobile/apps/locker/lib/services/files/download/manager.dart b/mobile/apps/locker/lib/services/files/download/manager.dart
index cb8f2935cb..3df8011a0c 100644
--- a/mobile/apps/locker/lib/services/files/download/manager.dart
+++ b/mobile/apps/locker/lib/services/files/download/manager.dart
@@ -24,7 +24,6 @@ class DownloadManager {
DownloadManager(this._dio);
- /// Subscribe to download progress updates for a specific file ID
Stream<DownloadTask> watchDownload(int fileId) {
_streams[fileId] ??= StreamController<DownloadTask>.broadcast();
return _streams[fileId]!.stream;
@@ -36,8 +35,6 @@ class DownloadManager {
return size > downloadChunkSize;
}
- /// Start download and return a Future that completes when download finishes
- /// If download was paused, calling this again will resume it
Future<DownloadResult> download(
int fileId,
String filename,
@@ -89,7 +86,6 @@ class DownloadManager {
return completer.future;
}
- /// Pause download
Future<void> pause(int fileId) async {
final token = _cancelTokens[fileId];
if (token != null && !token.isCancelled) {
@@ -109,7 +105,6 @@ class DownloadManager {
}
}
- /// Cancel and delete download
Future<void> cancel(int fileId) async {
final token = _cancelTokens[fileId];
if (token != null && !token.isCancelled) {
@@ -125,10 +120,8 @@ class DownloadManager {
_cleanup(fileId);
}
- /// Get current download status
Future<DownloadTask?> getDownload(int fileId) async => _tasks[fileId];
- /// Get all downloads
Future<List<DownloadTask>> getAllDownloads() async => _tasks.values.toList();
Future<void> _startDownload(
diff --git a/mobile/apps/locker/lib/services/files/offline/offline_files_service.dart b/mobile/apps/locker/lib/services/files/offline/offline_files_service.dart
index dfffbce13e..9d81f4d7b2 100644
--- a/mobile/apps/locker/lib/services/files/offline/offline_files_service.dart
+++ b/mobile/apps/locker/lib/services/files/offline/offline_files_service.dart
@@ -12,10 +12,6 @@ import 'package:locker/services/files/sync/models/file.dart';
import 'package:locker/services/info_file_service.dart';
import 'package:logging/logging.dart';
-/// Handles Locker's explicit per-file offline save flow.
-///
-/// A file is marked offline only after the encrypted blob has been saved on
-/// this device.
class OfflineFilesService {
OfflineFilesService._privateConstructor();
@@ -31,7 +27,7 @@ class OfflineFilesService {
await cleanupStaleOfflineFileCopies(olderThan: _cachedFileCleanupAge);
}
- /// Shared files and info records are intentionally excluded from offline save.
+ // Shared files and info records are excluded from offline save.
bool _canMarkOffline(EnteFile file) {
final currentUserID = Configuration.instance.getUserID();
return file.uploadedFileID != null &&
@@ -54,7 +50,6 @@ class OfflineFilesService {
return eligibleFilesById.values.toList();
}
- /// Downloads the encrypted blob and marks the file offline on success.
Future<bool> markFilesOffline(
BuildContext context,
Iterable<EnteFile> files,
@@ -171,7 +166,6 @@ class OfflineFilesService {
return successCount > 0;
}
- /// Clears offline state for the selected files on this device.
Future<bool> unmarkFilesOffline(
BuildContext context,
Iterable<EnteFile> files,
@@ -250,8 +244,8 @@ class OfflineFilesService {
await _clearOfflineState(staleFileIDs);
}
- /// Downloads first, then writes the local offline mark if the file is still
- /// active in the current library view.
+ // Mark offline only after the encrypted copy is saved and the file is still
+ // active.
Future<bool> _ensureOfflineCopyAndMark(EnteFile file) async {
final fileID = file.uploadedFileID!;
await ensureEncryptedOfflineCopy(file);
diff --git a/mobile/apps/locker/lib/services/files/sync/models/common_keys.dart b/mobile/apps/locker/lib/services/files/sync/models/common_keys.dart
index 1156623e8a..44dbf1665e 100644
--- a/mobile/apps/locker/lib/services/files/sync/models/common_keys.dart
+++ b/mobile/apps/locker/lib/services/files/sync/models/common_keys.dart
@@ -4,5 +4,5 @@ const magicKeyVisibility = 'visibility';
const visibleVisibility = 0;
const archiveVisibility = 1;
-///Do not use [hiddenVisibility] for hidden files
+// Do not use hiddenVisibility for hidden files.
const hiddenVisibility = 2;
diff --git a/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart b/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
index 42650e43d9..c609d7a13a 100644
--- a/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
+++ b/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
@@ -95,7 +95,6 @@ class FileUploader {
return completer.future;
}
- /// Special upload method for info files that contain only metadata
Future<EnteFile> uploadInfoFile(
EnteFile infoFile,
Collection collection,
@@ -800,7 +799,6 @@ class FileUploader {
}
}
- /// Upload method specifically for info files that don't require file content or thumbnails
Future<EnteFile> _uploadInfoFileMetadata(
EnteFile file,
int collectionID,
diff --git a/mobile/apps/locker/lib/services/info_file_service.dart b/mobile/apps/locker/lib/services/info_file_service.dart
index f1b803b3d0..afc72ab030 100644
--- a/mobile/apps/locker/lib/services/info_file_service.dart
+++ b/mobile/apps/locker/lib/services/info_file_service.dart
@@ -13,7 +13,6 @@ class InfoFileService {
final _logger = Logger('InfoFileService');
- /// Creates and uploads an info file
Future<EnteFile> createAndUploadInfoFile({
required InfoItem infoItem,
required Collection collection,
@@ -52,7 +51,6 @@ class InfoFileService {
}
}
- /// Updates an existing info file with new data
Future<bool> updateInfoFile({
required EnteFile existingFile,
required InfoItem updatedInfoItem,
@@ -95,7 +93,6 @@ class InfoFileService {
}
}
- /// Extracts info data from a file
InfoItem? extractInfoFromFile(EnteFile file) {
try {
final infoData = file.pubMagicMetadata.info;
@@ -143,7 +140,6 @@ class InfoFileService {
}
}
- /// Checks if a file is an info file
bool isInfoFile(EnteFile file) {
if (file.fileType == FileType.info) {
return true;
@@ -154,7 +150,6 @@ class InfoFileService {
return file.pubMagicMetadata.info != null;
}
- /// Gets the display title for an info file based on its content
String getInfoFileTitle(InfoItem infoItem) {
switch (infoItem.type) {
case InfoType.note:
@@ -174,13 +169,11 @@ class InfoFileService {
}
}
- /// Gets the display title directly from an EnteFile (convenience method)
String? getFileTitleFromFile(EnteFile file) {
final infoItem = extractInfoFromFile(file);
return infoItem != null ? getInfoFileTitle(infoItem) : null;
}
- /// Special upload method for info files that don't require physical file content
Future<EnteFile> _uploadInfoFile(
EnteFile enteFile,
Collection collection,
diff --git a/mobile/apps/locker/lib/ui/components/custom_list_scrollbar.dart b/mobile/apps/locker/lib/ui/components/custom_list_scrollbar.dart
index 2a8fd3484c..2174afde3a 100644
--- a/mobile/apps/locker/lib/ui/components/custom_list_scrollbar.dart
+++ b/mobile/apps/locker/lib/ui/components/custom_list_scrollbar.dart
@@ -1,9 +1,6 @@
import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
-/// A thin scrollbar rendered beside a bounded [ListView], with the thumb sized
-/// to [visibleItems] of [itemCount] and positioned from the shared
-/// [scrollController]. Shared by the add-email and share-collection sheets.
class CustomListScrollbar extends StatelessWidget {
const CustomListScrollbar({
super.key,
diff --git a/mobile/apps/locker/lib/ui/mixins/search_mixin.dart b/mobile/apps/locker/lib/ui/mixins/search_mixin.dart
index 472ff8a976..44bc29bd9d 100644
--- a/mobile/apps/locker/lib/ui/mixins/search_mixin.dart
+++ b/mobile/apps/locker/lib/ui/mixins/search_mixin.dart
@@ -210,7 +210,6 @@ mixin SearchMixin<T extends StatefulWidget> on State<T> {
return words.any((word) => word.startsWith(lowerQuery));
}
- /// Handle keyboard shortcuts
bool handleKeyEvent(KeyEvent event) {
if (event is KeyDownEvent) {
// Clear search or close search on ESC
@@ -245,7 +244,6 @@ mixin SearchMixin<T extends StatefulWidget> on State<T> {
void updateSearchQuery(String query) => _onSearchChanged(query);
- /// Programmatically activate search with a specific query
void activateSearchWithQuery(String query) {
setState(() {
_isSearchActive = true;
@@ -261,7 +259,6 @@ mixin SearchMixin<T extends StatefulWidget> on State<T> {
});
}
- /// Programmatically dismiss the search UI and reset state
void dismissSearch() {
if (_isSearchActive) {
_deactivateSearch();
diff --git a/mobile/apps/locker/lib/ui/pages/uploader_page.dart b/mobile/apps/locker/lib/ui/pages/uploader_page.dart
index c224996b4c..3df7e6cc9e 100644
--- a/mobile/apps/locker/lib/ui/pages/uploader_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/uploader_page.dart
@@ -20,9 +20,6 @@ import "package:locker/utils/bottom_sheet_illustration.dart";
import "package:locker/utils/error_sheet.dart";
import 'package:logging/logging.dart';
-/// Abstract base class that provides file upload functionality.
-/// Contains common file picking and uploading logic that can be reused
-/// across different pages like HomePage and CollectionPage.
abstract class UploaderPage extends BaseHomePage {
const UploaderPage({super.key});
}
@@ -30,14 +27,10 @@ abstract class UploaderPage extends BaseHomePage {
abstract class UploaderPageState<T extends UploaderPage> extends State<T> {
final _logger = Logger('UploaderPage');
- /// Returns the collection that should be pre-selected in the upload dialog.
- /// Return null to default to uncategorized collection.
Collection? get selectedCollection => null;
- /// Called after a successful file upload to refresh the UI
void onFileUploadComplete();
- /// Opens a file picker dialog and uploads the selected file
Future<bool> addFile() async {
final FilePickerResult? result = await FilePicker.pickFiles(
type: FileType.any,
diff --git a/mobile/apps/locker/lib/ui/utils/legacy_utils.dart b/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
index d86b6e8c51..75edcc197e 100644
--- a/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
+++ b/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
@@ -10,15 +10,10 @@ import "package:logging/logging.dart";
final _logger = Logger("LegacyUtils");
-/// Opens the Legacy (Emergency contacts) page after authenticating the user.
Future<void> openLegacyPage(BuildContext context) async {
await _openLegacy(context, showIntroWhenNoKits: false);
}
-/// Opens Legacy from a home onboarding entrypoint.
-///
-/// Users without a Legacy kit see the intro before setup. Users with an
-/// existing kit continue to the regular Legacy management page.
Future<void> openLegacyFromHome(BuildContext context) async {
await _openLegacy(context, showIntroWhenNoKits: true);
}
diff --git a/mobile/apps/locker/lib/utils/bottom_sheet_illustration.dart b/mobile/apps/locker/lib/utils/bottom_sheet_illustration.dart
index 8d660731ae..116550994f 100644
--- a/mobile/apps/locker/lib/utils/bottom_sheet_illustration.dart
+++ b/mobile/apps/locker/lib/utils/bottom_sheet_illustration.dart
@@ -1,6 +1,5 @@
import "package:flutter/material.dart";
-/// Standard Locker illustrations shown at the top of bottom sheets.
class LockerBottomSheetIllustration extends StatelessWidget {
const LockerBottomSheetIllustration._(this.assetPath);
diff --git a/mobile/apps/locker/lib/utils/collection_actions.dart b/mobile/apps/locker/lib/utils/collection_actions.dart
index 449c6f4c20..12127c34c8 100644
--- a/mobile/apps/locker/lib/utils/collection_actions.dart
+++ b/mobile/apps/locker/lib/utils/collection_actions.dart
@@ -23,11 +23,9 @@ import "package:locker/utils/bottom_sheet_illustration.dart";
import "package:locker/utils/error_sheet.dart";
import 'package:logging/logging.dart';
-/// Utility class for common collection actions like edit and delete
class CollectionActions {
static final _logger = Logger('CollectionActions');
- /// Shows a dialog sheet to create a new collection
static Future<Collection?> createCollection(
BuildContext context, {
bool autoSelectInParent = false,
@@ -231,7 +229,6 @@ class CollectionActions {
}
}
- /// Shows a confirmation dialog and deletes a collection
static Future<void> deleteCollection(
BuildContext context,
Collection collection, {
diff --git a/mobile/apps/locker/lib/utils/collection_list_util.dart b/mobile/apps/locker/lib/utils/collection_list_util.dart
index eadd996d56..59d6e7483f 100644
--- a/mobile/apps/locker/lib/utils/collection_list_util.dart
+++ b/mobile/apps/locker/lib/utils/collection_list_util.dart
@@ -1,7 +1,5 @@
import 'package:locker/services/collections/models/collection.dart';
-/// Returns a list of collections with duplicate IDs removed while preserving
-/// order.
List<Collection> uniqueCollectionsById(List<Collection> collections) {
final seenIds = <int>{};
return collections.where((collection) => seenIds.add(collection.id)).toList();
diff --git a/mobile/apps/locker/lib/utils/collection_sort_util.dart b/mobile/apps/locker/lib/utils/collection_sort_util.dart
index b9251f5259..19767f3189 100644
--- a/mobile/apps/locker/lib/utils/collection_sort_util.dart
+++ b/mobile/apps/locker/lib/utils/collection_sort_util.dart
@@ -1,8 +1,6 @@
import 'package:locker/services/collections/models/collection.dart';
-/// Utility class for sorting collections with consistent logic across the app
class CollectionSortUtil {
- /// Sorts collections with Important (favorites) collection first, then alphabetically by name
static void sortCollections(List<Collection> collections) {
collections.sort((a, b) {
// Important collection (favorites) should come first
@@ -21,14 +19,12 @@ class CollectionSortUtil {
});
}
- /// Returns a new sorted list of collections with Important (favorites) first
static List<Collection> getSortedCollections(List<Collection> collections) {
final sortedList = List<Collection>.from(collections);
sortCollections(sortedList);
return sortedList;
}
- /// Filters out the user's uncategorized collection and sorts the rest.
static List<Collection> filterAndSortCollections(
List<Collection> collections,
int userID,
@@ -42,8 +38,6 @@ class CollectionSortUtil {
return filtered;
}
- /// Compares two collections for sorting, prioritizing Important collection
- /// Returns -1 if a should come before b, 1 if b should come before a, 0 if equal
static int compareCollections(Collection a, Collection b) {
// Important collection (favorites) should come first
if (a.type == CollectionType.favorites &&
@@ -60,8 +54,6 @@ class CollectionSortUtil {
return nameA.toLowerCase().compareTo(nameB.toLowerCase());
}
- /// Compares two collections for sorting with Important always first regardless of sort direction
- /// Used for table sorting where Important should always be first
static int compareCollectionsWithFavoritesPriority(
Collection a,
Collection b,
@@ -80,8 +72,6 @@ class CollectionSortUtil {
return ascending ? compareCollections(a, b) : compareCollections(b, a);
}
- /// Compares two collections for date sorting with Important always first regardless of sort direction
- /// Used for table sorting where Important should always be first
static int compareCollectionsByDateWithFavoritesPriority(
Collection a,
Collection b,
diff --git a/mobile/apps/locker/lib/utils/error_sheet.dart b/mobile/apps/locker/lib/utils/error_sheet.dart
index f4b47bbeaf..fba6886a29 100644
--- a/mobile/apps/locker/lib/utils/error_sheet.dart
+++ b/mobile/apps/locker/lib/utils/error_sheet.dart
@@ -5,11 +5,6 @@ import "package:ente_utils/email_util.dart" show sendLogs;
import "package:flutter/material.dart";
import "package:locker/utils/bottom_sheet_illustration.dart";
-/// Shows Locker's standard generic-error bottom sheet.
-///
-/// Parses [error] into a user-facing message via [parseErrorForUI] and offers a
-/// "contact support" action that ships logs. Kept as a single helper so every
-/// catch block stays a one-liner instead of re-inlining the same sheet config.
Future<void> showLockerErrorSheet(BuildContext context, Object? error) {
return showErrorBottomSheetComponent<void>(
context: context,
diff --git a/mobile/apps/locker/lib/utils/file_actions.dart b/mobile/apps/locker/lib/utils/file_actions.dart
index df0d18008d..e696ebb479 100644
--- a/mobile/apps/locker/lib/utils/file_actions.dart
+++ b/mobile/apps/locker/lib/utils/file_actions.dart
@@ -25,11 +25,9 @@ import "package:locker/utils/bottom_sheet_illustration.dart";
import "package:locker/utils/error_sheet.dart";
import "package:logging/logging.dart";
-/// Utility class for common file actions like edit, share, delete, and favorites
class FileActions {
static final _logger = Logger("FileActions");
- /// Shows edit dialog for a file to update title
static Future<void> editFile(
BuildContext context,
EnteFile file, {
@@ -243,7 +241,6 @@ class FileActions {
).push(MaterialPageRoute(builder: (context) => page));
}
- /// Creates and shows a shareable link for a file
static Future<void> shareFileLink(BuildContext context, EnteFile file) async {
final dialog = createProgressDialog(
context,
@@ -279,7 +276,6 @@ class FileActions {
}
}
- /// Deletes a single file after confirmation
static Future<void> deleteFile(
BuildContext context,
EnteFile file, {
@@ -330,7 +326,6 @@ class FileActions {
}
}
- /// Deletes multiple files after confirmation
static Future<void> deleteMultipleFiles(
BuildContext context,
List<EnteFile> files, {
@@ -397,12 +392,10 @@ class FileActions {
}
}
- /// Checks if a file is marked as important using cache
static bool isImportant(EnteFile file) {
return FavoritesService.instance.isFavoriteCache(file);
}
- /// Toggles important status of a single file
static Future<void> markImportant(
BuildContext context,
EnteFile file, {
@@ -448,7 +441,6 @@ class FileActions {
}
}
- /// Marks multiple files as important
static Future<void> markMultipleImportant(
BuildContext context,
List<EnteFile> files, {
diff --git a/mobile/apps/locker/lib/utils/file_util.dart b/mobile/apps/locker/lib/utils/file_util.dart
index 5df554b2e5..86e196db8c 100644
--- a/mobile/apps/locker/lib/utils/file_util.dart
+++ b/mobile/apps/locker/lib/utils/file_util.dart
@@ -303,9 +303,6 @@ class FileUtil {
}
}
- /// Saves files using the platform's system file picker.
- /// On Android and iOS this shows a system sheet allowing the user
- /// to choose where to save the file.
static Future<String?> _saveFile({
required Uint8List bytes,
required String fileName,
diff --git a/mobile/apps/photos/lib/db/common/conflict_algo.dart b/mobile/apps/photos/lib/db/common/conflict_algo.dart
index b83bd58e15..081aacf804 100644
--- a/mobile/apps/photos/lib/db/common/conflict_algo.dart
+++ b/mobile/apps/photos/lib/db/common/conflict_algo.dart
@@ -1,39 +1,7 @@
enum SqliteAsyncConflictAlgorithm {
- /// When a constraint violation occurs, an immediate ROLLBACK occurs,
- /// thus ending the current transaction, and the command aborts with a
- /// return code of SQLITE_CONSTRAINT. If no transaction is active
- /// (other than the implied transaction that is created on every command)
- /// then this algorithm works the same as ABORT.
rollback,
-
- /// When a constraint violation occurs,no ROLLBACK is executed
- /// so changes from prior commands within the same transaction
- /// are preserved. This is the default behavior.
abort,
-
- /// When a constraint violation occurs, the command aborts with a return
- /// code SQLITE_CONSTRAINT. But any changes to the database that
- /// the command made prior to encountering the constraint violation
- /// are preserved and are not backed out.
fail,
-
- /// When a constraint violation occurs, the one row that contains
- /// the constraint violation is not inserted or changed.
- /// But the command continues executing normally. Other rows before and
- /// after the row that contained the constraint violation continue to be
- /// inserted or updated normally. No error is returned.
ignore,
-
- /// When a UNIQUE constraint violation occurs, the pre-existing rows that
- /// are causing the constraint violation are removed prior to inserting
- /// or updating the current row. Thus the insert or update always occurs.
- /// The command continues executing normally. No error is returned.
- /// If a NOT NULL constraint violation occurs, the NULL value is replaced
- /// by the default value for that column. If the column has no default
- /// value, then the ABORT algorithm is used. If a CHECK constraint
- /// violation occurs then the IGNORE algorithm is used. When this conflict
- /// resolution strategy deletes rows in order to satisfy a constraint,
- /// it does not invoke delete triggers on those rows.
- /// This behavior might change in a future release.
replace,
}
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dart
index b05ace23b2..d090ae3caa 100644
--- a/mobile/apps/photos/lib/db/files_db.dart
+++ b/mobile/apps/photos/lib/db/files_db.dart
@@ -60,21 +60,19 @@ class FilesDB with SqlDbBase {
static const columnMetadataDecryptionHeader = 'metadata_decryption_header';
static const columnFileSize = 'file_size';
- // MMD -> Magic Metadata
+ // MMD is magic metadata.
static const columnMMdEncodedJson = 'mmd_encoded_json';
static const columnMMdVersion = 'mmd_ver';
static const columnPubMMdEncodedJson = 'pub_mmd_encoded_json';
static const columnPubMMdVersion = 'pub_mmd_ver';
- // part of magic metadata
- // Only parse & store selected fields from JSON in separate columns if
- // we need to write query based on that field
+ // JSON fields become columns only when needed for queries.
static const columnMMdVisibility = 'mmd_visibility';
- //If adding or removing a new column, make sure to update the `_columnNames` list
- //and update `_generateColumnsAndPlaceholdersForInsert` and
- //`_generateUpdateAssignmentsWithPlaceholders`
+ // When columns change, also update _columnNames,
+ // _generateColumnsAndPlaceholdersForInsert, and
+ // _generateUpdateAssignmentsWithPlaceholders.
static final _migrationScripts = [
...createTable(filesTable),
...alterDeviceFolderToAllowNULL(),
@@ -124,21 +122,17 @@ class FilesDB with SqlDbBase {
columnAddedTime,
];
- // make this a singleton class
FilesDB._privateConstructor();
static final FilesDB instance = FilesDB._privateConstructor();
- // only have a single app-wide reference to the database
static Future<SqliteDatabase>? _sqliteAsyncDBFuture;
Future<SqliteDatabase> get sqliteAsyncDB async {
- // lazily instantiate the db the first time it is accessed
_sqliteAsyncDBFuture ??= _initSqliteAsyncDatabase();
return _sqliteAsyncDBFuture!;
}
- // this opens the database (and creates it if it doesn't exist)
Future<SqliteDatabase> _initSqliteAsyncDatabase() async {
final Directory documentsDirectory =
await getApplicationDocumentsDirectory();
@@ -149,7 +143,6 @@ class FilesDB with SqlDbBase {
return database;
}
- // SQL code to create the database table
static List<String> createTable(String tableName) {
return [
'''
@@ -451,7 +444,6 @@ class FilesDB with SqlDbBase {
.where((column) => column != columnGeneratedID)
.toList();
- // Sort files into appropriate parameter sets
for (final file in files) {
if (file.generatedID == null) {
withoutIdParams.add(_getParameterSetForFile(file));
@@ -479,7 +471,6 @@ class FilesDB with SqlDbBase {
}
}
- // Insert any remaining files
if (withIdParams.isNotEmpty) {
await _insertBatch(
conflictAlgorithm,
@@ -584,10 +575,6 @@ class FilesDB with SqlDbBase {
return ids;
}
- /// Checks which (fileID, collectionID) pairs exist in the database.
- ///
- /// Returns a map keyed by collection ID, with each value containing
- /// the existing file IDs for that collection.
Future<Map<int, Set<int>>> getExistingFileIDsByCollection(
Set<(int fileID, int collectionID)> pairs,
) async {
@@ -858,10 +845,6 @@ class FilesDB with SqlDbBase {
return files;
}
- /// Gets multiple uploaded files by their IDs in a single query.
- ///
- /// Returns files in the same order as [fileIDs], with null for missing files.
- /// More efficient than calling [getUploadedFile] multiple times.
Future<List<EnteFile?>> getUploadedFilesBatch(
List<int> fileIDs,
int collectionID,
@@ -880,7 +863,6 @@ class FilesDB with SqlDbBase {
final results = await db.getAll(query, [...fileIDs, collectionID]);
final files = convertToFiles(results);
- // Build a map for O(1) lookup
final fileMap = <int, EnteFile>{};
for (final file in files) {
if (file.uploadedFileID != null) {
@@ -892,12 +874,6 @@ class FilesDB with SqlDbBase {
return fileIDs.map((id) => fileMap[id]).toList();
}
- /// Gets files added by other users to user's collections.
- ///
- /// Returns files where owner_id != currentUserID, ordered by added_time DESC.
- /// Used to populate the feed with shared photo items.
- /// Hidden collections are filtered downstream in _filterFeedItems.
- /// Offset is supported for paged fetches while aggregating feed groups.
Future<List<EnteFile>> getRecentlySharedFiles({
required int currentUserID,
int limit = 100,
@@ -1003,8 +979,6 @@ class FilesDB with SqlDbBase {
);
}
- // Files which user added to a collection manually but they are not
- // uploaded yet or files belonging to a collection which is marked for backup
Future<List<EnteFile>> getFilesPendingForUpload() async {
final db = await instance.sqliteAsyncDB;
final results = await db.getAll(
@@ -1015,8 +989,6 @@ class FilesDB with SqlDbBase {
'ORDER BY $columnCreationTime DESC',
);
final files = convertToFiles(results);
- // future-safe filter just to ensure that the query doesn't end up returning files
- // which should not be backed up
files.removeWhere(
(e) =>
e.collectionID == null ||
@@ -1119,9 +1091,7 @@ class FilesDB with SqlDbBase {
return result;
}
- // remove references for local files which are either already uploaded
- // or queued for upload but not yet uploaded
- // Remove queued local files that have duplicate uploaded entries with same localID
+ // Remove queued rows whose local IDs also have uploaded rows.
Future<int> removeQueuedLocalFiles(Set<String> localIDs, int ownerID) async {
if (localIDs.isEmpty) {
_logger.finest("No local IDs provided for removal");
@@ -1140,7 +1110,6 @@ class FilesDB with SqlDbBase {
final batch = localIDsList.sublist(i, endIndex);
final placeholders = List.filled(batch.length, '?').join(',');
- // Find localIDs that already have uploaded entries
final result = await db.execute('''
SELECT DISTINCT $columnLocalID
FROM $filesTable
@@ -1159,15 +1128,13 @@ class FilesDB with SqlDbBase {
'?',
).join(',');
- // Delete queued entries for localIDs that already have uploaded versions
final deleteResult = await db.execute('''
DELETE FROM $filesTable
WHERE $columnLocalID IN ($localIdPlaceholder)
AND ($columnUploadedFileID IS NULL OR $columnUploadedFileID = -1)
''', alreadyUploadedLocalIDs);
- final removedCount =
- deleteResult.length; // or however your DB returns affected rows
+ final removedCount = deleteResult.length;
if (removedCount > 0) {
_logger.warning(
"Batch ${(i ~/ batchSize) + 1}: Removed $removedCount queued duplicates",
@@ -1202,8 +1169,6 @@ class FilesDB with SqlDbBase {
return result;
}
- // Sets the collectionID for the files with given LocalIDs if the
- // corresponding file entries are not already mapped to some other collection
Future<void> setCollectionIDForUnMappedLocalFiles(
int collectionID,
Set<String> localIDs,
@@ -1433,7 +1398,7 @@ class FilesDB with SqlDbBase {
Future<void> deleteLocalFile(EnteFile file) async {
final db = await instance.sqliteAsyncDB;
if (file.localID != null) {
- // delete all files with same local ID
+ // Delete every queued row with the same local ID.
unawaited(
db.execute(
'DELETE FROM $filesTable WHERE $columnLocalID = ? AND ($columnUploadedFileID IS NULL OR $columnUploadedFileID = -1)',
@@ -1601,8 +1566,6 @@ class FilesDB with SqlDbBase {
return result;
}
- // getCollectionLatestFileTime returns map of collectionID to the max
- // creationTime of the files in the collection.
Future<Map<int, int>> getCollectionIDToMaxCreationTime() async {
final enteWatch = EnteWatch("getCollectionIDToMaxCreationTime")..start();
final db = await instance.sqliteAsyncDB;
@@ -1638,8 +1601,6 @@ class FilesDB with SqlDbBase {
return result;
}
- // getCollectionFileFirstOrLast returns the first or last uploaded file in
- // the collection based on the given collectionID and the order.
Future<EnteFile?> getCollectionFileFirstOrLast(
int collectionID,
bool sortAsc,
@@ -1843,7 +1804,7 @@ class FilesDB with SqlDbBase {
}
}
- ///Each collectionIDs in list aren't necessarily unique
+ // Collection IDs may repeat.
Future<List<int>> getAllCollectionIDsOfFiles(
List<int> uploadedFileIDs,
) async {
@@ -1861,8 +1822,6 @@ class FilesDB with SqlDbBase {
return collectionIDsOfFiles;
}
- /// Returns only uploaded file IDs from given collections.
- /// If [ownerID] is provided, only returns files owned by that user.
Future<List<int>> getUploadedFileIDsInCollections(
Set<int> collectionIds, {
int? ownerID,
@@ -1891,8 +1850,6 @@ class FilesDB with SqlDbBase {
return results.map((row) => row[columnUploadedFileID] as int).toList();
}
- /// Returns only collection IDs that contain any of the given uploaded file
- /// IDs.
Future<Set<int>> getCollectionIDsForUploadedFileIDs(
List<int> uploadedFileIds,
) async {
@@ -1926,7 +1883,6 @@ class FilesDB with SqlDbBase {
return files;
}
- // For a given userID, return unique uploadedFileId for the given userID
Future<List<int>> getUploadIDsWithMissingSize(int userId) async {
final db = await instance.sqliteAsyncDB;
final rows = await db.getAll(
@@ -1943,8 +1899,6 @@ class FilesDB with SqlDbBase {
return result;
}
- // updateSizeForUploadIDs takes a map of upploadedFileID and fileSize and
- // update the fileSize for the given uploadedFileID
Future<void> updateSizeForUploadIDs(
Map<int, int> uploadedFileIDToSize,
) async {
@@ -2079,10 +2033,6 @@ class FilesDB with SqlDbBase {
return ids.length;
}
- /// Returns hidden files that have local copies on the device.
- /// Only returns files owned by [ownerID] from the specified
- /// [hiddenCollectionIds].
- /// Results are deduplicated by uploadedFileID
Future<List<EnteFile>> getHiddenFilesWithLocalCopy(
Set<int> hiddenCollectionIds,
int ownerID,
@@ -2107,7 +2057,6 @@ class FilesDB with SqlDbBase {
return convertToFiles(results);
}
- /// Returns true if there are any hidden files with local copies on the device.
Future<bool> hasHiddenFilesWithLocalCopy(
Set<int> hiddenCollectionIds,
int ownerID,
@@ -2131,9 +2080,7 @@ class FilesDB with SqlDbBase {
return results.isNotEmpty;
}
- /// Clears localID for all rows matching any of the given uploadedFileIDs.
- /// This is used when deleting files from device to ensure all collection
- /// entries for the same file have their localID cleared.
+ // Clear every collection row for each uploaded file.
Future<void> clearLocalIDsForUploadedFileIDs(
List<int> uploadedFileIDs,
) async {
@@ -2149,7 +2096,6 @@ class FilesDB with SqlDbBase {
''');
}
- ///Returns "columnName1 = ?, columnName2 = ?, ..."
String _generateUpdateAssignmentsWithPlaceholders({
required int? fileGenId,
bool omitCollectionId = false,
@@ -2231,9 +2177,6 @@ class FilesDB with SqlDbBase {
longitude,
getInt(file.fileType),
file.modificationTime,
- // encrypted_key/key_decryption_nonce are per-collection (the file key
- // wrapped with that collection's key), so they must be omitted from a
- // cross-collection update to avoid overwriting sibling rows.
if (!omitKeyMaterial) file.encryptedKey,
if (!omitKeyMaterial) file.keyDecryptionNonce,
file.fileDecryptionHeader,
diff --git a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart
index 7d96923177..598735429c 100644
--- a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart
+++ b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart
@@ -2,9 +2,6 @@ import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:photos/db/ml/schema.dart";
import "package:photos/models/ml/ml_versions.dart";
-// ── Pet Face DB Mapper ──
-
-/// Represents a row in the [petFacesTable].
class DBPetFace {
final int fileId;
final String petFaceId;
@@ -43,8 +40,7 @@ class DBPetFace {
};
}
- /// Creates a dummy entry to mark a file as pet-indexed when no pets were
- /// found, matching how [Face.empty] works for human face detection.
+ // Sentinel rows mark files with no pet results.
factory DBPetFace.empty(int fileId, {bool error = false}) {
return DBPetFace(
fileId: fileId,
@@ -74,9 +70,6 @@ class DBPetFace {
}
}
-// ── Detected Object DB Mapper ──
-
-/// Represents a row in the [petBodiesTable].
class DBPetBody {
final int fileId;
final String petBodyId;
diff --git a/mobile/apps/photos/lib/db/social_db.dart b/mobile/apps/photos/lib/db/social_db.dart
index 7ae5d80ced..94dc8d12a8 100644
--- a/mobile/apps/photos/lib/db/social_db.dart
+++ b/mobile/apps/photos/lib/db/social_db.dart
@@ -94,7 +94,6 @@ class SocialDB {
)
''');
- // Create indexes for common queries
await db.execute(
'CREATE INDEX idx_comments_file_collection ON $_commentsTable(file_id, collection_id)',
);
@@ -103,8 +102,6 @@ class SocialDB {
);
}
- // ============ Comment Methods ============
-
Future<void> addComment(Comment comment) async {
final db = await database;
await db.insert(
@@ -153,8 +150,7 @@ class SocialDB {
return rows.map(_rowToComment).toList();
}
- /// Restricts the lookup to [candidateCollectionIDs] so the composite
- /// file/collection index can narrow the rows considered for the latest item.
+ // Candidate collections let the file/collection index narrow this lookup.
Future<Comment?> getLatestCommentForFile(
int fileID, {
required List<int> candidateCollectionIDs,
@@ -293,8 +289,6 @@ class SocialDB {
return rows.map(_rowToComment).toList();
}
- // ============ Reaction Methods ============
-
Future<List<Reaction>> getReactionsForFile(int fileID) async {
final db = await database;
final rows = await db.query(
@@ -364,8 +358,6 @@ class SocialDB {
return rows.map(_rowToReaction).toList();
}
- // ============ Sync Time Methods ============
-
Future<int> getCommentsSyncTime(int collectionID) async {
final db = await database;
final rows = await db.query(
@@ -426,7 +418,6 @@ class SocialDB {
Future<void> setAnonProfilesSyncTime(int collectionID, int syncTime) async {
final db = await database;
- // First check if the row exists
final rows = await db.query(
_syncTimeTable,
where: 'collection_id = ?',
@@ -447,8 +438,6 @@ class SocialDB {
}
}
- // ============ Bulk Upsert Methods ============
-
Future<void> upsertComments(List<Comment> comments) async {
if (comments.isEmpty) return;
final db = await database;
@@ -463,9 +452,6 @@ class SocialDB {
await batch.commit(noResult: true);
}
- /// Resolves `parent_comment_user_id` for reply comments by looking up the
- /// parent comment's `user_id`. Only processes rows where the field is still
- /// NULL, making it idempotent.
Future<void> resolveParentCommentUserIDs(int collectionID) async {
final db = await database;
await db.rawUpdate(
@@ -496,8 +482,6 @@ class SocialDB {
await batch.commit(noResult: true);
}
- // ============ Anon Profile Methods ============
-
Future<void> upsertAnonProfiles(List<AnonProfile> profiles) async {
if (profiles.isEmpty) return;
final db = await database;
@@ -538,10 +522,6 @@ class SocialDB {
return _rowToAnonProfile(rows.first);
}
- // ============ Feed Query Methods ============
-
- /// Gets all reactions on files (photo likes) excluding the current user's reactions.
- /// Returns reactions sorted by created_at DESC.
Future<List<Reaction>> getReactionsOnFiles({
required int excludeUserID,
int limit = 100,
@@ -560,8 +540,6 @@ class SocialDB {
return rows.map(_rowToReaction).toList();
}
- /// Gets all comments on files excluding the current user's comments.
- /// Returns comments sorted by created_at DESC.
Future<List<Comment>> getCommentsOnFiles({
required int excludeUserID,
int limit = 100,
@@ -580,15 +558,12 @@ class SocialDB {
return rows.map(_rowToComment).toList();
}
- /// Gets all replies to comments, excluding the current user's own replies.
- /// Returns replies sorted by created_at DESC.
Future<List<Comment>> getReplies({
required int excludeUserID,
int limit = 100,
int offset = 0,
}) async {
final db = await database;
- // Get all replies excluding the current user's own replies
final rows = await db.query(
_commentsTable,
where:
@@ -601,16 +576,12 @@ class SocialDB {
return rows.map(_rowToComment).toList();
}
- /// Gets all reactions on top-level comments, excluding the current user's reactions.
- /// Returns reactions sorted by created_at DESC.
Future<List<Reaction>> getReactionsOnUserComments({
required int targetUserID,
int limit = 100,
int offset = 0,
}) async {
final db = await database;
- // Get all reactions on comments (not on files) excluding current user's
- // Join to ensure we only get reactions on top-level comments (not replies)
final rows = await db.rawQuery(
'''
SELECT r.* FROM $_reactionsTable r
@@ -625,15 +596,12 @@ class SocialDB {
return rows.map(_rowToReaction).toList();
}
- /// Gets all reactions on replies, excluding the current user's reactions.
- /// Returns reactions sorted by created_at DESC.
Future<List<Reaction>> getReactionsOnUserReplies({
required int targetUserID,
int limit = 100,
int offset = 0,
}) async {
final db = await database;
- // Get all reactions on replies excluding current user's
final rows = await db.rawQuery(
'''
SELECT r.* FROM $_reactionsTable r
@@ -648,8 +616,6 @@ class SocialDB {
return rows.map(_rowToReaction).toList();
}
- /// Gets all reactions on files after [sinceTime], excluding the current user.
- /// Returns reactions sorted by created_at DESC.
Future<List<Reaction>> getReactionsOnFilesSince({
required int excludeUserID,
required int sinceTime,
@@ -666,8 +632,6 @@ class SocialDB {
return rows.map(_rowToReaction).toList();
}
- /// Gets all comments on files after [sinceTime], excluding the current user.
- /// Returns comments sorted by created_at DESC.
Future<List<Comment>> getCommentsOnFilesSince({
required int excludeUserID,
required int sinceTime,
@@ -684,8 +648,6 @@ class SocialDB {
return rows.map(_rowToComment).toList();
}
- /// Gets all replies after [sinceTime], excluding the current user.
- /// Returns replies sorted by created_at DESC.
Future<List<Comment>> getRepliesSince({
required int excludeUserID,
required int sinceTime,
@@ -702,8 +664,6 @@ class SocialDB {
return rows.map(_rowToComment).toList();
}
- // ============ Cleanup Methods ============
-
Future<void> deleteCollectionData(int collectionID) async {
final db = await database;
await db.delete(
@@ -742,12 +702,8 @@ class SocialDB {
return await db.delete(_reactionsTable);
}
- // ============ Debug Methods ============
-
Future<void> seedExampleData() async {}
- // ============ Row Mappers ============
-
Map<String, dynamic> _commentToRow(Comment comment) {
return {
'id': comment.id,
diff --git a/mobile/packages/account_deletion/lib/src/account_deletion_host.dart b/mobile/packages/account_deletion/lib/src/account_deletion_host.dart
index 85bae3239b..4208727ca2 100644
--- a/mobile/packages/account_deletion/lib/src/account_deletion_host.dart
+++ b/mobile/packages/account_deletion/lib/src/account_deletion_host.dart
@@ -1,6 +1,4 @@
abstract class AccountDeletionHost {
- /// Decrypts the account deletion challenge using the host's keypair and
- /// returns the decoded challenge that is sent back to the server.
String decryptDeleteChallenge(String encryptedChallenge);
Future<void> logout();
diff --git a/mobile/packages/accounts/lib/models/two_factor.dart b/mobile/packages/accounts/lib/models/two_factor.dart
index 45f7c8fde8..bebdbb27fe 100644
--- a/mobile/packages/accounts/lib/models/two_factor.dart
+++ b/mobile/packages/accounts/lib/models/two_factor.dart
@@ -1,6 +1,5 @@
enum TwoFactorType { totp, passkey }
-// ToString for TwoFactorType
String twoFactorTypeToString(TwoFactorType type) {
switch (type) {
case TwoFactorType.totp:
diff --git a/mobile/packages/accounts/lib/models/user_details.dart b/mobile/packages/accounts/lib/models/user_details.dart
index ae651c9d67..23d8a44b4a 100644
--- a/mobile/packages/accounts/lib/models/user_details.dart
+++ b/mobile/packages/accounts/lib/models/user_details.dart
@@ -29,38 +29,28 @@ class UserDetails {
this.lockerFamilyUsage,
);
- // Locker-specific limits computed client-side based on subscription
- // Free tier: 100 files, 1GB storage
- // Paid tier: 1000 files, 10GB storage
static const int _lockerFileLimitFree = 100;
static const int _lockerFileLimitPaid = 1000;
- static const int _lockerStorageLimitFree = 1 * 1024 * 1024 * 1024; // 1GB
- static const int _lockerStorageLimitPaid = 10 * 1024 * 1024 * 1024; // 10GB
+ static const int _lockerStorageLimitFree = 1 * 1024 * 1024 * 1024;
+ static const int _lockerStorageLimitPaid = 10 * 1024 * 1024 * 1024;
- /// Returns true if user has paid access (direct subscription, family plan,
- /// or paid add-ons)
bool hasPaidSubscription() {
- // Direct paid subscription
if (!subscription.isFreePlan() && subscription.isValid()) {
return true;
}
- // Family plan member
if (isPartOfFamily()) {
return true;
}
- // Has paid add-ons
if (hasPaidAddon()) {
return true;
}
return false;
}
- /// Returns the locker file limit based on subscription status
int getLockerFileLimit() {
return hasPaidSubscription() ? _lockerFileLimitPaid : _lockerFileLimitFree;
}
- /// Returns the locker storage limit based on subscription status
int getLockerStorageLimit() {
return hasPaidSubscription()
? _lockerStorageLimitPaid
@@ -83,9 +73,6 @@ class UserDetails {
return currentUserMember.isAdmin;
}
- // getFamilyOrPersonalUsage will return total usage for family if user
- // belong to family group. Otherwise, it will return storage consumed by
- // current user
int getFamilyOrPersonalUsage() {
return isPartOfFamily() ? familyData!.getTotalUsage() : usage;
}
@@ -98,15 +85,11 @@ class UserDetails {
return max(getTotalStorage() - getFamilyOrPersonalUsage(), 0);
}
- // getTotalStorage will return total storage available including the
- // storage bonus
int getTotalStorage() {
return (isPartOfFamily() ? familyData!.storage : subscription.storage) +
storageBonus;
}
- // return the member storage limit if user is part of family and the admin
- // has set the storage limit for the user.
int? familyMemberStorageLimit() {
if (isPartOfFamily()) {
try {
@@ -121,7 +104,6 @@ class UserDetails {
return null;
}
- // This is the total storage for which user has paid for.
int getPlanPlusAddonStorage() {
return (isPartOfFamily() ? familyData!.storage : subscription.storage) +
bonusData!.totalAddOnBonus();
@@ -213,14 +195,12 @@ class ProfileData {
bool isEmailMFAEnabled;
bool isTwoFactorEnabled;
- // Constructor with default values
ProfileData({
this.canDisableEmailMFA = false,
this.isEmailMFAEnabled = false,
this.isTwoFactorEnabled = false,
});
- // Factory method to create ProfileData instance from JSON
factory ProfileData.fromJson(Map<String, dynamic>? json) {
return ProfileData(
canDisableEmailMFA: json?['canDisableEmailMFA'] ?? false,
@@ -229,7 +209,6 @@ class ProfileData {
);
}
- // Method to convert ProfileData instance to JSON
Map<String, dynamic> toJson() {
return {
'canDisableEmailMFA': canDisableEmailMFA,
@@ -244,7 +223,6 @@ class ProfileData {
class FamilyData {
final List<FamilyMember>? members;
- // Storage available based on the family plan
final int storage;
final int expiryTime;
diff --git a/mobile/packages/accounts/lib/pages/email_entry_page.dart b/mobile/packages/accounts/lib/pages/email_entry_page.dart
index 67ff0ebc00..e30b43d355 100644
--- a/mobile/packages/accounts/lib/pages/email_entry_page.dart
+++ b/mobile/packages/accounts/lib/pages/email_entry_page.dart
@@ -74,7 +74,6 @@ class _EmailEntryPageState extends State<EmailEntryPage> {
Widget build(BuildContext context) {
final isKeypadOpen = MediaQuery.of(context).viewInsets.bottom > 100;
- // Initialize theme-aware color
final colorScheme = getEnteColorScheme(context);
_validFieldValueColor = colorScheme.primary700.withValues(alpha: 0.2);
diff --git a/mobile/packages/accounts/lib/pages/login_page.dart b/mobile/packages/accounts/lib/pages/login_page.dart
index 8cfd2a1902..07cf4b9450 100644
--- a/mobile/packages/accounts/lib/pages/login_page.dart
+++ b/mobile/packages/accounts/lib/pages/login_page.dart
@@ -189,7 +189,6 @@ class _LoginPageState extends State<LoginPage> {
},
autocorrect: false,
keyboardType: TextInputType.emailAddress,
- //initialValue: _email,
autofocus: true,
),
const SizedBox(height: 24),
diff --git a/mobile/packages/accounts/lib/pages/login_pwd_verification_page.dart b/mobile/packages/accounts/lib/pages/login_pwd_verification_page.dart
index 04286e0c78..56d3d059b6 100644
--- a/mobile/packages/accounts/lib/pages/login_pwd_verification_page.dart
+++ b/mobile/packages/accounts/lib/pages/login_pwd_verification_page.dart
@@ -13,11 +13,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import "package:logging/logging.dart";
-// LoginPasswordVerificationPage is a page that allows the user to enter their password to verify their identity.
-// If the password is correct, then the user is either directed to
-// PasswordReentryPage (if the user has not yet set up 2FA) or TwoFactorAuthenticationPage (if the user has set up 2FA).
-// In the PasswordReentryPage, the password is auto-filled based on the
-// volatile password.
class LoginPasswordVerificationPage extends StatefulWidget {
final BaseConfiguration config;
final SrpAttributes srpAttributes;
@@ -155,7 +150,7 @@ class _LoginPasswordVerificationPageState
await dialog.hide();
if (e is LoginKeyDerivationError) {
_logger.severe('loginKey derivation error', e, s);
- // LoginKey err, perform regular login via ott verification
+ // Fall back to OTT when login-key derivation fails.
await UserService.instance.sendOtt(
context.mounted ? context : null,
email!,
@@ -166,7 +161,7 @@ class _LoginPasswordVerificationPageState
if (!context.mounted) {
return;
}
- // device is not powerful enough to perform derive key
+ // This device cannot derive the key; offer recovery instead.
final result = await showAlertBottomSheet<bool>(
context,
title: context.strings.recreatePasswordTitle,
@@ -269,8 +264,7 @@ class _LoginPasswordVerificationPageState
),
const SizedBox(height: 8),
Visibility(
- // hidden textForm for suggesting auto-fill service for saving
- // password
+ // Prompts platform password saving.
visible: false,
child: TextFormField(
autofillHints: const [AutofillHints.email],
diff --git a/mobile/packages/accounts/lib/pages/passkey_page.dart b/mobile/packages/accounts/lib/pages/passkey_page.dart
index 8677a3a5dd..089e1bff13 100644
--- a/mobile/packages/accounts/lib/pages/passkey_page.dart
+++ b/mobile/packages/accounts/lib/pages/passkey_page.dart
@@ -148,7 +148,6 @@ class _PasskeyPageState extends State<PasskeyPage> {
Future<bool> _initDeepLinks() async {
final appLinks = AppLinks();
- // Attach a listener to the stream
appLinks.stringLinkStream.listen(
_handleDeeplink,
onError: (err) {
diff --git a/mobile/packages/accounts/lib/pages/password_entry_page.dart b/mobile/packages/accounts/lib/pages/password_entry_page.dart
index 4e8b8eb7c4..24801a5d2d 100644
--- a/mobile/packages/accounts/lib/pages/password_entry_page.dart
+++ b/mobile/packages/accounts/lib/pages/password_entry_page.dart
@@ -223,8 +223,7 @@ class _PasswordEntryPageState extends State<PasswordEntryPage> {
),
const SizedBox(height: 8),
Visibility(
- // hidden textForm for suggesting auto-fill service for saving
- // password
+ // Prompts platform password saving.
visible: false,
child: TextFormField(
autofillHints: const [AutofillHints.email],
diff --git a/mobile/packages/accounts/lib/pages/password_reentry_page.dart b/mobile/packages/accounts/lib/pages/password_reentry_page.dart
index 2797227fa9..3879846133 100644
--- a/mobile/packages/accounts/lib/pages/password_reentry_page.dart
+++ b/mobile/packages/accounts/lib/pages/password_reentry_page.dart
@@ -237,8 +237,7 @@ class _PasswordReentryPageState extends State<PasswordReentryPage> {
),
const SizedBox(height: 8),
Visibility(
- // hidden textForm for suggesting auto-fill service for saving
- // password
+ // Prompts platform password saving.
visible: false,
child: TextFormField(
autofillHints: const [AutofillHints.email],
diff --git a/mobile/packages/accounts/lib/pages/request_pwd_verification_page.dart b/mobile/packages/accounts/lib/pages/request_pwd_verification_page.dart
index 74d2fea526..db5cf38ae7 100644
--- a/mobile/packages/accounts/lib/pages/request_pwd_verification_page.dart
+++ b/mobile/packages/accounts/lib/pages/request_pwd_verification_page.dart
@@ -100,7 +100,6 @@ class _RequestPasswordVerificationPageState
CryptoUtil.base642bin(attributes.keyDecryptionNonce),
);
await dialog.show();
- // pop
await widget.onPasswordVerified(keyEncryptionKey);
await dialog.hide();
if (context.mounted) {
@@ -153,8 +152,7 @@ class _RequestPasswordVerificationPageState
),
),
Visibility(
- // hidden textForm for suggesting auto-fill service for saving
- // password
+ // Prompts platform password saving.
visible: false,
child: TextFormField(
autofillHints: const [AutofillHints.email],
diff --git a/mobile/packages/accounts/lib/services/user_service.dart b/mobile/packages/accounts/lib/services/user_service.dart
index bae19ea928..1a6a0a9397 100644
--- a/mobile/packages/accounts/lib/services/user_service.dart
+++ b/mobile/packages/accounts/lib/services/user_service.dart
@@ -190,8 +190,6 @@ class UserService {
);
}
- // getPublicKey returns null value if email id is not
- // associated with another ente account
Future<String?> getPublicKey(String email) async {
try {
final response = await _enteDio.get(
@@ -230,7 +228,6 @@ class UserService {
userDetails.profileData!.canDisableEmailMFA,
);
}
- // handle email change from different client
if (userDetails.email != _config.getEmail()) {
await setEmail(userDetails.email);
}
@@ -310,8 +307,7 @@ class UserService {
}
_logger.severe(e);
- //This future is for waiting for the dialog from which logout() is called
- //to close and only then to show the error dialog.
+ // Let the logout dialog close before showing the error.
Future.delayed(const Duration(milliseconds: 150), () {
if (context.mounted) {
unawaited(showGenericErrorDialog(context: context, error: e));
@@ -477,7 +473,6 @@ class UserService {
(route) => route.isFirst,
);
} else {
- // should never reach here
throw Exception("unexpected response during email verification");
}
} on DioException catch (e) {
@@ -826,7 +821,6 @@ class UserService {
);
}
} else {
- // should never reach here
throw Exception("unexpected response during email verification");
}
}
diff --git a/mobile/packages/backup_exclusion/lib/backup_exclusion.dart b/mobile/packages/backup_exclusion/lib/backup_exclusion.dart
index 5a347aa655..575f3b7b2e 100644
--- a/mobile/packages/backup_exclusion/lib/backup_exclusion.dart
+++ b/mobile/packages/backup_exclusion/lib/backup_exclusion.dart
@@ -7,22 +7,13 @@ import 'package:logging/logging.dart';
final _logger = Logger('BackupExclusion');
const _channel = MethodChannel('io.ente.backup_exclusion');
-/// Marks [path] as excluded from iCloud and local backups on iOS.
-///
-/// Called on every app init rather than once, so the flag is re-applied after
-/// device restores (where directories are recreated without the attribute).
-/// The syscall is idempotent and has negligible overhead.
-///
-/// No-op on non-iOS platforms.
+// Reapply on every app init: device restores recreate directories without it.
+// The operation is idempotent and cheap.
Future<void> excludeFromBackup(String path) async {
if (!Platform.isIOS) return;
await _invokeExcludeFromBackup(path);
}
-/// Invokes the platform channel directly, without the iOS platform guard.
-///
-/// Exposed for unit testing so tests can exercise the channel logic and
-/// logging behaviour without needing to fake [Platform.isIOS].
@visibleForTesting
Future<void> invokeExcludeFromBackup(String path) =>
_invokeExcludeFromBackup(path);
diff --git a/mobile/packages/configuration/lib/base_configuration.dart b/mobile/packages/configuration/lib/base_configuration.dart
index 5a9d41f10d..0e85333893 100644
--- a/mobile/packages/configuration/lib/base_configuration.dart
+++ b/mobile/packages/configuration/lib/base_configuration.dart
@@ -112,18 +112,13 @@ abstract class BaseConfiguration {
}
Future<KeyGenResult> generateKey(String password) async {
- // Create a master key
final masterKey = CryptoUtil.generateKey();
- // Create a recovery key
final recoveryKey = CryptoUtil.generateKey();
- // Encrypt master key and recovery key with each other
final encryptedMasterKey = CryptoUtil.encryptSync(masterKey, recoveryKey);
final encryptedRecoveryKey = CryptoUtil.encryptSync(recoveryKey, masterKey);
- // Derive a key from the password that will be used to encrypt and
- // decrypt the master key
final kekSalt = CryptoUtil.getSaltToDeriveKey();
final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
utf8.encode(password),
@@ -131,13 +126,11 @@ abstract class BaseConfiguration {
);
final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
- // Encrypt the key with this derived key
final encryptedKeyData = CryptoUtil.encryptSync(
masterKey,
derivedKeyResult.key,
);
- // Generate a public-private keypair and encrypt the latter
final keyPair = CryptoUtil.generateKeyPair();
final encryptedSecretKeyData = CryptoUtil.encryptSync(
keyPair.secretKey,
@@ -169,11 +162,8 @@ abstract class BaseConfiguration {
Future<Tuple2<KeyAttributes, Uint8List>> getAttributesForNewPassword(
String password,
) async {
- // Get master key
final masterKey = getKey();
- // Derive a key from the password that will be used to encrypt and
- // decrypt the master key
final kekSalt = CryptoUtil.getSaltToDeriveKey();
final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
utf8.encode(password),
@@ -181,7 +171,6 @@ abstract class BaseConfiguration {
);
final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
- // Encrypt the key with this derived key
final encryptedKeyData = CryptoUtil.encryptSync(
masterKey!,
derivedKeyResult.key,
@@ -199,10 +188,6 @@ abstract class BaseConfiguration {
return Tuple2(updatedAttributes, loginKey);
}
- // decryptSecretsAndGetLoginKey decrypts the master key and recovery key
- // with the given password and save them in local secure storage.
- // This method also returns the keyEncKey that can be used for performing
- // SRP setup for existing users.
Future<Uint8List> decryptSecretsAndGetKeyEncKey(
String password,
KeyAttributes attributes, {
@@ -248,7 +233,6 @@ abstract class BaseConfiguration {
}
Future<void> recover(String recoveryKey) async {
- // check if user has entered mnemonic code
if (recoveryKey.contains(' ')) {
final split = recoveryKey.split(' ');
if (split.length != mnemonicKeyWordCount) {
@@ -303,9 +287,6 @@ abstract class BaseConfiguration {
return savedEndpoint;
}
- // isEnteProduction checks if the current endpoint is the default production
- // endpoint. This is used to determine if the app is in production mode or
- // not. The default production endpoint is set in the environment variable
bool isEnteProduction() {
return getHttpEndpoint() == kDefaultProductionEndpoint;
}
@@ -403,7 +384,7 @@ abstract class BaseConfiguration {
);
}
- // Caution: This directory is cleared on app start
+ // This directory is cleared on app start.
String getTempDirectory() {
return _tempDocumentsDirPath;
}
diff --git a/mobile/packages/contacts/lib/contacts.dart b/mobile/packages/contacts/lib/contacts.dart
index f1ec673c34..1af6c3fed9 100644
--- a/mobile/packages/contacts/lib/contacts.dart
+++ b/mobile/packages/contacts/lib/contacts.dart
@@ -1,10 +1,5 @@
library;
-/// Shared contacts package for native Flutter apps.
-///
-/// `ContactsSession.accountKey` means the logged-in user's existing top-level
-/// account key, not a contacts-specific key. The package uses it only to
-/// unwrap or create the per-user root contact key.
export 'src/db/contacts_database.dart';
export 'src/models/contact_data.dart';
export 'src/models/contact_record.dart';
diff --git a/mobile/packages/contacts/lib/src/models/contacts_session.dart b/mobile/packages/contacts/lib/src/models/contacts_session.dart
index b9b2b68ca2..374f8f447c 100644
--- a/mobile/packages/contacts/lib/src/models/contacts_session.dart
+++ b/mobile/packages/contacts/lib/src/models/contacts_session.dart
@@ -1,25 +1,16 @@
import 'dart:typed_data';
-/// Resolves the logged-in user's existing top-level account key on demand.
typedef AccountKeyProvider = Future<Uint8List> Function();
-/// Session input for opening contacts.
-///
-/// `accountKey` means the logged-in user's existing top-level account key.
-/// It is the same conceptual key that Photos currently exposes via
-/// `Configuration.instance.getKey()`. It is not a contacts-specific key.
-///
-/// The contacts package uses this key only to unwrap or create the per-user
-/// root contact key stored under `/user-entity/key?type=contact`.
+// accountKey is the existing top-level account key. Contacts uses it only to
+// unwrap or create the per-user contact root key.
class ContactsSession {
final String baseUrl;
final String authToken;
final int userId;
- /// The logged-in user's existing top-level account key.
final Uint8List? accountKey;
- /// Lazy resolver for the logged-in user's existing top-level account key.
final AccountKeyProvider? accountKeyProvider;
final String? userAgent;
final String? clientPackage;
diff --git a/mobile/packages/contacts/lib/src/service/contact_directory.dart b/mobile/packages/contacts/lib/src/service/contact_directory.dart
index 05c77441c5..8d41092609 100644
--- a/mobile/packages/contacts/lib/src/service/contact_directory.dart
+++ b/mobile/packages/contacts/lib/src/service/contact_directory.dart
@@ -9,7 +9,6 @@ import 'package:logging/logging.dart';
typedef ContactsServiceFactory = ContactsService Function();
-/// Account-scoped, observable contact cache over [ContactsService].
class ContactDirectory {
ContactDirectory({
ContactsService? contactsService,
@@ -88,8 +87,7 @@ class ContactDirectory {
void clearSession({bool notify = true}) => _clear(notify: notify);
- /// Positive account IDs are authoritative and never fall back to email;
- /// email lookup is only for identities without a known account ID.
+ // Positive account IDs are authoritative and never fall back to email.
ContactRecord? getCachedContact({int? contactUserId, String? email}) {
if (contactUserId != null && contactUserId > 0) {
return _contactsByUserId[contactUserId];
diff --git a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
index fd711ea570..12c531989c 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
@@ -5,7 +5,6 @@ import 'package:ente_contacts/src/service/contacts_service.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
-/// Read-oriented compatibility facade over the shared [ContactDirectory].
class ContactsDisplayService {
ContactsDisplayService._privateConstructor() : _store = ContactDirectory();
@@ -16,7 +15,7 @@ class ContactsDisplayService {
ValueListenable<int> get changes => _store.revision;
- /// Known accounts keep the same contact-scoped notifier across hydration.
+ // Known accounts keep the same notifier across cache hydration.
ValueListenable<int> changesFor({int? contactUserId, String? email}) {
final resolvedUserId = contactUserId != null && contactUserId > 0
? contactUserId
diff --git a/mobile/packages/ente_crypto_api/lib/src/crypto_api.dart b/mobile/packages/ente_crypto_api/lib/src/crypto_api.dart
index 5ae8a357f6..3af7ee31c6 100644
--- a/mobile/packages/ente_crypto_api/lib/src/crypto_api.dart
+++ b/mobile/packages/ente_crypto_api/lib/src/crypto_api.dart
@@ -83,7 +83,6 @@ abstract class CryptoApi {
int opsLimit,
);
- // Expose the Argon2 limits so higher layers can tune mem/ops values.
int get pwhashMemLimitInteractive;
int get pwhashMemLimitSensitive;
int get pwhashOpsLimitInteractive;
diff --git a/mobile/packages/ente_pure_utils/lib/src/data_util.dart b/mobile/packages/ente_pure_utils/lib/src/data_util.dart
index e8e81d72fa..efe97f73ac 100644
--- a/mobile/packages/ente_pure_utils/lib/src/data_util.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/data_util.dart
@@ -33,7 +33,6 @@ String formatBytes(int bytes, [int decimals = 2]) {
return '${(bytes / pow(k, i)).toStringAsFixed(dm)} ${storageUnits[i]}';
}
-//shows 1st decimal only if less than 10GB & omits decimal if decimal is 0
num roundBytesUsedToGBs(int usedBytes, int freeSpace) {
const tenGBinBytes = 10737418240;
num bytesInGB = convertBytesToGBs(usedBytes);
@@ -44,7 +43,6 @@ num roundBytesUsedToGBs(int usedBytes, int freeSpace) {
return bytesInGB;
}
-//Eg: 0.3 GB, 11.0 GB, 532.3 GB
num convertBytesToGBs(int bytes) {
return num.parse((bytes / (pow(1024, 3))).toStringAsFixed(1));
}
@@ -57,7 +55,6 @@ int convertBytesToMBs(int bytes) {
return (bytes / pow(1024, 2)).round();
}
-//Eg: 1TB, 1.3TB, 4.9TB, 3TB
num roundGBsToTBs(num sizeInGBs) {
final num sizeInTBs = num.parse((sizeInGBs / 1000).toStringAsFixed(1));
if (sizeInTBs % 1 == 0) {
@@ -67,13 +64,7 @@ num roundGBsToTBs(num sizeInGBs) {
}
}
-/// Computes the MD5 hash of a file or a portion of it.
-///
-/// [filePath] - Path to the file
-/// [start] - Optional starting byte position for partial hash computation
-/// [end] - Optional ending byte position for partial hash computation
-///
-/// Returns base64-encoded MD5 hash suitable for HTTP Content-MD5 header.
+// Returns base64 for the HTTP Content-MD5 header.
Future<String> computeMd5(String filePath, {int? start, int? end}) async {
final file = File(filePath);
final output = AccumulatorSink<Digest>();
diff --git a/mobile/packages/ente_pure_utils/lib/src/date_time_util.dart b/mobile/packages/ente_pure_utils/lib/src/date_time_util.dart
index 3e46903a6c..cf352a60a5 100644
--- a/mobile/packages/ente_pure_utils/lib/src/date_time_util.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/date_time_util.dart
@@ -60,17 +60,14 @@ Map<int, String> _days = {
final currentYear = int.parse(DateTime.now().year.toString());
const searchStartYear = 1970;
-//Jun 2022
String getMonthAndYear(DateTime dateTime) {
return "${_months[dateTime.month]!} ${dateTime.year}";
}
-//Thu, 30 Jun
String getDayAndMonth(DateTime dateTime) {
return "${_days[dateTime.weekday]!}, ${dateTime.day} ${_months[dateTime.month]!}";
}
-//30 Jun, 2022
String getDateAndMonthAndYear(DateTime dateTime) {
return "${dateTime.day} ${_months[dateTime.month]!}, ${dateTime.year}";
}
@@ -91,7 +88,6 @@ String getAbbreviationOfYear(DateTime dateTime) {
return (dateTime.year % 100).toString();
}
-//14:32
String getTime(DateTime dateTime) {
final hours = dateTime.hour > 9
? dateTime.hour.toString()
@@ -102,29 +98,24 @@ String getTime(DateTime dateTime) {
return "$hours:$minutes";
}
-//11:22 AM
String getTimeIn12hrFormat(DateTime dateTime) {
return DateFormat.jm().format(dateTime);
}
-//Thu, Jun 30, 2022 - 14:32
String getFormattedTime(
DateTime dateTime, {
BuildContext? context,
bool withYear = false,
}) {
if (context != null) {
- // Use locale-aware formatting when context is provided
return DateFormat(
'E, MMM d, y - HH:mm',
Localizations.localeOf(context).languageCode,
).format(dateTime);
}
- // Default formatting
return "${getDay(dateTime)}, ${getMonth(dateTime)} ${dateTime.day}, ${dateTime.year} - ${getTime(dateTime)}";
}
-//30 Jun'22
String getFormattedDate(DateTime dateTime) {
return "${dateTime.day} ${getMonth(dateTime)}'${getAbbreviationOfYear(dateTime)}";
}
@@ -263,8 +254,6 @@ Widget getDayWidget(
);
}
-// Added from photos standalone utils
-
bool areFromSameDay(int firstCreationTime, int secondCreationTime) {
final firstDate = DateTime.fromMicrosecondsSinceEpoch(firstCreationTime);
final secondDate = DateTime.fromMicrosecondsSinceEpoch(secondCreationTime);
@@ -281,12 +270,10 @@ bool areDatesInSameWeek(DateTime date1, DateTime date2) {
}
final int dayOfWeek1 = date1.weekday;
final int dayOfWeek2 = date2.weekday;
- // Calculate the start and end dates of the week for both dates
final DateTime startOfWeek1 = date1.subtract(Duration(days: dayOfWeek1 - 1));
final DateTime endOfWeek1 = startOfWeek1.add(const Duration(days: 6));
final DateTime startOfWeek2 = date2.subtract(Duration(days: dayOfWeek2 - 1));
final DateTime endOfWeek2 = startOfWeek2.add(const Duration(days: 6));
- // Check if the two dates fall within the same week range
if ((date1.isAfter(startOfWeek2) && date1.isBefore(endOfWeek2)) ||
(date2.isAfter(startOfWeek1) && date2.isBefore(endOfWeek1))) {
return true;
@@ -294,33 +281,24 @@ bool areDatesInSameWeek(DateTime date1, DateTime date2) {
return false;
}
-// Create link default names:
-// Same day: "Dec 19, 2022"
-// Same month: "Dec 19 - 22, 2022"
-// Base case: "Dec 19, 2022 - Jan 7, 2023"
String getNameForDateRange(int firstCreationTime, int secondCreationTime) {
final startTime = DateTime.fromMicrosecondsSinceEpoch(firstCreationTime);
final endTime = DateTime.fromMicrosecondsSinceEpoch(secondCreationTime);
- // different year
if (startTime.year != endTime.year) {
return "${_shortMonths[startTime.month]!} ${startTime.day}, ${startTime.year} - "
"${_shortMonths[endTime.month]!} ${endTime.day}, ${endTime.year}";
}
- // same year, diff month
if (startTime.month != endTime.month) {
return "${_shortMonths[startTime.month]!} ${startTime.day} - "
"${_shortMonths[endTime.month]!} ${endTime.day}, ${endTime.year}";
}
- // same month and year, diff day
if (startTime.day != endTime.day) {
return "${_shortMonths[startTime.month]!} ${startTime.day} - "
"${_shortMonths[endTime.month]!} ${endTime.day}, ${endTime.year}";
}
- // same day
return "${_shortMonths[endTime.month]!} ${endTime.day}, ${endTime.year}";
}
-/// Returns the duration in seconds from the format "h:mm:ss" or "m:ss".
int? durationToSeconds(String? duration) {
if (duration == null) {
return null;
@@ -329,14 +307,12 @@ int? durationToSeconds(String? duration) {
int seconds = 0;
if (parts.length == 3) {
- // Format: "h:mm:ss"
- seconds += int.parse(parts[0]) * 3600; // Hours to seconds
- seconds += int.parse(parts[1]) * 60; // Minutes to seconds
- seconds += int.parse(parts[2]); // Seconds
+ seconds += int.parse(parts[0]) * 3600;
+ seconds += int.parse(parts[1]) * 60;
+ seconds += int.parse(parts[2]);
} else if (parts.length == 2) {
- // Format: "m:ss"
- seconds += int.parse(parts[0]) * 60; // Minutes to seconds
- seconds += int.parse(parts[1]); // Seconds
+ seconds += int.parse(parts[0]) * 60;
+ seconds += int.parse(parts[1]);
} else {
throw FormatException('Invalid duration format: $duration');
}
@@ -344,7 +320,6 @@ int? durationToSeconds(String? duration) {
return seconds;
}
-/// Returns the duration in the format "h:mm:ss" or "m:ss".
String secondsToDuration(int totalSeconds) {
final hours = totalSeconds ~/ 3600;
final minutes = (totalSeconds % 3600) ~/ 60;
@@ -383,13 +358,11 @@ final RegExp _filenameExp = RegExp('[\\.A-Za-z]*');
DateTime? parseDateTimeFromFileNameV2(
String fileName, {
- /* to avoid parsing incorrect date time from the filename, the max and min
- year limits the chances of parsing incorrect date times
- */
+ // Year bounds reduce false dates parsed from filenames.
int minYear = 1990,
int? maxYear,
}) {
- // add next year to avoid corner cases for 31st Dec
+ // Include next year for 31 December edge cases.
maxYear ??= currentYear + 1;
String val = fileName.replaceAll(_filenameExp, '');
if (val.isNotEmpty && !_isNumeric(val[0])) {
diff --git a/mobile/packages/ente_pure_utils/lib/src/debouncer.dart b/mobile/packages/ente_pure_utils/lib/src/debouncer.dart
index a6c6667454..2802db28e1 100644
--- a/mobile/packages/ente_pure_utils/lib/src/debouncer.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/debouncer.dart
@@ -2,16 +2,12 @@ import 'dart:async';
import 'package:flutter/material.dart';
-///Do not forget to cancel the debounce's timer using [cancelDebounce]
-///when the debouncer is no longer needed
+// Call cancelDebounce when the debouncer is no longer needed.
class Debouncer {
final Duration _duration;
final ValueNotifier<bool> _debounceActiveNotifier = ValueNotifier(false);
- /// If executionInterval is not null, then the debouncer will execute the
- /// current callback it has in run() method repeatedly in the given interval.
- /// This is useful for example when you want to execute a callback every 5 seconds
final Duration? executionInterval;
Timer? _debounceTimer;
final bool leading;
@@ -34,7 +30,6 @@ class Debouncer {
bool shouldRunImmediately = false;
if (executionInterval != null) {
- // ensure the stop watch is running
_stopwatch.start();
if (_stopwatch.elapsedMilliseconds > executionInterval!.inMilliseconds) {
shouldRunImmediately = true;
@@ -64,7 +59,6 @@ class Debouncer {
}
}
- // Backward compatibility alias
void cancelDebounceTimer() => cancelDebounce();
bool isActive() => _debounceTimer != null && _debounceTimer!.isActive;
diff --git a/mobile/packages/ente_pure_utils/lib/src/extensions/list.dart b/mobile/packages/ente_pure_utils/lib/src/extensions/list.dart
index e25d587c2a..c98c8a935b 100644
--- a/mobile/packages/ente_pure_utils/lib/src/extensions/list.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/extensions/list.dart
@@ -7,9 +7,6 @@ extension ListExtension<E> on List<E> {
return result;
}
- // splitMatch, based on the matchFunction, split the input list in two
- // lists. result.matched contains items which matched and result.unmatched
- // contains remaining items.
ListMatch<E> splitMatch(bool Function(E e) matchFunction) {
final listMatch = ListMatch<E>();
for (final element in this) {
diff --git a/mobile/packages/ente_pure_utils/lib/src/navigation_util.dart b/mobile/packages/ente_pure_utils/lib/src/navigation_util.dart
index 6ae914e796..501be0472a 100644
--- a/mobile/packages/ente_pure_utils/lib/src/navigation_util.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/navigation_util.dart
@@ -52,9 +52,9 @@ PageRouteBuilder<T> _buildPageRoute<T extends Object>(Widget page) {
class SwipeableRouteBuilder<T> extends PageRoute<T> {
final RoutePageBuilder pageBuilder;
+ // Cupertino preserves the iOS back-swipe gesture.
final PageTransitionsBuilder matchingBuilder =
- const CupertinoPageTransitionsBuilder(); // Default iOS/macOS (to get the swipe right to go back gesture)
- // final PageTransitionsBuilder matchingBuilder = const FadeUpwardsPageTransitionsBuilder(); // Default Android/Linux/Windows
+ const CupertinoPageTransitionsBuilder();
SwipeableRouteBuilder({required this.pageBuilder});
@@ -77,7 +77,7 @@ class SwipeableRouteBuilder<T> extends PageRoute<T> {
bool get maintainState => true;
@override
- Duration get transitionDuration => const Duration(milliseconds: 300); // Can give custom Duration, unlike in MaterialPageRoute
+ Duration get transitionDuration => const Duration(milliseconds: 300);
@override
Widget buildTransitions(
diff --git a/mobile/packages/ente_pure_utils/lib/src/simple_task_queue.dart b/mobile/packages/ente_pure_utils/lib/src/simple_task_queue.dart
index 1f11c2da2a..d23610d7df 100644
--- a/mobile/packages/ente_pure_utils/lib/src/simple_task_queue.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/simple_task_queue.dart
@@ -1,11 +1,6 @@
import "dart:async";
import "dart:collection";
-// SimpleTaskQueue is a simple task queue that allows you to add tasks
-// and run them concurrently up to a specified limit. It doesn't support
-// task cancellation or timeout, but it can be used for simple
-// asynchronous task management.
-// See [TaskQueue] for a more advanced implementation with
class SimpleTaskQueue {
final int maxConcurrent;
final Queue<Future<void> Function()> _queue = Queue();
diff --git a/mobile/packages/ente_pure_utils/lib/src/stop_watch.dart b/mobile/packages/ente_pure_utils/lib/src/stop_watch.dart
index 7d82d51438..422b49daac 100644
--- a/mobile/packages/ente_pure_utils/lib/src/stop_watch.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/stop_watch.dart
@@ -37,12 +37,6 @@ class EnteWatch extends Stopwatch {
}
}
-// TimerLogger helps in quickly including the timeTaken for various operation.
-// The timeTaken is logged only if it exceeds the logThreshold. With each call to toString, the timer is reset.
-// Usage:
-// final TimeLogger tlog = TimeLogger(context: "PhotoProcessingService");
-// _logger.info("some operation $tlog");
-// _logger.info("another operation $tlog");
class TimeLogger {
final String context;
final int logThreshold;
diff --git a/mobile/packages/ente_pure_utils/lib/src/task_queue.dart b/mobile/packages/ente_pure_utils/lib/src/task_queue.dart
index af911c1b88..1c15485552 100644
--- a/mobile/packages/ente_pure_utils/lib/src/task_queue.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/task_queue.dart
@@ -3,7 +3,6 @@ import "dart:developer";
import 'package:collection/collection.dart';
-/// Class to hold task information
class _QueueItem<T> {
final T id;
final Future<void> Function() task;
@@ -29,7 +28,6 @@ class _QueueItem<T> {
Future<void> get future => completer.future;
}
-/// Custom exception for task timeout
class TaskQueueTimeoutException implements Exception {
final dynamic taskId;
final Duration timeout;
@@ -41,7 +39,6 @@ class TaskQueueTimeoutException implements Exception {
'Task $taskId timed out after ${timeout.inSeconds} seconds';
}
-/// Custom exception for task being discarded due to queue overflow
class TaskQueueOverflowException implements Exception {
final dynamic taskId;
@@ -60,27 +57,19 @@ class TaskQueueCancelledException implements Exception {
String toString() => 'Task $taskId was cancelled';
}
-/// A generic task queue that can manage tasks with priority, cancellation, and timeout functionality.
class TaskQueue<T> {
- /// Maximum number of tasks that can run concurrently
final int maxConcurrentTasks;
- /// Timeout duration after which a task is considered stale
final Duration taskTimeout;
- /// Maximum size of the queue before older tasks are discarded
final int maxQueueSize;
- /// Map to store tasks for quick lookup by ID
final _taskMap = <T, _QueueItem>{};
- /// Priority queue to sort tasks by timestamp (most recent first)
final HeapPriorityQueue<_QueueItem> _priorityQueue;
- /// Set of currently running task ids
final _runningTasks = <T>{};
- /// Constructor
TaskQueue({
this.maxConcurrentTasks = 1,
this.taskTimeout = const Duration(minutes: 5),
@@ -89,63 +78,48 @@ class TaskQueue<T> {
(a, b) => b.lastUpdated.compareTo(a.lastUpdated),
); // Reversed for most recent first
- /// Add or update a task in the queue
Future<void> addTask(T id, Future<void> Function() task) {
- // If the task is already in the queue, update its timestamp to increase priority
if (_taskMap.containsKey(id)) {
final item = _taskMap[id]!;
- // We need to remove and re-add to the priority queue to update its position
_priorityQueue.remove(item);
item.updateTimestamp();
_priorityQueue.add(item);
return item.future;
} else {
- // Check if we need to make room in the queue
_enforceQueueSizeLimit();
- // Add new task to the queue
final queueItem = _QueueItem(id, task);
_taskMap[id] = queueItem;
_priorityQueue.add(queueItem);
- // Try to process tasks
_processQueue();
return queueItem.future;
}
}
- /// Enforce the maximum queue size by discarding older tasks
void _enforceQueueSizeLimit() {
- // If we're under the limit, no action needed
if (_taskMap.length < maxQueueSize) {
return;
}
- // Create a temporary queue to find oldest items
- // We need this because our main queue is ordered by most recent first
final tempQueue = PriorityQueue<_QueueItem>(
(a, b) => a.lastUpdated.compareTo(b.lastUpdated),
- ); // Oldest first
+ );
- // Add all items to the temporary queue
for (var item in _taskMap.values) {
tempQueue.add(item);
}
- // Calculate how many items we need to remove
- final excessItems =
- _taskMap.length - maxQueueSize + 1; // +1 to make room for the new item
+ final excessItems = _taskMap.length - maxQueueSize + 1;
- // Remove the oldest items
for (var i = 0; i < excessItems && tempQueue.isNotEmpty; i++) {
final oldestItem = tempQueue.removeFirst();
_priorityQueue.remove(oldestItem);
_taskMap.remove(oldestItem.id);
- // Complete with overflow error
if (!oldestItem.completer.isCompleted) {
oldestItem.completer.completeError(
TaskQueueOverflowException(oldestItem.id),
@@ -154,9 +128,7 @@ class TaskQueue<T> {
}
}
- /// Remove a task from the queue by its ID
bool removeTask(T id) {
- // Can only remove tasks that aren't already running
if (_runningTasks.contains(id)) {
return false;
}
@@ -168,7 +140,6 @@ class TaskQueue<T> {
return false;
}
_priorityQueue.remove(item);
- // Complete the future with a cancellation error
if (!item.completer.isCompleted) {
item.completer.completeError(TaskQueueCancelledException(id));
}
@@ -180,70 +151,53 @@ class TaskQueue<T> {
return false;
}
- /// Get the number of tasks waiting in the queue
int get pendingTasksCount => _taskMap.length;
- /// Get the number of currently running tasks
int get runningTasksCount => _runningTasks.length;
- /// Process the queue and execute tasks if possible
void _processQueue() async {
- // Remove timed out tasks
_removeTimedOutTasks();
- // If we can't run more tasks, exit
if (_runningTasks.length >= maxConcurrentTasks || _priorityQueue.isEmpty) {
return;
}
- // Get the highest priority task (most recent)
final queueItem = _priorityQueue.removeFirst();
final taskId = queueItem.id;
- // Remove from the map
_taskMap.remove(taskId);
- // Mark this task as running
_runningTasks.add(taskId);
try {
- // Execute the task
await queueItem.task();
- // Complete the future successfully
if (!queueItem.completer.isCompleted) {
queueItem.completer.complete();
}
} catch (e) {
- // Complete the future with the error
if (!queueItem.completer.isCompleted) {
queueItem.completer.completeError(e);
}
log('Task error: $e');
} finally {
- // Mark the task as completed
_runningTasks.remove(taskId);
- // Process the next task in the queue
_processQueue();
}
}
- /// Remove tasks that have timed out
void _removeTimedOutTasks() {
final timedOutIds = <T>[];
- // First pass: identify timed out items
for (var entry in _taskMap.entries) {
if (entry.value.isTimedOut(taskTimeout)) {
timedOutIds.add(entry.key);
}
}
- // Second pass: remove them and complete with timeout error
for (var id in timedOutIds) {
final item = _taskMap[id]!;
_priorityQueue.remove(item);
- // Complete the future with a timeout error
if (!item.completer.isCompleted) {
item.completer.completeError(
TaskQueueTimeoutException(id, taskTimeout),
@@ -254,9 +208,7 @@ class TaskQueue<T> {
}
}
- /// Clear all pending tasks
void clear() {
- // Complete all pending tasks with cancellation errors
for (var entry in _taskMap.entries) {
if (!entry.value.completer.isCompleted) {
entry.value.completer.completeError(
diff --git a/mobile/packages/ente_qr/lib/ente_qr.dart b/mobile/packages/ente_qr/lib/ente_qr.dart
index 3538e43cff..9ab5be4e6d 100644
--- a/mobile/packages/ente_qr/lib/ente_qr.dart
+++ b/mobile/packages/ente_qr/lib/ente_qr.dart
@@ -25,12 +25,6 @@ class EnteQr {
return EnteQrPlatform.instance.getPlatformVersion();
}
- /// Scans a QR code from an image file at the given path.
- ///
- /// [imagePath] - The file path to the image containing the QR code
- ///
- /// Returns a [QrScanResult] containing either the QR code content on success
- /// or an error message on failure.
Future<QrScanResult> scanQrFromImage(
String imagePath, {
bool tryOriginalResolution = false,
@@ -56,10 +50,6 @@ class EnteQr {
return fallbackResult.success ? fallbackResult : result;
}
- /// Scans all QR codes from an image file at the given path.
- ///
- /// Returns a [QrScanResults] containing a list of [QrDetection] with
- /// content and normalized bounding boxes for each detected QR code.
Future<QrScanResults> scanAllQrFromImage(String imagePath) {
return _scanPlatform.scanAllQrFromImage(imagePath);
}
diff --git a/mobile/packages/ente_qr/lib/ente_qr_method_channel.dart b/mobile/packages/ente_qr/lib/ente_qr_method_channel.dart
index cb81787d97..172d100c7f 100644
--- a/mobile/packages/ente_qr/lib/ente_qr_method_channel.dart
+++ b/mobile/packages/ente_qr/lib/ente_qr_method_channel.dart
@@ -2,9 +2,7 @@ import 'package:ente_qr/ente_qr_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
-/// An implementation of [EnteQrPlatform] that uses method channels.
class MethodChannelEnteQr extends EnteQrPlatform {
- /// The method channel used to interact with the native platform.
@visibleForTesting
final methodChannel = const MethodChannel('ente_qr');
@@ -34,7 +32,6 @@ class MethodChannelEnteQr extends EnteQrPlatform {
return QrScanResult.error('Failed to scan QR code');
}
- // Convert to Map<String, dynamic> safely
final Map<String, dynamic> resultMap = Map<String, dynamic>.from(
result as Map,
);
diff --git a/mobile/packages/ente_qr/lib/ente_qr_platform_interface.dart b/mobile/packages/ente_qr/lib/ente_qr_platform_interface.dart
index 1c1f14f354..0f54419ef7 100644
--- a/mobile/packages/ente_qr/lib/ente_qr_platform_interface.dart
+++ b/mobile/packages/ente_qr/lib/ente_qr_platform_interface.dart
@@ -1,7 +1,6 @@
import 'package:ente_qr/ente_qr_method_channel.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
-/// The result of QR code scanning
class QrScanResult {
final String? content;
final String? error;
@@ -18,21 +17,16 @@ class QrScanResult {
}
}
-/// A single detected QR code with its content and normalized bounding box.
+// Bounding boxes use normalized 0..1 coordinates.
class QrDetection {
- /// The decoded QR code content.
final String content;
- /// Normalized x coordinate of the bounding box (0.0 to 1.0).
final double x;
- /// Normalized y coordinate of the bounding box (0.0 to 1.0).
final double y;
- /// Normalized width of the bounding box (0.0 to 1.0).
final double width;
- /// Normalized height of the bounding box (0.0 to 1.0).
final double height;
const QrDetection({
@@ -54,7 +48,6 @@ class QrDetection {
}
}
-/// The result of scanning for multiple QR codes.
class QrScanResults {
final List<QrDetection> detections;
final String? error;
@@ -76,21 +69,14 @@ class QrScanResults {
}
abstract class EnteQrPlatform extends PlatformInterface {
- /// Constructs a EnteQrPlatform.
EnteQrPlatform() : super(token: _token);
static final Object _token = Object();
static EnteQrPlatform _instance = MethodChannelEnteQr();
- /// The default instance of [EnteQrPlatform] to use.
- ///
- /// Defaults to [MethodChannelEnteQr].
static EnteQrPlatform get instance => _instance;
- /// Platform-specific implementations should set this with their own
- /// platform-specific class that extends [EnteQrPlatform] when
- /// they register themselves.
static set instance(EnteQrPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
@@ -100,8 +86,6 @@ abstract class EnteQrPlatform extends PlatformInterface {
throw UnimplementedError('platformVersion() has not been implemented.');
}
- /// Scans a QR code from an image file at the given path.
- /// Returns the QR code content as a string if successful, null otherwise.
Future<QrScanResult> scanQrFromImage(
String imagePath, {
bool tryOriginalResolution = false,
@@ -109,8 +93,6 @@ abstract class EnteQrPlatform extends PlatformInterface {
throw UnimplementedError('scanQrFromImage() has not been implemented.');
}
- /// Scans all QR codes from an image file at the given path.
- /// Returns a list of detections with content and bounding boxes.
Future<QrScanResults> scanAllQrFromImage(String imagePath) {
throw UnimplementedError('scanAllQrFromImage() has not been implemented.');
}
diff --git a/mobile/packages/legacy/lib/events/legacy_kit_created_event.dart b/mobile/packages/legacy/lib/events/legacy_kit_created_event.dart
index d0fe96cff8..81967c80e4 100644
--- a/mobile/packages/legacy/lib/events/legacy_kit_created_event.dart
+++ b/mobile/packages/legacy/lib/events/legacy_kit_created_event.dart
@@ -1,4 +1,3 @@
import "package:ente_events/models/event.dart";
-/// Fired after a Legacy Kit is successfully created.
class LegacyKitCreatedEvent extends Event {}
diff --git a/mobile/packages/legacy/lib/models/emergency_models.dart b/mobile/packages/legacy/lib/models/emergency_models.dart
index 5ee1e31435..4170a0ef4a 100644
--- a/mobile/packages/legacy/lib/models/emergency_models.dart
+++ b/mobile/packages/legacy/lib/models/emergency_models.dart
@@ -58,7 +58,6 @@ class EmergencyContact {
this.recoveryNoticeInDays,
);
- // copyWith
EmergencyContact copyWith({
User? user,
User? emergencyContact,
@@ -73,7 +72,6 @@ class EmergencyContact {
);
}
- // fromJson
EmergencyContact.fromJson(Map<String, dynamic> json)
: user = User.fromMap(json['user']),
emergencyContact = User.fromMap(json['emergencyContact']),
@@ -90,16 +88,12 @@ class EmergencyContact {
}
class EmergencyInfo {
- // List of emergency contacts added by the user
final List<EmergencyContact> contacts;
- // List of recovery sessions that are created to recover current user account
final List<RecoverySessions> recoverSessions;
- // List of emergency contacts that have added current user as their emergency contact
final List<EmergencyContact> othersEmergencyContact;
- // List of recovery sessions that are created to recover grantor's account
final List<RecoverySessions> othersRecoverySession;
EmergencyInfo(
@@ -109,7 +103,6 @@ class EmergencyInfo {
this.othersRecoverySession,
);
- // from json
EmergencyInfo.fromJson(Map<String, dynamic> json)
: contacts = (json['contacts'] as List)
.map((contact) => EmergencyContact.fromJson(contact))
@@ -142,7 +135,6 @@ class RecoverySessions {
this.createdAt,
);
- // fromJson
RecoverySessions.fromJson(Map<String, dynamic> json)
: id = json['id'],
user = User.fromMap(json['user']),
diff --git a/mobile/packages/legacy/lib/pages/other_contact_page.dart b/mobile/packages/legacy/lib/pages/other_contact_page.dart
index b1843d9d4c..a4f2a154a9 100644
--- a/mobile/packages/legacy/lib/pages/other_contact_page.dart
+++ b/mobile/packages/legacy/lib/pages/other_contact_page.dart
@@ -17,9 +17,6 @@ import "package:flutter/material.dart";
import "package:intl/intl.dart";
import "package:logging/logging.dart";
-// OtherContactPage is used to start recovery process for other user's account
-// Based on the state of the contact & recovery session, it will show
-// different UI
class OtherContactPage extends StatefulWidget {
final EmergencyContact contact;
final EmergencyInfo emergencyInfo;
@@ -104,7 +101,6 @@ class _OtherContactPageState extends State<OtherContactPage> {
),
Text(accountEmail, style: textTheme.smallMuted),
const SizedBox(height: 12),
- // Description text based on recovery state
if (recoverySession == null)
Text(
context.strings.recoverAccountDesc(
@@ -127,7 +123,6 @@ class _OtherContactPageState extends State<OtherContactPage> {
style: textTheme.smallMuted,
),
const SizedBox(height: 24),
- // Start recovery button (no active session)
if (recoverySession == null)
GradientButton(
text: context.strings.startRecovery,
diff --git a/mobile/packages/legacy/lib/pages/recover_others_account.dart b/mobile/packages/legacy/lib/pages/recover_others_account.dart
index 7e94ce86ea..d154c8ac7b 100644
--- a/mobile/packages/legacy/lib/pages/recover_others_account.dart
+++ b/mobile/packages/legacy/lib/pages/recover_others_account.dart
@@ -146,8 +146,7 @@ class _RecoverOthersAccountState extends State<RecoverOthersAccount> {
),
const Padding(padding: EdgeInsets.all(12)),
Visibility(
- // hidden textForm for suggesting auto-fill service for saving
- // password
+ // Prompts platform password saving.
visible: false,
child: TextFormField(
autofillHints: const [AutofillHints.email],
@@ -296,7 +295,6 @@ class _RecoverOthersAccountState extends State<RecoverOthersAccount> {
final KeyAttributes attributes = widget.attributes;
Uint8List? masterKey;
try {
- // Decrypt the master key that was earlier encrypted with the recovery key
masterKey = await CryptoUtil.decrypt(
CryptoUtil.base642bin(attributes.masterKeyEncryptedWithRecoveryKey),
CryptoUtil.hex2bin(widget.recoveryKey),
@@ -307,15 +305,12 @@ class _RecoverOthersAccountState extends State<RecoverOthersAccount> {
rethrow;
}
- // Derive a key from the password that will be used to encrypt and
- // decrypt the master key
final kekSalt = CryptoUtil.getSaltToDeriveKey();
final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
utf8.encode(password),
kekSalt,
);
final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
- // Encrypt the key with this derived key
final encryptedKeyData = CryptoUtil.encryptSync(
masterKey,
derivedKeyResult.key,
diff --git a/mobile/packages/legacy/lib/pages/select_contact_page.dart b/mobile/packages/legacy/lib/pages/select_contact_page.dart
index 64a215f5a1..23d238154f 100644
--- a/mobile/packages/legacy/lib/pages/select_contact_page.dart
+++ b/mobile/packages/legacy/lib/pages/select_contact_page.dart
@@ -22,7 +22,6 @@ import "package:ente_ui/theme/text_style.dart";
import "package:flutter/material.dart";
import "package:logging/logging.dart";
-/// Shows the add contact bottom sheet and returns true if a contact was added
Future<bool?> showAddContactSheet(
BuildContext context, {
required EmergencyInfo emergencyInfo,
@@ -409,7 +408,6 @@ class _AddContactSheetState extends State<AddContactSheet> {
}
}
- // People who added you as their emergency contact
for (final contact in widget.emergencyInfo.othersEmergencyContact) {
add(contact.user.email, userID: contact.user.id);
}
@@ -420,7 +418,6 @@ class _AddContactSheetState extends State<AddContactSheet> {
add(member.email, userID: member.userID);
}
- // Filter by search text
if (_textController.text.trim().isNotEmpty) {
suggestedUsers.removeWhere(
(element) => !element.matchesResolvedNameOrEmail(_textController.text),
diff --git a/mobile/packages/lock_screen/lib/local_authentication_service.dart b/mobile/packages/lock_screen/lib/local_authentication_service.dart
index 3481861fc8..4eca173b52 100644
--- a/mobile/packages/lock_screen/lib/local_authentication_service.dart
+++ b/mobile/packages/lock_screen/lib/local_authentication_service.dart
@@ -33,7 +33,6 @@ class LocalAuthenticationService {
}) async {
final unlockReason = context.strings.unlock;
if (kDebugMode && useDebugAuthCache) {
- // if last auth time is less than 60 seconds, don't ask for auth again
if (lastAuthTime != 0 &&
DateTime.now().millisecondsSinceEpoch - lastAuthTime < 60000) {
return true;
diff --git a/mobile/packages/lock_screen/lib/lock_screen_settings.dart b/mobile/packages/lock_screen/lib/lock_screen_settings.dart
index adb533c150..b7d076d0fa 100644
--- a/mobile/packages/lock_screen/lib/lock_screen_settings.dart
+++ b/mobile/packages/lock_screen/lib/lock_screen_settings.dart
@@ -64,11 +64,9 @@ class LockScreenSettings {
_secureStorage = const FlutterSecureStorage();
_preferences = await SharedPreferences.getInstance();
- ///Workaround for privacyScreen not working when app is killed and opened.
+ // Workaround for privacyScreen not working when app is killed and opened.
await setHideAppContent(getShouldHideAppContent());
- /// Function to Check if the migration for lock screen changes has
- /// already been done by checking a stored boolean value.
await runLockScreenChangesMigration();
await _clearLsDataInKeychainIfFreshInstall(hasOptedForOfflineMode);
@@ -217,7 +215,6 @@ class LockScreenSettings {
double? get appLogoHeight => _appLogoHeight;
- /// Verifies that the hash of [text] matches [storedHash].
Future<bool> verify({
required String text,
required String? storedHash,
@@ -236,12 +233,8 @@ class LockScreenSettings {
return hash == storedHash;
}
- /// Like [verify], but for secrets created by photos' lock screen.
- ///
- /// On a miss it retries with photos' legacy (Interactive ops) parameters and,
- /// on a hit, upgrades the stored hash to the current parameters under
- /// [storageKey]. The re-store is best-effort, so a correct secret is never
- /// rejected.
+ // Photos may still have hashes made with legacy Interactive ops.
+ // Upgrade them best-effort; a storage failure must not reject the secret.
Future<bool> verifyWithLegacyFallback({
required String text,
required String? storedHash,
diff --git a/mobile/packages/lock_screen/lib/ui/app_lock.dart b/mobile/packages/lock_screen/lib/ui/app_lock.dart
index c7306945fd..1d6eb0c189 100644
--- a/mobile/packages/lock_screen/lib/ui/app_lock.dart
+++ b/mobile/packages/lock_screen/lib/ui/app_lock.dart
@@ -6,27 +6,6 @@ import 'package:flutter/material.dart';
@visibleForTesting
const appLockContentObscurerKey = ValueKey('app_lock_content_obscurer');
-/// A widget which handles app lifecycle events for showing and hiding a lock screen.
-/// This should wrap around a `MyApp` widget (or equivalent).
-///
-/// [lockScreen] is a [Widget] which should be a screen for handling login logic and
-/// calling `AppLock.of(context).didUnlock();` upon a successful login.
-///
-/// [builder] is a [Function] taking an [Object] as its argument and should return a
-/// [Widget]. The [Object] argument is provided by the [lockScreen] calling
-/// `AppLock.of(context).didUnlock();` with an argument. [Object] can then be injected
-/// in to your `MyApp` widget (or equivalent).
-///
-/// [enabled] determines wether or not the [lockScreen] should be shown on app launch
-/// and subsequent app pauses. This can be changed later on using `AppLock.of(context).enable();`,
-/// `AppLock.of(context).disable();` or the convenience method `AppLock.of(context).setEnabled(enabled);`
-/// using a bool argument.
-///
-/// [backgroundLockLatency] determines how much time is allowed to pass when
-/// the app is in the background state before the [lockScreen] widget should be
-/// shown upon returning. It defaults to instantly.
-///
-
// ignore_for_file: unnecessary_this, library_private_types_in_public_api
class AppLock extends StatefulWidget {
final Widget Function(Object?) builder;
@@ -42,7 +21,6 @@ class AppLock extends StatefulWidget {
final LocaleListResolutionCallback? localeListResolutionCallback;
final bool debugShowCheckedModeBanner;
- /// Invoked on each successful unlock (launch, resume, or manual).
final VoidCallback? onUnlock;
const AppLock({
@@ -206,14 +184,6 @@ class _AppLockState extends State<AppLock> with WidgetsBindingObserver {
);
}
- /// Causes `AppLock` to either pop the [lockScreen] if the app is already running
- /// or instantiates widget returned from the [builder] method if the app is cold
- /// launched.
- ///
- /// [args] is an optional argument which will get passed to the [builder] method
- /// when built. Use this when you want to inject objects created from the
- /// [lockScreen] in to the rest of your app so you can better guarantee that some
- /// objects, services or databases are already instantiated before using them.
void didUnlock([Object? args]) {
this.widget.onUnlock?.call();
if (this._didUnlockForAppLaunch) {
@@ -223,12 +193,6 @@ class _AppLockState extends State<AppLock> with WidgetsBindingObserver {
}
}
- /// Makes sure that [AppLock] shows the [lockScreen] on subsequent app pauses if
- /// [enabled] is true of makes sure it isn't shown on subsequent app pauses if
- /// [enabled] is false.
- ///
- /// This is a convenience method for calling the [enable] or [disable] method based
- /// on [enabled].
void setEnabled(bool enabled) {
if (enabled) {
this.enable();
@@ -246,21 +210,18 @@ class _AppLockState extends State<AppLock> with WidgetsBindingObserver {
});
}
- /// Makes sure that [AppLock] shows the [lockScreen] on subsequent app pauses.
void enable() {
setState(() {
this._enabled = true;
});
}
- /// Makes sure that [AppLock] doesn't show the [lockScreen] on subsequent app pauses.
void disable() {
setState(() {
this._enabled = false;
});
}
- /// Show the [lockScreen] for automatic locking (app launch, background resume).
Future<void> showLockScreen() {
this._setLocked(true);
return _navigatorKey.currentState!.pushNamed(
@@ -269,7 +230,7 @@ class _AppLockState extends State<AppLock> with WidgetsBindingObserver {
);
}
- /// Show the [lockScreen] for user-initiated manual lock (no auto-auth on first frame).
+ // Manual lock must not auto-authenticate on its first frame.
Future<void> showManualLockScreen() {
this._setLocked(true);
return _navigatorKey.currentState!.pushNamed(
diff --git a/mobile/packages/lock_screen/lib/ui/lock_screen.dart b/mobile/packages/lock_screen/lib/ui/lock_screen.dart
index 1d9e64d3e8..a88efa8144 100644
--- a/mobile/packages/lock_screen/lib/ui/lock_screen.dart
+++ b/mobile/packages/lock_screen/lib/ui/lock_screen.dart
@@ -45,9 +45,8 @@ class _LockScreenState extends State<LockScreen> with WidgetsBindingObserver {
int invalidAttemptCount = 0;
int remainingTimeInSeconds = 0;
final _lockscreenSetting = LockScreenSettings.instance;
- // Suppress auto-auth only for the initial manual presentation.
bool _suppressAutoPrompt = false;
- // Opening the Linux setup guide can background the app; skip that resume.
+ // Opening the Linux setup guide backgrounds the app; skip that resume.
bool _suppressNextLifecyclePrompt = false;
@override
@@ -202,7 +201,7 @@ class _LockScreenState extends State<LockScreen> with WidgetsBindingObserver {
} else {
await UserService.instance.logout(context);
}
- // To start the app afresh, resetting all state.
+ // Restart from a clean process after logout.
Process.killPid(pid, ProcessSignal.sigkill);
},
),
@@ -221,15 +220,12 @@ class _LockScreenState extends State<LockScreen> with WidgetsBindingObserver {
_hasPlacedAppInBackground = false;
return;
}
- // This is triggered either when the lock screen is dismissed or when
- // the app is brought to foreground
_hasPlacedAppInBackground = false;
final bool didAuthInLast5Seconds =
lastAuthenticatingTime != null &&
DateTime.now().millisecondsSinceEpoch - lastAuthenticatingTime! <
5000;
if (!_hasAuthenticationFailed && !didAuthInLast5Seconds) {
- // If there is a cooldown timer (after multiple failures), respect it
if (_lockscreenSetting.getlastInvalidAttemptTime() >
DateTime.now().millisecondsSinceEpoch &&
!_isShowingLockScreen) {
@@ -242,21 +238,16 @@ class _LockScreenState extends State<LockScreen> with WidgetsBindingObserver {
_showLockScreen(source: "lifeCycle");
});
} else if (!_suppressAutoPrompt) {
- // No cooldown: auto-prompt when app becomes active again
_showLockScreen(source: "lifeCycle");
}
} else {
- _hasAuthenticationFailed = false; // Reset failure state
+ _hasAuthenticationFailed = false;
}
} else if (state == AppLifecycleState.paused ||
state == AppLifecycleState.inactive) {
- // This is triggered either when the lock screen pops up or when
- // the app is pushed to background
if (!_isShowingLockScreen) {
_hasPlacedAppInBackground = true;
- _hasAuthenticationFailed = false; // reset failure state
- // If we suppressed the initial auto-prompt due to manual lock,
- // enable auto-prompt for the next resume after focus loss.
+ _hasAuthenticationFailed = false;
_suppressAutoPrompt = false;
}
}
@@ -364,15 +355,13 @@ class _LockScreenState extends State<LockScreen> with WidgetsBindingObserver {
isTimerRunning = false;
});
} else {
+ // Backgrounding the app is not a failed authentication.
if (!_hasPlacedAppInBackground) {
- // Treat this as a failure only if user did not explicitly
- // put the app in background
if (_lockscreenSetting.getInvalidAttemptCount() > 4 &&
invalidAttemptCount !=
_lockscreenSetting.getInvalidAttemptCount()) {
invalidAttemptCount = _lockscreenSetting.getInvalidAttemptCount();
- // For logged-in users, auto-logout after 10 failed attempts
if (invalidAttemptCount > 9 && widget.config.isLoggedIn()) {
await _autoLogoutOnMaxInvalidAttempts();
return;
diff --git a/mobile/packages/lock_screen/lib/ui/lock_screen_password.dart b/mobile/packages/lock_screen/lib/ui/lock_screen_password.dart
index 4bb6d37bf2..cc8bdd58f1 100644
--- a/mobile/packages/lock_screen/lib/ui/lock_screen_password.dart
+++ b/mobile/packages/lock_screen/lib/ui/lock_screen_password.dart
@@ -8,16 +8,6 @@ import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:flutter_svg/flutter_svg.dart";
-/// [isChangingLockScreenSettings] Authentication required for changing lock screen settings.
-/// Set to true when the app requires the user to authenticate before allowing
-/// changes to the lock screen settings.
-
-/// [isAuthenticatingOnAppLaunch] Authentication required on app launch.
-/// Set to true when the app requires the user to authenticate immediately upon opening.
-
-/// [isAuthenticatingForInAppChange] Authentication required for in-app changes (e.g., email, password).
-/// Set to true when the app requires the to authenticate for sensitive actions like email, password changes.
-
class LockScreenPassword extends StatefulWidget {
const LockScreenPassword({
super.key,
diff --git a/mobile/packages/lock_screen/lib/ui/lock_screen_pin.dart b/mobile/packages/lock_screen/lib/ui/lock_screen_pin.dart
index 6ab73a0e5b..800363f155 100644
--- a/mobile/packages/lock_screen/lib/ui/lock_screen_pin.dart
+++ b/mobile/packages/lock_screen/lib/ui/lock_screen_pin.dart
@@ -11,16 +11,6 @@ import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:flutter_svg/flutter_svg.dart";
-/// [isChangingLockScreenSettings] Authentication required for changing lock screen settings.
-/// Set to true when the app requires the user to authenticate before allowing
-/// changes to the lock screen settings.
-
-/// [isAuthenticatingOnAppLaunch] Authentication required on app launch.
-/// Set to true when the app requires the user to authenticate immediately upon opening.
-
-/// [isAuthenticatingForInAppChange] Authentication required for in-app changes (e.g., email, password).
-/// Set to true when the app requires the to authenticate for sensitive actions like email, password changes.
-
class LockScreenPin extends StatefulWidget {
const LockScreenPin({
super.key,
diff --git a/mobile/packages/log_viewer/lib/log_viewer.dart b/mobile/packages/log_viewer/lib/log_viewer.dart
index 651939e384..31013f2b25 100644
--- a/mobile/packages/log_viewer/lib/log_viewer.dart
+++ b/mobile/packages/log_viewer/lib/log_viewer.dart
@@ -5,53 +5,40 @@ import 'package:logging/logging.dart' as log;
export 'src/core/log_database.dart';
export 'src/core/log_models.dart';
-// Core exports
export 'src/core/log_store.dart';
export 'src/ui/log_detail_page.dart';
export 'src/ui/log_filter_dialog.dart';
export 'src/ui/log_list_tile.dart';
-// UI exports
export 'src/ui/log_viewer_page.dart';
-/// Main entry point for the log viewer functionality
class LogViewer {
static bool _initialized = false;
static String _prefix = '';
- /// Initialize the log viewer
- /// This should be called once during app startup
static Future<void> initialize({String prefix = ''}) async {
if (_initialized) return;
_prefix = prefix;
- // Initialize the log store
await LogStore.instance.initialize();
- // Register callback with super_logging if available
_registerWithSuperLogging();
_initialized = true;
}
- /// Register callback with super_logging to receive logs
static void _registerWithSuperLogging() {
- // Try to register with SuperLogging if available
try {
- // This will be called dynamically by the main app if SuperLogging is available
- // For now, fallback to direct logger listening without prefix
log.Logger.root.onRecord.listen((record) {
LogStore.addLogRecord(record, _prefix);
});
} catch (e) {
- // SuperLogging not available, fallback to direct logger
log.Logger.root.onRecord.listen((record) {
LogStore.addLogRecord(record, '');
});
}
}
- /// Get the log viewer page widget
static Widget getViewerPage() {
if (!_initialized) {
throw StateError(
@@ -61,7 +48,6 @@ class LogViewer {
return const LogViewerPage();
}
- /// Open the log viewer in a new route
static Future<void> openViewer(BuildContext context) async {
if (!_initialized) {
await initialize();
@@ -76,10 +62,8 @@ class LogViewer {
);
}
- /// Check if log viewer is initialized
static bool get isInitialized => _initialized;
- /// Dispose of log viewer resources
static Future<void> dispose() async {
if (_initialized) {
await LogStore.instance.dispose();
diff --git a/mobile/packages/log_viewer/lib/src/core/log_database.dart b/mobile/packages/log_viewer/lib/src/core/log_database.dart
index 9cbd49507b..cf51b7cc0c 100644
--- a/mobile/packages/log_viewer/lib/src/core/log_database.dart
+++ b/mobile/packages/log_viewer/lib/src/core/log_database.dart
@@ -5,7 +5,6 @@ import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
-/// Manages SQLite database for log storage
class LogDatabase {
static const String _databaseName = 'log_viewer.db';
static const String _tableName = 'logs';
@@ -16,13 +15,11 @@ class LogDatabase {
LogDatabase({this.maxEntries = 10000});
- /// Get database instance
Future<Database> get database async {
_database ??= await _initDatabase();
return _database!;
}
- /// Initialize database
Future<Database> _initDatabase() async {
final documentsDirectory = await getApplicationDocumentsDirectory();
final path = join(documentsDirectory.path, _databaseName);
@@ -35,7 +32,6 @@ class LogDatabase {
);
}
- /// Create database tables
Future<void> _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $_tableName(
@@ -50,31 +46,24 @@ class LogDatabase {
)
''');
- // Minimal indexes for write performance - only timestamp for ordering
await db.execute(
'CREATE INDEX idx_timestamp ON $_tableName(timestamp DESC)',
);
}
- /// Called when database is opened
Future<void> _onOpen(Database db) async {
- // Enable write-ahead logging for better performance
- // Use rawQuery for PRAGMA commands to avoid permission issues
await db.rawQuery('PRAGMA journal_mode = WAL');
}
- /// Insert a single log entry
Future<int> insertLog(LogEntry entry) async {
final db = await database;
final id = await db.insert(_tableName, entry.toMap());
- // Auto-truncate if needed
await _truncateIfNeeded(db);
return id;
}
- /// Insert multiple log entries in a batch
Future<void> insertLogs(List<LogEntry> entries) async {
if (entries.isEmpty) return;
@@ -89,7 +78,6 @@ class LogDatabase {
await _truncateIfNeeded(db);
}
- /// Get logs with optional filtering
Future<List<LogEntry>> getLogs({
LogFilter? filter,
int limit = 250,
@@ -97,12 +85,10 @@ class LogDatabase {
}) async {
final db = await database;
- // Build WHERE clause
final conditions = <String>[];
final args = <dynamic>[];
if (filter != null) {
- // Logger filter
if (filter.selectedLoggers.isNotEmpty) {
final placeholders = List.filled(
filter.selectedLoggers.length,
@@ -112,7 +98,6 @@ class LogDatabase {
args.addAll(filter.selectedLoggers);
}
- // Level filter
if (filter.selectedLevels.isNotEmpty) {
final placeholders = List.filled(
filter.selectedLevels.length,
@@ -122,7 +107,6 @@ class LogDatabase {
args.addAll(filter.selectedLevels);
}
- // Process prefix filter
if (filter.selectedProcesses.isNotEmpty) {
final placeholders = List.filled(
filter.selectedProcesses.length,
@@ -132,7 +116,6 @@ class LogDatabase {
args.addAll(filter.selectedProcesses);
}
- // Search query
if (filter.searchQuery != null && filter.searchQuery!.isNotEmpty) {
conditions.add('(message LIKE ? OR error LIKE ?)');
final searchPattern = '%${filter.searchQuery}%';
@@ -140,7 +123,6 @@ class LogDatabase {
args.add(searchPattern);
}
- // Time range
if (filter.startTime != null) {
conditions.add('timestamp >= ?');
args.add(filter.startTime!.millisecondsSinceEpoch);
@@ -167,7 +149,6 @@ class LogDatabase {
return results.map((map) => LogEntry.fromMap(map)).toList();
}
- /// Get unique logger names for filtering
Future<List<String>> getUniqueLoggers() async {
final db = await database;
final results = await db.rawQuery(
@@ -177,7 +158,6 @@ class LogDatabase {
return results.map((row) => row['logger_name'] as String).toList();
}
- /// Get unique process prefixes for filtering
Future<List<String>> getUniqueProcesses() async {
final db = await database;
final results = await db.rawQuery(
@@ -188,14 +168,12 @@ class LogDatabase {
.map((row) => row['process_prefix'] as String)
.toList();
- // Always include 'Foreground' as an option for empty prefix
final uniquePrefixes = <String>[''];
uniquePrefixes.addAll(prefixes);
return uniquePrefixes;
}
- /// Get count of logs matching filter
Future<int> getLogCount({LogFilter? filter}) async {
final db = await database;
@@ -206,7 +184,6 @@ class LogDatabase {
return result.first['count'] as int;
}
- // Build WHERE clause (same as getLogs)
final conditions = <String>[];
final args = <dynamic>[];
@@ -261,13 +238,11 @@ class LogDatabase {
return result.first['count'] as int;
}
- /// Clear all logs
Future<void> clearLogs() async {
final db = await database;
await db.delete(_tableName);
}
- /// Clear logs by logger name
Future<void> clearLogsByLogger(String loggerName) async {
final db = await database;
await db.delete(
@@ -277,18 +252,15 @@ class LogDatabase {
);
}
- /// Truncate old logs if over limit
Future<void> _truncateIfNeeded(Database db) async {
final countResult = await db.rawQuery(
'SELECT COUNT(*) as count FROM $_tableName',
);
final count = countResult.first['count'] as int;
- // When we reach 11k+ entries, keep only the last 10k
if (count >= maxEntries + 1000) {
final toDelete = count - maxEntries;
- // Delete oldest entries
await db.execute(
'''
DELETE FROM $_tableName
@@ -303,11 +275,9 @@ class LogDatabase {
}
}
- /// Get logger statistics with count and percentage
Future<List<LoggerStatistic>> getLoggerStatistics({LogFilter? filter}) async {
final db = await database;
- // Build WHERE clause (same as getLogs)
final conditions = <String>[];
final args = <dynamic>[];
@@ -360,14 +330,12 @@ class LogDatabase {
? ''
: 'WHERE ${conditions.join(' AND ')}';
- // Get total count for percentage calculation
final totalQuery = 'SELECT COUNT(*) as total FROM $_tableName $whereClause';
final totalResult = await db.rawQuery(totalQuery, args);
final totalCount = totalResult.first['total'] as int;
if (totalCount == 0) return [];
- // Get logger statistics using single optimized query
final statsQuery =
'''
SELECT
@@ -393,7 +361,6 @@ class LogDatabase {
.toList();
}
- /// Get time range of all logs
Future<TimeRange?> getTimeRange() async {
final db = await database;
final result = await db.rawQuery('''
@@ -417,7 +384,6 @@ class LogDatabase {
return null;
}
- /// Get all log timestamps for timeline visualization
Future<List<DateTime>> getLogTimestamps() async {
final db = await database;
final result = await db.rawQuery('''
@@ -433,7 +399,6 @@ class LogDatabase {
.toList();
}
- /// Close database connection
Future<void> close() async {
final db = _database;
if (db != null) {
diff --git a/mobile/packages/log_viewer/lib/src/core/log_models.dart b/mobile/packages/log_viewer/lib/src/core/log_models.dart
index c03f614481..f2f37065d2 100644
--- a/mobile/packages/log_viewer/lib/src/core/log_models.dart
+++ b/mobile/packages/log_viewer/lib/src/core/log_models.dart
@@ -1,6 +1,5 @@
import 'package:flutter/material.dart';
-/// Represents a single log entry
class LogEntry {
final int? id;
final String message;
@@ -22,7 +21,6 @@ class LogEntry {
this.processPrefix = '',
});
- /// Create from database map
factory LogEntry.fromMap(Map<String, dynamic> map) {
return LogEntry(
id: map['id'] as int?,
@@ -36,7 +34,6 @@ class LogEntry {
);
}
- /// Convert to database map
Map<String, dynamic> toMap() {
return {
if (id != null) 'id': id,
@@ -50,7 +47,6 @@ class LogEntry {
};
}
- /// Get color based on log level
Color get levelColor {
switch (level.toUpperCase()) {
case 'SHOUT':
@@ -71,7 +67,6 @@ class LogEntry {
}
}
- /// Get background color for list tile
Color? get backgroundColor {
switch (level.toUpperCase()) {
case 'SHOUT':
@@ -84,7 +79,6 @@ class LogEntry {
}
}
- /// Truncate message for preview
String get truncatedMessage {
final lines = message.split('\n');
const maxLines = 4;
@@ -96,7 +90,6 @@ class LogEntry {
return '${lines.take(maxLines).join('\n')}...';
}
- /// Format timestamp for display
String get formattedTime {
final hour = timestamp.hour.toString().padLeft(2, '0');
final minute = timestamp.minute.toString().padLeft(2, '0');
@@ -105,12 +98,10 @@ class LogEntry {
return '$hour:$minute:$second.$millis';
}
- /// Get display name for process prefix
String get processDisplayName {
if (processPrefix.isEmpty) {
return 'Foreground';
}
- // Remove square brackets if present (e.g., "[fbg]" -> "fbg")
final cleanPrefix = processPrefix.replaceAll(RegExp(r'[\[\]]'), '');
switch (cleanPrefix) {
case 'fbg':
@@ -135,7 +126,6 @@ class LogEntry {
}
}
-/// Filter configuration for log queries
class LogFilter {
final Set<String> selectedLoggers;
final Set<String> selectedLevels;
@@ -155,7 +145,6 @@ class LogFilter {
this.sortNewestFirst = true,
});
- /// Create a copy with modifications
LogFilter copyWith({
Set<String>? selectedLoggers,
Set<String>? selectedLevels,
@@ -178,7 +167,6 @@ class LogFilter {
);
}
- /// Check if any filters are active
bool get hasActiveFilters {
return selectedLoggers.isNotEmpty ||
selectedLevels.isNotEmpty ||
@@ -188,11 +176,9 @@ class LogFilter {
endTime != null;
}
- /// Clear all filters
static const LogFilter empty = LogFilter();
}
-/// Logger statistics data
class LoggerStatistic {
final String loggerName;
final int logCount;
@@ -204,10 +190,8 @@ class LoggerStatistic {
required this.percentage,
});
- /// Alias for logCount for compatibility
int get count => logCount;
- /// Format percentage for display
String get formattedPercentage {
if (percentage >= 10) {
return '${percentage.toStringAsFixed(1)}%';
@@ -219,7 +203,6 @@ class LoggerStatistic {
}
}
-/// Available log levels
class LogLevels {
static const List<String> all = [
'ALL',
@@ -234,7 +217,6 @@ class LogLevels {
'OFF',
];
- /// Get levels typically shown by default
static const List<String> defaultVisible = [
'INFO',
'WARNING',
@@ -243,7 +225,6 @@ class LogLevels {
];
}
-/// Represents a time range for logs
class TimeRange {
final DateTime start;
final DateTime end;
diff --git a/mobile/packages/log_viewer/lib/src/core/log_store.dart b/mobile/packages/log_viewer/lib/src/core/log_store.dart
index 5859b779a2..4f69145cca 100644
--- a/mobile/packages/log_viewer/lib/src/core/log_store.dart
+++ b/mobile/packages/log_viewer/lib/src/core/log_store.dart
@@ -4,7 +4,6 @@ import 'package:log_viewer/src/core/log_database.dart';
import 'package:log_viewer/src/core/log_models.dart';
import 'package:logging/logging.dart' as log;
-/// Singleton store that receives and manages logs
class LogStore {
static final LogStore _instance = LogStore._internal();
static LogStore get instance => _instance;
@@ -14,38 +13,32 @@ class LogStore {
final LogDatabase _database = LogDatabase();
final _logStreamController = StreamController<LogEntry>.broadcast();
- // Buffer for batch inserts - optimized for small entries
final List<LogEntry> _buffer = [];
Timer? _flushTimer;
static const int _bufferSize = 10;
- static const int _maxBufferSize = 200; // Safety limit
+ static const int _maxBufferSize = 200;
bool _initialized = false;
bool get initialized => _initialized;
- /// Stream of new log entries
Stream<LogEntry> get logStream => _logStreamController.stream;
- /// Initialize the log store
Future<void> initialize() async {
if (_initialized) return;
- await _database.database; // Initialize database
+ await _database.database;
- // Start periodic flush timer - less frequent for better batching
_flushTimer = Timer.periodic(const Duration(seconds: 15), (_) => _flush());
_initialized = true;
}
- /// Static method that super_logging.dart will call
static void addLogRecord(log.LogRecord record, [String? processPrefix]) {
if (_instance._initialized) {
_instance._addLog(record, processPrefix ?? '');
}
}
- /// Add a log from a LogRecord
void _addLog(log.LogRecord record, String processPrefix) {
final entry = LogEntry(
message: record.message,
@@ -57,29 +50,23 @@ class LogStore {
processPrefix: processPrefix,
);
- // Add to buffer for batch insert
_buffer.add(entry);
- // Emit to stream for real-time updates
_logStreamController.add(entry);
- // Flush when buffer reaches optimal size or safety limit
if (_buffer.length >= _bufferSize) {
_flush();
} else if (_buffer.length >= _maxBufferSize) {
- // Emergency flush if buffer grows too large
_flush();
}
}
- /// Flush buffered logs to database
Future<void> _flush() async {
if (_buffer.isEmpty) return;
final toInsert = List<LogEntry>.from(_buffer);
_buffer.clear();
- // Use non-blocking database insert for better write performance
unawaited(
_database.insertLogs(toInsert).catchError((e) {
// ignore: avoid_print
@@ -88,53 +75,44 @@ class LogStore {
);
}
- /// Get logs with filtering
Future<List<LogEntry>> getLogs({
LogFilter? filter,
int limit = 250,
int offset = 0,
}) async {
- // Flush any pending logs first
await _flush();
return _database.getLogs(filter: filter, limit: limit, offset: offset);
}
- /// Get unique logger names
Future<List<String>> getLoggerNames() async {
return _database.getUniqueLoggers();
}
- /// Get unique process prefixes
Future<List<String>> getProcessNames() async {
return _database.getUniqueProcesses();
}
- /// Get logger statistics with count and percentage
Future<List<LoggerStatistic>> getLoggerStatistics({LogFilter? filter}) async {
await _flush();
return _database.getLoggerStatistics(filter: filter);
}
- /// Get count of logs matching filter
Future<int> getLogCount({LogFilter? filter}) async {
await _flush();
return _database.getLogCount(filter: filter);
}
- /// Clear all logs
Future<void> clearLogs() async {
_buffer.clear();
await _database.clearLogs();
}
- /// Clear logs by logger
Future<void> clearLogsByLogger(String loggerName) async {
_buffer.removeWhere((log) => log.loggerName == loggerName);
await _database.clearLogsByLogger(loggerName);
}
- /// Export logs as text
Future<String> exportLogs({LogFilter? filter}) async {
final logs = await getLogs(filter: filter, limit: 10000);
@@ -165,19 +143,16 @@ class LogStore {
return buffer.toString();
}
- /// Get time range of all logs
Future<TimeRange?> getTimeRange() async {
await _flush();
return _database.getTimeRange();
}
- /// Get all log timestamps for timeline visualization
Future<List<DateTime>> getLogTimestamps() async {
await _flush();
return _database.getLogTimestamps();
}
- /// Export logs as JSON
Future<String> exportLogsAsJson({LogFilter? filter}) async {
final logs = await getLogs(filter: filter, limit: 10000);
@@ -194,7 +169,6 @@ class LogStore {
)
.toList();
- // Manual JSON formatting for readability
final buffer = StringBuffer();
buffer.writeln('[');
for (int i = 0; i < jsonLogs.length; i++) {
@@ -211,7 +185,6 @@ class LogStore {
return buffer.toString();
}
- /// Dispose resources
Future<void> dispose() async {
_flushTimer?.cancel();
await _flush();
diff --git a/mobile/packages/log_viewer/lib/src/ui/log_detail_page.dart b/mobile/packages/log_viewer/lib/src/ui/log_detail_page.dart
index d8066cf9d3..68e0e6fa7d 100644
--- a/mobile/packages/log_viewer/lib/src/ui/log_detail_page.dart
+++ b/mobile/packages/log_viewer/lib/src/ui/log_detail_page.dart
@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:log_viewer/src/core/log_models.dart';
-/// Detailed view of a single log entry
class LogDetailPage extends StatelessWidget {
final LogEntry log;
@@ -126,7 +125,6 @@ class LogDetailPage extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- // Log metadata
Container(
width: double.infinity,
color: theme.appBarTheme.backgroundColor,
@@ -156,14 +154,12 @@ class LogDetailPage extends StatelessWidget {
),
),
- // Message section
_buildSection(
context: context,
title: 'MESSAGE',
content: log.message,
),
- // Error section (if present)
if (log.error != null)
_buildSection(
context: context,
@@ -171,7 +167,6 @@ class LogDetailPage extends StatelessWidget {
content: log.error!,
),
- // Stack trace section (if present)
if (log.stackTrace != null)
_buildSection(
context: context,
diff --git a/mobile/packages/log_viewer/lib/src/ui/log_filter_dialog.dart b/mobile/packages/log_viewer/lib/src/ui/log_filter_dialog.dart
index a5c735e3d9..7985384bba 100644
--- a/mobile/packages/log_viewer/lib/src/ui/log_filter_dialog.dart
+++ b/mobile/packages/log_viewer/lib/src/ui/log_filter_dialog.dart
@@ -1,7 +1,6 @@
import 'package:flutter/material.dart';
import 'package:log_viewer/src/core/log_models.dart';
-/// Dialog for configuring log filters
class LogFilterDialog extends StatefulWidget {
final List<String> availableLoggers;
final List<String> availableProcesses;
@@ -106,7 +105,6 @@ class _LogFilterDialogState extends State<LogFilterDialog> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
- // Header
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: const BoxDecoration(
@@ -132,7 +130,6 @@ class _LogFilterDialogState extends State<LogFilterDialog> {
),
),
- // Content
Flexible(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(
@@ -142,7 +139,6 @@ class _LogFilterDialogState extends State<LogFilterDialog> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- // Log Levels
Text(
'Log Levels',
style: theme.textTheme.titleMedium?.copyWith(
@@ -161,7 +157,6 @@ class _LogFilterDialogState extends State<LogFilterDialog> {
),
const SizedBox(height: 16),
- // Process Prefixes
if (widget.availableProcesses.isNotEmpty) ...[
Text(
'Process',
@@ -270,7 +265,6 @@ class _LogFilterDialogState extends State<LogFilterDialog> {
const SizedBox(height: 16),
],
- // Loggers
if (widget.availableLoggers.isNotEmpty) ...[
Text(
'Loggers',
@@ -373,7 +367,6 @@ class _LogFilterDialogState extends State<LogFilterDialog> {
),
),
- // Actions
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
diff --git a/mobile/packages/log_viewer/lib/src/ui/log_list_tile.dart b/mobile/packages/log_viewer/lib/src/ui/log_list_tile.dart
index f9c64479a6..3eec5038d6 100644
--- a/mobile/packages/log_viewer/lib/src/ui/log_list_tile.dart
+++ b/mobile/packages/log_viewer/lib/src/ui/log_list_tile.dart
@@ -1,7 +1,6 @@
import 'package:flutter/material.dart';
import 'package:log_viewer/src/core/log_models.dart';
-/// Individual log item widget
class LogListTile extends StatelessWidget {
final LogEntry log;
final VoidCallback onTap;
diff --git a/mobile/packages/log_viewer/lib/src/ui/log_viewer_page.dart b/mobile/packages/log_viewer/lib/src/ui/log_viewer_page.dart
index 4c36613512..e2548bac78 100644
--- a/mobile/packages/log_viewer/lib/src/ui/log_viewer_page.dart
+++ b/mobile/packages/log_viewer/lib/src/ui/log_viewer_page.dart
@@ -10,7 +10,6 @@ import 'package:log_viewer/src/ui/logger_statistics_page.dart';
import 'package:log_viewer/src/ui/timeline_widget.dart';
import 'package:share_plus/share_plus.dart';
-/// Main log viewer page
class LogViewerPage extends StatefulWidget {
const LogViewerPage({super.key});
@@ -32,13 +31,11 @@ class _LogViewerPageState extends State<LogViewerPage> {
bool _isLoadingMore = false;
bool _hasMoreLogs = true;
int _currentOffset = 0;
- static const int _pageSize = 100; // Load 100 logs at a time
+ static const int _pageSize = 100;
StreamSubscription<LogEntry>? _logStreamSubscription;
- // Time filtering state
bool _timeFilterEnabled = false;
- // Timeline state
DateTime? _overallStartTime;
DateTime? _overallEndTime;
DateTime? _timelineStartTime;
@@ -57,9 +54,7 @@ class _LogViewerPageState extends State<LogViewerPage> {
await _initializeTimeline();
await _loadLogs();
- // Listen for new logs
_logStreamSubscription = _logStore.logStream.listen((_) {
- // Debounce updates to avoid too frequent refreshes
_scheduleRefresh();
});
}
@@ -177,12 +172,10 @@ class _LogViewerPageState extends State<LogViewerPage> {
}
void _onSearchChanged(String query) {
- // Parse query for special syntax like "logger:SomeName"
String? searchText = query;
Set<String>? loggerFilters;
if (query.isNotEmpty) {
- // Regular expression to match logger:name patterns
final loggerPattern = RegExp(r'logger:(\S+)');
final matches = loggerPattern.allMatches(query);
@@ -191,10 +184,8 @@ class _LogViewerPageState extends State<LogViewerPage> {
for (final match in matches) {
final loggerName = match.group(1);
if (loggerName != null) {
- // Support wildcards (e.g., Auth* matches AuthService, Authentication, etc.)
if (loggerName.endsWith('*')) {
final prefix = loggerName.substring(0, loggerName.length - 1);
- // Find all loggers that start with this prefix
for (final logger in _availableLoggers) {
if (logger.startsWith(prefix)) {
loggerFilters.add(logger);
@@ -206,19 +197,16 @@ class _LogViewerPageState extends State<LogViewerPage> {
}
}
- // Remove logger:name patterns from search text
searchText = query.replaceAll(loggerPattern, '').trim();
if (searchText.isEmpty) {
searchText = null;
}
}
} else {
- // Clear logger filters when search is empty
loggerFilters = {};
}
setState(() {
- // Only update logger filters if logger: syntax was found or query is empty
final newLoggerFilters =
loggerFilters ??
(query.isEmpty ? <String>{} : _filter.selectedLoggers);
@@ -248,18 +236,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
_loadLogs();
}
- // String _formatTimeRange(double hours) {
- // if (hours < 1) {
- // final minutes = (hours * 60).round();
- // return '${minutes}m';
- // } else if (hours < 24) {
- // return '${hours.round()}h';
- // } else {
- // final days = (hours / 24).round();
- // return '${days}d';
- // }
- // }
-
Future<void> _showFilterDialog() async {
final newFilter = await showDialog<LogFilter>(
context: context,
@@ -337,7 +313,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
),
);
- // If a logger filter was returned, apply it to the search box
if (result != null && mounted) {
_searchController.text = result;
_onSearchChanged(result);
@@ -455,7 +430,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
),
body: Column(
children: [
- // Search bar
Container(
color: theme.appBarTheme.backgroundColor,
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 6.0),
@@ -488,7 +462,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
),
),
- // Timeline filter
if (_overallStartTime != null && _overallEndTime != null) ...[
Container(
color: theme.appBarTheme.backgroundColor,
@@ -521,7 +494,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
setState(() {
_timeFilterEnabled = !_timeFilterEnabled;
if (_timeFilterEnabled) {
- // Reset timeline to full range when enabled
_timelineStartTime = _overallStartTime;
_timelineEndTime = _overallEndTime;
}
@@ -547,7 +519,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
],
],
- // Active filters display
if (_filter.hasActiveFilters)
Container(
height: 40,
@@ -647,7 +618,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
),
),
- // Log list
Expanded(
child: _isLoading
? const Center(child: CircularProgressIndicator())
@@ -678,7 +648,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
? const SizedBox.shrink()
: const Divider(height: 1),
itemBuilder: (context, index) {
- // Show loading indicator at the bottom
if (index >= _logs.length) {
if (_isLoadingMore) {
return const Padding(
@@ -686,7 +655,6 @@ class _LogViewerPageState extends State<LogViewerPage> {
child: Center(child: CircularProgressIndicator()),
);
} else {
- // Trigger loading more when reaching the end
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadMoreLogs();
});
diff --git a/mobile/packages/log_viewer/lib/src/ui/logger_statistics_page.dart b/mobile/packages/log_viewer/lib/src/ui/logger_statistics_page.dart
index c621cec860..e0f6fefc4e 100644
--- a/mobile/packages/log_viewer/lib/src/ui/logger_statistics_page.dart
+++ b/mobile/packages/log_viewer/lib/src/ui/logger_statistics_page.dart
@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:log_viewer/src/core/log_models.dart';
import 'package:log_viewer/src/core/log_store.dart';
-/// Page showing logger statistics with percentage breakdown
class LoggerStatisticsPage extends StatefulWidget {
final LogFilter filter;
@@ -49,7 +48,6 @@ class _LoggerStatisticsPageState extends State<LoggerStatisticsPage> {
}
Color _getLoggerColor(int index, double percentage) {
- // Color coding based on percentage
if (percentage > 50) return Colors.red.shade400;
if (percentage > 20) return Colors.orange.shade400;
if (percentage > 10) return Colors.blue.shade400;
@@ -118,7 +116,6 @@ class _LoggerStatisticsPageState extends State<LoggerStatisticsPage> {
)
: Column(
children: [
- // Summary cards
Container(
padding: const EdgeInsets.all(16),
child: Row(
@@ -146,7 +143,6 @@ class _LoggerStatisticsPageState extends State<LoggerStatisticsPage> {
),
),
- // Statistics list
Expanded(
child: RefreshIndicator(
onRefresh: _loadStatistics,
@@ -161,7 +157,6 @@ class _LoggerStatisticsPageState extends State<LoggerStatisticsPage> {
margin: const EdgeInsets.only(bottom: 8),
child: InkWell(
onTap: () {
- // Navigate back to log viewer with logger filter in search
Navigator.pop(
context,
'logger:${stat.loggerName}',
diff --git a/mobile/packages/log_viewer/lib/src/ui/timeline_widget.dart b/mobile/packages/log_viewer/lib/src/ui/timeline_widget.dart
index 77ae4778e4..a113f9e142 100644
--- a/mobile/packages/log_viewer/lib/src/ui/timeline_widget.dart
+++ b/mobile/packages/log_viewer/lib/src/ui/timeline_widget.dart
@@ -64,7 +64,6 @@ class _TimelineWidgetState extends State<TimelineWidget> {
final RenderBox renderBox = context.findRenderObject() as RenderBox;
final double width = renderBox.size.width - 40; // Account for handle width
- // Convert global position to local position within the timeline track
final Offset globalPosition = details.globalPosition;
final Offset localPosition = renderBox.globalToLocal(globalPosition);
final double localX =
@@ -114,7 +113,6 @@ class _TimelineWidgetState extends State<TimelineWidget> {
builder: (context, constraints) {
return Stack(
children: [
- // Timeline track
Positioned(
left: 20,
right: 20,
@@ -137,7 +135,6 @@ class _TimelineWidgetState extends State<TimelineWidget> {
),
),
- // Selected range
Positioned(
left: 20 + (_leftPosition * (constraints.maxWidth - 40)),
right:
@@ -162,7 +159,6 @@ class _TimelineWidgetState extends State<TimelineWidget> {
),
),
- // Left handle
Positioned(
left: (_leftPosition * (constraints.maxWidth - 40)),
top: 12,
@@ -199,7 +195,6 @@ class _TimelineWidgetState extends State<TimelineWidget> {
),
),
- // Right handle
Positioned(
left: (_rightPosition * (constraints.maxWidth - 40)),
top: 12,
@@ -241,7 +236,6 @@ class _TimelineWidgetState extends State<TimelineWidget> {
),
),
- // Time labels
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
@@ -271,7 +265,6 @@ class _TimelineWidgetState extends State<TimelineWidget> {
final bucketDuration = totalDuration / bucketCount;
final buckets = List<int>.filled(bucketCount, 0);
- // Count logs in each bucket
for (final timestamp in widget.logTimestamps) {
final offset = timestamp.difference(widget.startTime).inMilliseconds;
if (offset >= 0 && offset <= totalDuration) {
diff --git a/mobile/packages/logging/lib/super_logging.dart b/mobile/packages/logging/lib/super_logging.dart
index 68d0b2d674..912e9c2626 100644
--- a/mobile/packages/logging/lib/super_logging.dart
+++ b/mobile/packages/logging/lib/super_logging.dart
@@ -17,7 +17,6 @@ import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
-/// Type definition for functions that may return a value or Future
typedef FutureOrVoidCallback = dynamic Function();
extension SuperString on String {
@@ -72,65 +71,20 @@ extension SuperLogRecord on log.LogRecord {
}
class LogConfig {
- /// The DSN for a Sentry app.
- /// This can be obtained from the Sentry apps's "settings > Client Keys (DSN)" page.
- ///
- /// Only logs containing errors are sent to sentry.
- /// Errors can be caught using a try-catch block, like so:
- ///
- /// ```
- /// final logger = Logger("main");
- ///
- /// try {
- /// // do something dangerous here
- /// } catch(e, trace) {
- /// logger.info("Huston, we have a problem", e, trace);
- /// }
- /// ```
- ///
- /// If this is [null], Sentry logger is completely disabled (default).
String? sentryDsn;
String? tunnel;
- /// A built-in retry mechanism for sending errors to sentry.
- ///
- /// This parameter defines the time to wait for, before retrying.
Duration sentryRetryDelay;
- /// Path of the directory where log files will be stored.
- ///
- /// If this is [null], file logging is completely disabled (default).
- ///
- /// If this is an empty string (['']),
- /// then a 'logs' directory will be created in [getTemporaryDirectory()].
- ///
- /// A non-empty string will be treated as an explicit path to a directory.
- ///
- /// The chosen directory can be accessed using [SuperLogging.logFile.parent].
String? logDirPath;
- /// The maximum number of log files inside [logDirPath].
- ///
- /// One log file is created per day.
- /// Older log files are deleted automatically.
int maxLogFiles;
- /// Whether to enable super logging features in debug mode.
- ///
- /// Sentry and file logging are typically not needed in debug mode,
- /// where a complete logcat is available.
bool enableInDebugMode;
- /// If provided, super logging will invoke this function, and
- /// any uncaught errors during its execution will be reported.
- ///
- /// Works by using [FlutterError.onError] and [runZoned].
FutureOrVoidCallback? body;
- /// The date format for storing log files.
- ///
- /// `DateFormat('y-M-d')` by default.
DateFormat? dateFmt;
String prefix;
@@ -151,10 +105,8 @@ class LogConfig {
}
class SuperLogging {
- /// The logger for SuperLogging
static final $ = log.Logger('ente_logging');
- /// The current super logging configuration
static late LogConfig config;
static late SharedPreferences _preferences;
@@ -239,7 +191,6 @@ class SuperLogging {
static String _lastExtraLines = '';
static Future onLogRecord(log.LogRecord rec) async {
- // log misc info if it changed
String? extraLines = "app version: '$appVersion'\n";
if (extraLines != _lastExtraLines) {
_lastExtraLines = extraLines;
@@ -249,10 +200,8 @@ class SuperLogging {
final str = "${config.prefix} ${rec.toPrettyString(extraLines)}";
- // write to stdout
printLog(str);
- // push to log queue
if (fileIsEnabled) {
fileQueueEntries.add('$str\n');
if (fileQueueEntries.length == 1) {
@@ -260,7 +209,6 @@ class SuperLogging {
}
}
- // add error to sentry queue
if (sentryIsEnabled && rec.error != null) {
_sendErrorToSentry(rec.error!, null).ignore();
}
@@ -282,18 +230,16 @@ class SuperLogging {
}
}
- // Logs on must be chunked or they get truncated otherwise
- // See https://github.com/flutter/flutter/issues/22665
+ // Long logs are truncated unless chunked.
+ // https://github.com/flutter/flutter/issues/22665
static var logChunkSize = 800;
static void printLog(String text) {
text.chunked(logChunkSize).forEach(debugPrint);
}
- /// A queue to be consumed by [setupSentry].
static final sentryQueueControl = StreamController<Error>();
- /// Whether sentry logging is currently enabled or not.
static bool sentryIsEnabled = false;
static Future<void> setupSentry() async {
@@ -336,29 +282,24 @@ class SuperLogging {
return _preferences.getString(keyAnonymousUserID)!;
}
- /// The log file currently in use.
static File? logFile;
- /// Whether file logging is currently enabled or not.
static bool fileIsEnabled = false;
static Future<void> setupLogDir() async {
var dirPath = config.logDirPath;
- // choose [logDir]
if (dirPath == null || dirPath.isEmpty) {
final root = await getExternalStorageDirectory();
dirPath = join(root!.path, 'logs');
}
- // create [logDir]
final dir = Directory(dirPath);
await dir.create(recursive: true);
final files = <File>[];
final dates = <File, DateTime>{};
- // collect all log files with valid names
await for (final file in dir.list()) {
try {
final date = config.dateFmt!.parse(basename(file.path));
@@ -368,9 +309,7 @@ class SuperLogging {
}
final nowTime = DateTime.now();
- // delete old log files, if [maxLogFiles] is exceeded.
if (files.length > config.maxLogFiles) {
- // sort files based on ascending order of date (older first)
files.sort(
(a, b) => (dates[a] ?? nowTime).compareTo((dates[b] ?? nowTime)),
);
@@ -391,9 +330,6 @@ class SuperLogging {
);
}
- /// Current app version, obtained from package_info plugin.
- ///
- /// See: [getAppVersion]
static String? appVersion;
static Future<String> getAppVersion() async {
diff --git a/mobile/packages/logging/lib/tunneled_transport.dart b/mobile/packages/logging/lib/tunneled_transport.dart
index 32732a69d0..8d9a6f09cf 100644
--- a/mobile/packages/logging/lib/tunneled_transport.dart
+++ b/mobile/packages/logging/lib/tunneled_transport.dart
@@ -3,7 +3,6 @@ import 'dart:convert';
import 'package:http/http.dart';
import 'package:sentry/sentry.dart';
-/// A transport is in charge of sending the event to the Sentry server.
class TunneledTransport implements Transport {
final Uri _tunnel;
final SentryOptions _options;
@@ -40,8 +39,7 @@ class TunneledTransport implements Transport {
.then(Response.fromStream);
if (response.statusCode != 200) {
- // body guard to not log the error as it has performance impact to allocate
- // the body String.
+ // Reading response.body allocates it; only do so in debug mode.
if (_options.debug) {
_options.log(
SentryLevel.error,
@@ -129,8 +127,6 @@ class _CredentialBuilder {
Map<String, String> _buildHeaders(bool isWeb, String sdkIdentifier) {
final headers = {'Content-Type': 'application/x-sentry-envelope'};
- // NOTE(lejard_h) overriding user agent on VM and Flutter not sure why
- // for web it use browser user agent
if (!isWeb) {
headers['User-Agent'] = sdkIdentifier;
}
diff --git a/mobile/packages/native_video_editor/lib/native_video_editor.dart b/mobile/packages/native_video_editor/lib/native_video_editor.dart
index 02eeb3c34d..8431eacdd2 100644
--- a/mobile/packages/native_video_editor/lib/native_video_editor.dart
+++ b/mobile/packages/native_video_editor/lib/native_video_editor.dart
@@ -101,7 +101,7 @@ class NativeVideoInfo {
final int displayWidth;
final int displayHeight;
- /// Clockwise quarter-turn rotation required to display encoded pixels.
+ // Clockwise quarter-turn rotation required to display encoded pixels.
final int rotationDegrees;
final int? bitrate;
final double? frameRate;
@@ -259,8 +259,6 @@ class NativeVideoEditor {
'native_video_editor/progress',
);
- /// Combined operation: trim, rotate, and crop in a single pass
- /// More efficient when multiple operations are needed
static Future<VideoEditResult> processVideo({
required String inputPath,
required String outputPath,
@@ -431,7 +429,6 @@ class NativeVideoEditor {
return NativeVideoInfo.fromMap(result);
}
- /// Cancel any ongoing video processing
static Future<void> cancelProcessing() async {
await _invokeVoid('cancelProcessing', null, operation: 'cancel processing');
}
diff --git a/mobile/packages/network/lib/network.dart b/mobile/packages/network/lib/network.dart
index fd7ca53dbb..76a2b8ece5 100644
--- a/mobile/packages/network/lib/network.dart
+++ b/mobile/packages/network/lib/network.dart
@@ -26,18 +26,13 @@ class Network {
final version = packageInfo.version;
String packageName = packageInfo.packageName;
- // Fix package name for auth app on Windows/Linux only
- // On Linux, packageInfo returns "ente_auth" from pubspec.yaml (via version.json)
- // On Windows, packageInfo returns "Ente Auth" from Runner.rc InternalName field
- // We need to normalize both to "io.ente.auth" to match Android/iOS/macOS
+ // Desktop Auth reports names that must be normalized for production.
if (Platform.isWindows || Platform.isLinux) {
if (packageName == 'ente_auth' || packageName == 'Ente Auth') {
packageName = 'io.ente.auth';
}
}
- // Validate package name for production endpoint
- // This ensures we catch any edge cases where the package name is still incorrect
if (configuration.isEnteProduction()) {
if (!packageName.startsWith('io.ente.')) {
throw Exception(
diff --git a/mobile/packages/qr/lib/qr_code_dialog.dart b/mobile/packages/qr/lib/qr_code_dialog.dart
index 60d57ff4b2..0baa647987 100644
--- a/mobile/packages/qr/lib/qr_code_dialog.dart
+++ b/mobile/packages/qr/lib/qr_code_dialog.dart
@@ -202,7 +202,7 @@ class _QrCodeDialogState extends State<QrCodeDialog> {
widget.maxQrSize,
);
final double qrCodeSize = max(qrSize - 100, widget.minQrSize);
- // Round to nearest even number for crisp rendering
+ // Even dimensions render the QR code sharply.
final double qrCodeSizeEven = (qrCodeSize / 2).round() * 2.0;
final dialogBackgroundColor =
@@ -218,7 +218,6 @@ class _QrCodeDialogState extends State<QrCodeDialog> {
final shareButtonColor =
widget.shareButtonBackgroundColor ?? widget.accentColor;
- // Use theme text styles with copyWith for customization
final titleStyle =
widget.titleTextStyle ??
textTheme.titleMedium?.copyWith(
diff --git a/mobile/packages/scoped_dir_access/lib/scoped_dir_access.dart b/mobile/packages/scoped_dir_access/lib/scoped_dir_access.dart
index 416dd049b7..ec41825e88 100644
--- a/mobile/packages/scoped_dir_access/lib/scoped_dir_access.dart
+++ b/mobile/packages/scoped_dir_access/lib/scoped_dir_access.dart
@@ -1,8 +1,3 @@
-/// Cross-platform directory utilities with persistent access support.
-///
-/// - iOS: Uses security-scoped bookmarks for persistent directory access
-/// - Android: Uses Storage Access Framework (SAF) via saf_util/saf_stream
-/// - Other platforms: Uses standard file system access via file_picker
library;
import 'dart:io';
@@ -16,25 +11,19 @@ import 'package:saf_util/saf_util.dart';
final _logger = Logger('DirUtils');
-/// Represents a picked directory with platform-specific access credentials.
class PickedDirectory {
const PickedDirectory({required this.path, this.bookmark, this.treeUri});
- /// The display path of the directory.
final String path;
- /// iOS security-scoped bookmark (base64 encoded). Null on other platforms.
final String? bookmark;
- /// Android SAF tree URI. Null on other platforms.
final String? treeUri;
- /// Returns true if this directory has a security-scoped bookmark (iOS or macOS).
bool get hasBookmark => bookmark != null;
bool get isAndroid => treeUri != null;
}
-/// Result from starting security-scoped access on iOS.
class AccessResult {
const AccessResult({
required this.success,
@@ -47,7 +36,6 @@ class AccessResult {
final bool isStale;
}
-/// Information about a file in a directory.
class FileInfo {
const FileInfo({
required this.name,
@@ -62,31 +50,15 @@ class FileInfo {
final bool isDirectory;
final DateTime lastModified;
- /// Android SAF URI (for deletion). Null on other platforms.
final String? uri;
}
-/// Cross-platform directory utilities.
class DirUtils {
DirUtils._();
static final DirUtils instance = DirUtils._();
static const _channel = MethodChannel('io.ente.scoped_dir_access');
- // ============================================================
- // Directory Picker
- // ============================================================
-
- /// Pick a directory with persistent access.
- ///
- /// On iOS, this opens the native document picker and creates a security-scoped
- /// bookmark for persistent access across app launches.
- ///
- /// On Android, this opens SAF directory picker with persistent permissions.
- ///
- /// On other platforms, this uses file_picker.
- ///
- /// Returns null if the user cancels.
Future<PickedDirectory?> pickDirectory() async {
if (Platform.isIOS) {
return _pickDirectoryIos();
@@ -139,12 +111,10 @@ class DirUtils {
Future<PickedDirectory?> _pickDirectoryMacOS() async {
try {
- // Use file_picker to pick the directory
final path = await FilePicker.getDirectoryPath();
if (path == null) return null;
- // Create a security-scoped bookmark from the picked path
- // This must be done while we still have access (same session as picker)
+ // Create the bookmark while picker access is still active.
final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
'createBookmarkFromPath',
{'path': path},
@@ -183,14 +153,7 @@ class DirUtils {
}
}
- // ============================================================
- // Security-Scoped Access (iOS/macOS)
- // ============================================================
-
- /// Start accessing a security-scoped resource (iOS/macOS).
- ///
- /// You MUST call [stopAccess] when done to balance this call.
- /// On platforms without bookmark support, this is a no-op that returns success.
+ // Each successful call must be balanced with stopAccess.
Future<AccessResult?> startAccess(PickedDirectory dir) async {
if (!Platform.isIOS && !Platform.isMacOS) {
return AccessResult(success: true, path: dir.path, isStale: false);
@@ -221,9 +184,6 @@ class DirUtils {
}
}
- /// Stop accessing a security-scoped resource (iOS/macOS).
- ///
- /// On platforms without bookmark support, this is a no-op.
Future<bool> stopAccess(PickedDirectory dir) async {
if (!Platform.isIOS && !Platform.isMacOS) return true;
@@ -245,10 +205,6 @@ class DirUtils {
}
}
- /// Execute a function with security-scoped access.
- ///
- /// Automatically calls startAccess before and stopAccess after.
- /// On platforms without bookmark support, just executes the function directly.
Future<T?> withAccess<T>(
PickedDirectory dir,
Future<T> Function(String path) action,
@@ -266,16 +222,6 @@ class DirUtils {
}
}
- // ============================================================
- // File Operations
- // ============================================================
-
- /// Write a file to the directory.
- ///
- /// [dir] - The picked directory
- /// [fileName] - Name of the file to create
- /// [content] - File content as bytes
- /// [subPath] - Optional subdirectory path within the directory
Future<bool> writeFile(
PickedDirectory dir,
String fileName,
@@ -352,7 +298,6 @@ class DirUtils {
}
}
- /// List files in a directory.
Future<List<FileInfo>> listFiles(
PickedDirectory dir, {
String? subPath,
@@ -444,10 +389,6 @@ class DirUtils {
}
}
- /// Delete a file.
- ///
- /// For Android SAF, pass the file's URI as [filePathOrUri].
- /// For other platforms, pass the file path.
Future<bool> deleteFile(PickedDirectory dir, FileInfo file) async {
if (Platform.isAndroid && file.uri != null) {
return _deleteFileAndroid(file.uri!, file.isDirectory);
diff --git a/mobile/packages/screen_cover/lib/ente_screen_cover.dart b/mobile/packages/screen_cover/lib/ente_screen_cover.dart
index 140246dc39..dda3dd1cba 100644
--- a/mobile/packages/screen_cover/lib/ente_screen_cover.dart
+++ b/mobile/packages/screen_cover/lib/ente_screen_cover.dart
@@ -1,6 +1,5 @@
import "package:flutter/services.dart";
-/// Hides app content from screenshots/recents (Android) and the app switcher (iOS).
class EnteScreenCover {
EnteScreenCover._();
diff --git a/mobile/packages/sharing/lib/collection_sharing_service.dart b/mobile/packages/sharing/lib/collection_sharing_service.dart
index 3de0195387..4732d81a8d 100644
--- a/mobile/packages/sharing/lib/collection_sharing_service.dart
+++ b/mobile/packages/sharing/lib/collection_sharing_service.dart
@@ -17,7 +17,6 @@ class CollectionSharingService {
CollectionSharingService._privateConstructor();
- /// Share a collection with a user
Future<List<User>> share(
int collectionID,
String email,
@@ -48,7 +47,6 @@ class CollectionSharingService {
}
}
- /// Unshare a collection with a user
Future<List<User>> unshare(int collectionID, String email) async {
try {
final response = await _enteDio.post(
@@ -66,7 +64,6 @@ class CollectionSharingService {
}
}
- /// Create a public sharing URL for a collection
Future<Response> createShareUrl(int collectionID, bool enableCollect) async {
try {
final response = await _enteDio.post(
@@ -89,7 +86,6 @@ class CollectionSharingService {
}
}
- /// Disable public sharing URL for a collection
Future<void> disableShareUrl(int collectionID) async {
try {
await _enteDio.delete(
@@ -127,7 +123,6 @@ class CollectionSharingService {
}
}
- /// Leave a shared collection
Future<void> leaveCollection(int collectionID) async {
try {
await _enteDio.post("/collections/leave/$collectionID");
diff --git a/mobile/packages/sharing/lib/components/invite_dialog.dart b/mobile/packages/sharing/lib/components/invite_dialog.dart
index 4191d21681..910ef71493 100644
--- a/mobile/packages/sharing/lib/components/invite_dialog.dart
+++ b/mobile/packages/sharing/lib/components/invite_dialog.dart
@@ -5,7 +5,6 @@ import "package:ente_ui/theme/ente_theme.dart";
import "package:ente_utils/share_utils.dart";
import "package:flutter/material.dart";
-/// Shows the invite sheet when a user doesn't have an Ente account
Future<void> showInviteSheet(BuildContext context, {required String email}) {
return showBaseBottomSheet<void>(
context,
diff --git a/mobile/packages/sharing/lib/verify_identity_dialog.dart b/mobile/packages/sharing/lib/verify_identity_dialog.dart
index f01241266c..b3089bb6fc 100644
--- a/mobile/packages/sharing/lib/verify_identity_dialog.dart
+++ b/mobile/packages/sharing/lib/verify_identity_dialog.dart
@@ -30,11 +30,8 @@ Future<void> showVerifyIdentitySheet(
}
class VerifyIdentitySheet extends StatefulWidget {
- // email id of the user who's verification ID is being displayed for
- // verification
final String email;
- // self is true when the user is viewing their own verification ID
final bool self;
final BaseConfiguration config;
@@ -129,7 +126,6 @@ class _VerifyIdentitySheetState extends State<VerifyIdentitySheet> {
widget.email,
);
if (userPublicKey == null) {
- // user not found
return "";
}
return userPublicKey;
diff --git a/mobile/packages/utils/lib/platform_util.dart b/mobile/packages/utils/lib/platform_util.dart
index f6875d7ed6..be0b1eb389 100644
--- a/mobile/packages/utils/lib/platform_util.dart
+++ b/mobile/packages/utils/lib/platform_util.dart
@@ -17,8 +17,6 @@ class PlatformUtil {
String title,
String url,
) async {
- // For desktop, always open in external browser
- // For mobile, open in external browser (apps can override this if they have web view)
await launchUrlString(url);
}
diff --git a/mobile/packages/utils/lib/share_utils.dart b/mobile/packages/utils/lib/share_utils.dart
index 85be9957ef..93849e639a 100644
--- a/mobile/packages/utils/lib/share_utils.dart
+++ b/mobile/packages/utils/lib/share_utils.dart
@@ -118,8 +118,6 @@ Rect _sharePosOrigin(BuildContext? context, GlobalKey? key) {
return rect;
}
-/// Returns the rect of button if context and key are not null
-/// If key is null, returned rect will be at the center of the screen
Rect shareButtonRect(BuildContext context, GlobalKey? shareButtonKey) {
Size size = MediaQuery.sizeOf(context);
final RenderObject? renderObject = shareButtonKey?.currentContext