diff --git a/.github/workflows/release_github.yml b/.github/workflows/release_github.yml deleted file mode 100644 index ea0a9a8f..00000000 --- a/.github/workflows/release_github.yml +++ /dev/null @@ -1,68 +0,0 @@ -name: Publish on Github - -on: - workflow_dispatch: {} - push: - branches: - - main - paths: - - pubspec.yaml - -jobs: - build_and_publish: - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Clone repository - uses: actions/checkout@v4 - - - name: Set up Flutter - uses: subosito/flutter-action@v2 - with: - channel: stable - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - - - name: Install requirements - run: sudo apt-get install protobuf-compiler - - - name: Cloning sub-repos - run: git submodule update --init --recursive - - # - name: Check flutter code - # run: | - # flutter pub get - # flutter analyze - # flutter test - - - name: Check flutter code - run: flutter pub get - - - name: Create key.properties file - run: | - echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> ./android/key.properties - echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> ./android/key.properties - echo "keyAlias=github-releases-signature" >> ./android/key.properties - echo "storeFile=./keystore.jks" >> ./android/key.properties - - - name: Create keystore file - env: - KEYSTORE_FILE: ${{ secrets.KEYSTORE_FILE }} - run: echo $KEYSTORE_FILE | base64 --decode > ./android/app/keystore.jks - - - name: Build Android APK - run: flutter build apk --release --split-per-abi - - - name: Extract pubspec version - run: | - echo "PUBSPEC_VERSION=$(grep -oP 'version:\s*\K[^+]+(?=\+)' pubspec.yaml)" >> $GITHUB_ENV - - - name: Upload Release Binaries (stable) - uses: ncipollo/release-action@v1.18.0 - with: - token: ${{ secrets.GITHUB_TOKEN }} - tag: v${{ env.PUBSPEC_VERSION }} - allowUpdates: true - artifacts: build/app/outputs/flutter-apk/*.apk \ No newline at end of file diff --git a/.gitignore b/.gitignore index f87ae92b..f6e6d121 100644 --- a/.gitignore +++ b/.gitignore @@ -54,4 +54,5 @@ app.*.map.json android/.kotlin/ devtools_options.yaml rust/target -rust_dependencies/target \ No newline at end of file +rust_dependencies/target +fastlane/repo/status/running.json diff --git a/CHANGELOG.md b/CHANGELOG.md index de9937f7..bc2ef533 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,17 @@ # Changelog +## 0.2.26 + +- New: Import images from the gallery +- Improved: Media files are now stored in the dedicated "twonly" album +- Improved: UI components adapt to native styling (iOS/Android) +- Fix: Migration issue that resulted in a corrupted backup mechanism +- Fix: Database issues causing messages to be lost or the database to be corrupted +- Fix: Permission view did not disappear after they were granted + ## 0.2.23 -- Improves: Smaller UI changes +- Improved: Smaller UI changes - Fix: Some messages were not marked as opened. ## 0.2.20 diff --git a/android/.gitignore b/android/.gitignore index 55afd919..8da9e3f0 100644 --- a/android/.gitignore +++ b/android/.gitignore @@ -9,5 +9,7 @@ GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. # See https://flutter.dev/to/reference-keystore key.properties +key.github.properties +key.properties.backup **/*.keystore **/*.jks diff --git a/android/app/src/main/kotlin/eu/twonly/MainActivity.kt b/android/app/src/main/kotlin/eu/twonly/MainActivity.kt index 6af76265..8b680aad 100644 --- a/android/app/src/main/kotlin/eu/twonly/MainActivity.kt +++ b/android/app/src/main/kotlin/eu/twonly/MainActivity.kt @@ -10,11 +10,32 @@ import android.content.Context import io.crates.keyring.Keyring import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import android.os.Bundle +import android.net.Uri +import java.io.InputStream +import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.PickVisualMediaRequest +import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterFragmentActivity() { + private val CHANNEL = "eu.twonly/photo_picker" + private var pendingResult: MethodChannel.Result? = null + + private lateinit var pickMultipleMedia: ActivityResultLauncher override fun onCreate(savedInstanceState: Bundle?) { installSplashScreen() + + pickMultipleMedia = registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { uris -> + if (uris.isNotEmpty()) { + val uriStrings = uris.map { it.toString() } + pendingResult?.success(uriStrings) + } else { + pendingResult?.success(emptyList()) + } + pendingResult = null + } + super.onCreate(savedInstanceState) } @@ -35,7 +56,36 @@ class MainActivity : FlutterFragmentActivity() { Keyring.initializeNdkContext(applicationContext) - MediaStoreChannel.configure(flutterEngine, applicationContext) VideoCompressionChannel.configure(flutterEngine, applicationContext) + + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> + when (call.method) { + "pickImages" -> { + pendingResult = result + pickMultipleMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) + } + "getUriBytes" -> { + val uriString = call.argument("uri") + if (uriString != null) { + try { + val uri = Uri.parse(uriString) + val inputStream: InputStream? = contentResolver.openInputStream(uri) + if (inputStream != null) { + val bytes = inputStream.readBytes() + inputStream.close() + result.success(bytes) + } else { + result.error("UNAVAILABLE", "Could not open InputStream", null) + } + } catch (e: Exception) { + result.error("ERROR", e.message, null) + } + } else { + result.error("INVALID_ARGUMENT", "URI string is null", null) + } + } + else -> result.notImplemented() + } + } } } diff --git a/android/app/src/main/kotlin/eu/twonly/MediaStoreChannel.kt b/android/app/src/main/kotlin/eu/twonly/MediaStoreChannel.kt deleted file mode 100644 index e616e27c..00000000 --- a/android/app/src/main/kotlin/eu/twonly/MediaStoreChannel.kt +++ /dev/null @@ -1,92 +0,0 @@ -package eu.twonly - -import android.content.ContentValues -import android.content.Context -import android.os.Build -import android.os.Environment -import android.provider.MediaStore -import io.flutter.embedding.engine.FlutterEngine -import io.flutter.plugin.common.MethodChannel -import java.io.File -import java.io.FileInputStream -import java.io.InputStream -import java.io.OutputStream - -object MediaStoreChannel { - private const val CHANNEL = "eu.twonly/mediaStore" - - fun configure(flutterEngine: FlutterEngine, context: Context) { - val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL) - - channel.setMethodCallHandler { call, result -> - try { - if (call.method == "safeFileToDownload") { - val arguments = call.arguments>() as Map - val sourceFile = arguments["sourceFile"] - if (sourceFile == null) { - result.success(false) - } else { - val inputStream = FileInputStream(File(sourceFile)) - val outputName = File(sourceFile).name.takeIf { it.isNotEmpty() } ?: "memories.zip" - - val savedUri = saveZipToDownloads(context, outputName, inputStream) - if (savedUri != null) { - result.success(savedUri.toString()) - } else { - result.error("SAVE_FAILED", "Could not save ZIP", null) - } - } - } else { - result.notImplemented() - } - } catch (e: Exception) { - result.error("EXCEPTION", e.message, null) - } - } - } - - private fun saveZipToDownloads( - context: Context, - fileName: String = "archive.zip", - sourceStream: InputStream - ): android.net.Uri? { - val resolver = context.contentResolver - - val contentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) - put(MediaStore.MediaColumns.MIME_TYPE, "application/zip") - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) - put(MediaStore.MediaColumns.IS_PENDING, 1) - } - } - - val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) - } else { - MediaStore.Files.getContentUri("external") - } - - val uri = resolver.insert(collection, contentValues) ?: return null - - try { - resolver.openOutputStream(uri).use { out: OutputStream? -> - requireNotNull(out) { "Unable to open output stream" } - sourceStream.use { input -> - input.copyTo(out) - } - out.flush() - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - val done = ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) } - resolver.update(uri, done, null, null) - } - - return uri - } catch (e: Exception) { - try { resolver.delete(uri, null, null) } catch (_: Exception) {} - return null - } - } -} diff --git a/android/key.github.properties.example b/android/key.github.properties.example new file mode 100644 index 00000000..934506b5 --- /dev/null +++ b/android/key.github.properties.example @@ -0,0 +1,8 @@ +# Example signing credentials configuration for GitHub Releases. +# Copy this file to 'key.github.properties' and fill in your actual credentials. +# Do not commit the actual 'key.github.properties' file to version control. + +storePassword=YOUR_GITHUB_RELEASE_STORE_PASSWORD +keyPassword=YOUR_GITHUB_RELEASE_KEY_PASSWORD +keyAlias=github-releases-signature +storeFile=/absolute/path/to/your/github-release-keystore.jks diff --git a/dependencies b/dependencies index e0c6a961..72d9bd63 160000 --- a/dependencies +++ b/dependencies @@ -1 +1 @@ -Subproject commit e0c6a9617a20a8d6bc1ad4c6b9c2e229feb5f37a +Subproject commit 72d9bd6320bca1f1d29c6e61c3821fed326c0abe diff --git a/fastlane/Fastfile b/fastlane/Fastfile index 966178d2..e8ca079f 100644 --- a/fastlane/Fastfile +++ b/fastlane/Fastfile @@ -12,4 +12,133 @@ platform :android do skip_upload_screenshots: true ) end + + desc "Build the application locally and upload it as a new GitHub release" + lane :release_github do + # Read pubspec.yaml to get the version + pubspec_path = File.expand_path("../pubspec.yaml", __dir__) + unless File.exist?(pubspec_path) + UI.user_error!("Could not find pubspec.yaml at #{pubspec_path}") + end + + pubspec_content = File.read(pubspec_path) + version_match = pubspec_content.match(/^version:\s*([^+]+)/) + unless version_match + UI.user_error!("Could not extract version from pubspec.yaml") + end + + version = version_match[1].strip + tag_name = "v#{version}" + UI.message("Extracted version: #{version} (tag: #{tag_name})") + + # Load release notes from CHANGELOG.md + changelog_path = File.expand_path("../CHANGELOG.md", __dir__) + release_notes = "Automated local release via Fastlane" + if File.exist?(changelog_path) + changelog_content = File.read(changelog_path) + escaped_version = Regexp.escape(version) + pattern = /##\s*\[?#{escaped_version}\]?(.*?)(?=##\s*|\z)/m + match = changelog_content.match(pattern) + if match + release_notes = match[1].strip + UI.message("Loaded release notes from CHANGELOG.md:\n#{release_notes}") + else + UI.important("Could not find release notes for version #{version} in CHANGELOG.md. Using default description.") + end + else + UI.important("CHANGELOG.md not found at #{changelog_path}. Using default description.") + end + + # Handle key.properties swapping if key.github.properties exists + key_properties_path = File.expand_path("../android/key.properties", __dir__) + github_properties_path = File.expand_path("../android/key.github.properties", __dir__) + backup_properties_path = File.expand_path("../android/key.properties.backup", __dir__) + + swapped_properties = false + if File.exist?(github_properties_path) + UI.message("Found key.github.properties. Swapping in for the build...") + if File.exist?(key_properties_path) + FileUtils.cp(key_properties_path, backup_properties_path) + end + FileUtils.cp(github_properties_path, key_properties_path) + swapped_properties = true + else + UI.message("No key.github.properties found. Building with default key.properties...") + end + + begin + # Build the Android application + UI.message("Building Android APK...") + Dir.chdir(File.expand_path("..", __dir__)) do + sh("flutter build apk --release --split-per-abi") + end + ensure + # Restore original key.properties if swapped + if swapped_properties + UI.message("Restoring original key.properties...") + if File.exist?(backup_properties_path) + FileUtils.cp(backup_properties_path, key_properties_path) + FileUtils.rm(backup_properties_path) + else + FileUtils.rm_f(key_properties_path) + end + end + end + + # Find built APKs + apk_glob = File.expand_path("../build/app/outputs/flutter-apk/*-release.apk", __dir__) + apks = Dir.glob(apk_glob) + + if apks.empty? + UI.user_error!("No release APKs found matching #{apk_glob}") + end + + UI.message("Found APKs to upload: #{apks.join(', ')}") + + # Retrieve GitHub Token (fall back to gh auth token) + github_token = ENV["GITHUB_TOKEN"] + if github_token.nil? || github_token.empty? + UI.message("GITHUB_TOKEN env variable not set. Retrieving token via GitHub CLI (gh auth token)...") + begin + github_token = sh("gh auth token").strip + rescue => e + UI.user_error!("Failed to retrieve token from gh CLI. Make sure gh is installed and authenticated, or GITHUB_TOKEN environment variable is set. Error: #{e}") + end + end + + UI.message("Creating GitHub Release #{tag_name}...") + set_github_release( + repository_name: "twonlyapp/twonly-app", + api_token: github_token, + tag_name: tag_name, + name: "Release #{tag_name}", + description: release_notes, + upload_assets: apks + ) + UI.success("Successfully uploaded release #{tag_name} to GitHub!") + + # F-Droid deployment + fdroid_repo_dir = "/Users/tobi/Documents/drive/twonly/F-Droid/repo" + UI.message("Starting F-Droid deployment...") + FileUtils.mkdir_p(fdroid_repo_dir) + + apks.each do |apk_path| + basename = File.basename(apk_path) + new_name = "eu.twonly_v#{version}-#{basename}" + dest_path = File.join(fdroid_repo_dir, new_name) + UI.message("Copying APK to F-Droid repo: #{dest_path}") + FileUtils.cp(apk_path, dest_path) + end + + fdroid_dir = "/Users/tobi/Documents/drive/twonly/F-Droid" + update_script = File.join(fdroid_dir, "update.sh") + if File.exist?(update_script) + UI.message("Executing F-Droid update script...") + Dir.chdir(fdroid_dir) do + sh("chmod +x ./update.sh && ./update.sh") + end + else + UI.important("F-Droid update script not found at #{update_script}") + end + end end diff --git a/ios/Podfile.lock b/ios/Podfile.lock index eeb9bd6f..d0110fad 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -280,6 +280,9 @@ PODS: - Flutter - permission_handler_apple (9.3.0): - Flutter + - photo_manager (3.9.0): + - Flutter + - FlutterMacOS - pro_video_editor (0.0.1): - Flutter - PromisesObjC (2.4.0) @@ -355,6 +358,7 @@ DEPENDENCIES: - local_auth_darwin (from `.symlinks/plugins/local_auth_darwin/darwin`) - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) - permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`) + - photo_manager (from `.symlinks/plugins/photo_manager/darwin`) - pro_video_editor (from `.symlinks/plugins/pro_video_editor/ios`) - restart_app (from `.symlinks/plugins/restart_app/ios`) - rust_lib_twonly (from `.symlinks/plugins/rust_lib_twonly/ios`) @@ -460,6 +464,8 @@ EXTERNAL SOURCES: :path: ".symlinks/plugins/package_info_plus/ios" permission_handler_apple: :path: ".symlinks/plugins/permission_handler_apple/ios" + photo_manager: + :path: ".symlinks/plugins/photo_manager/darwin" pro_video_editor: :path: ".symlinks/plugins/pro_video_editor/ios" restart_app: @@ -536,6 +542,7 @@ SPEC CHECKSUMS: nanopb: fad817b59e0457d11a5dfbde799381cd727c1275 package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499 permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d + photo_manager: 25fd77df14f4f0ba5ef99e2c61814dde77e2bceb pro_video_editor: 44ef9a6d48dbd757ed428cf35396dd05f35c7830 PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 restart_app: 0714144901e260eae68f7afc2fc4aacc1a323ad2 diff --git a/lib/src/constants/routes.keys.dart b/lib/src/constants/routes.keys.dart index 4334b37c..86804303 100644 --- a/lib/src/constants/routes.keys.dart +++ b/lib/src/constants/routes.keys.dart @@ -41,6 +41,8 @@ class Routes { static const String settingsStorage = '/settings/storage_data'; static const String settingsStorageManage = '/settings/storage_data/manage'; static const String settingsStorageImport = '/settings/storage_data/import'; + static const String settingsStorageImportGallery = + '/settings/storage_data/import_gallery'; static const String settingsStorageExport = '/settings/storage_data/export'; static const String settingsHelp = '/settings/help'; static const String settingsHelpFaq = '/settings/help/faq'; diff --git a/lib/src/database/daos/mediafiles.dao.dart b/lib/src/database/daos/mediafiles.dao.dart index d22d3a80..0778a72d 100644 --- a/lib/src/database/daos/mediafiles.dao.dart +++ b/lib/src/database/daos/mediafiles.dao.dart @@ -185,6 +185,12 @@ class MediaFilesDao extends DatabaseAccessor return rows.map((row) => row.readTable(db.messages).messageId).toList(); } + Future> getMediaByHash(Uint8List hash) async { + final query = select(db.mediaFiles) + ..where((t) => t.storedFileHash.equals(hash)); + return query.get(); + } + Future> getStorageStats() async { final rows = await select(mediaFiles).get(); final stats = {}; diff --git a/lib/src/database/daos/messages.dao.dart b/lib/src/database/daos/messages.dao.dart index 45e09d0f..8b5348be 100644 --- a/lib/src/database/daos/messages.dao.dart +++ b/lib/src/database/daos/messages.dao.dart @@ -153,18 +153,25 @@ class MessagesDao extends DatabaseAccessor with _$MessagesDaoMixin { ); final groupIds = entry.value; - await (delete(messages)..where( - (m) => - m.groupId.isIn(groupIds) & - ((m.mediaStored.equals(true) & - m.isDeletedFromSender.equals(true)) | - m.mediaStored.equals(false)) & - // Only remove the message when ALL members have seen it. Otherwise the receipt will also be deleted which could cause issues in case a member opens the image later.. - (m.openedByAll.isSmallerThanValue(deletionTime) | - (m.isDeletedFromSender.equals(true) & - m.createdAt.isSmallerThanValue(deletionTime))), - )) - .go(); + final deletedCount = + await (delete(messages)..where( + (m) => + m.groupId.isIn(groupIds) & + ((m.mediaStored.equals(true) & + m.isDeletedFromSender.equals(true)) | + m.mediaStored.equals(false)) & + // Only remove the message when ALL members have seen it. Otherwise the receipt will also be deleted which could cause issues in case a member opens the image later.. + (m.openedByAll.isSmallerThanValue(deletionTime) | + (m.isDeletedFromSender.equals(true) & + m.createdAt.isSmallerThanValue(deletionTime))), + )) + .go(); + + if (deletedCount > 0) { + Log.info( + 'Deleted $deletedCount messages for groups $groupIds due to retention policy.', + ); + } } } @@ -266,30 +273,48 @@ class MessagesDao extends DatabaseAccessor with _$MessagesDaoMixin { actionTimestamp = msg.createdAt; } - await into(messageActions).insertOnConflictUpdate( - MessageActionsCompanion( - messageId: Value(messageId), - contactId: contactId, - type: const Value(MessageActionType.openedAt), - actionAt: Value(actionTimestamp), - ), - ); + final ts = actionTimestamp; + await transaction(() async { + await into(messageActions).insertOnConflictUpdate( + MessageActionsCompanion( + messageId: Value(messageId), + contactId: contactId, + type: const Value(MessageActionType.openedAt), + actionAt: Value(ts), + ), + ); + + final isOpenedByAll = await haveAllMembers( + messageId, + MessageActionType.openedAt, + ); + await (update( + messages, + )..where((tbl) => tbl.messageId.equals(messageId))).write( + MessagesCompanion( + openedAt: Value(ts), + openedByAll: Value(isOpenedByAll ? ts : null), + ), + ); + }); + + // Read-back verification: confirm the write was persisted. + final verified = await getMessageById(messageId).getSingleOrNull(); + if (verified != null && verified.openedAt == null) { + Log.warn( + 'handleMessagesOpened read-back failed for $messageId, retrying', + ); + await (update( + messages, + )..where((tbl) => tbl.messageId.equals(messageId))).write( + MessagesCompanion( + openedAt: Value(actionTimestamp), + ), + ); + } - final isOpenedByAll = await haveAllMembers( - messageId, - MessageActionType.openedAt, - ); - final rowsUpdated = - await (update( - messages, - )..where((tbl) => tbl.messageId.equals(messageId))).write( - MessagesCompanion( - openedAt: Value(actionTimestamp), - openedByAll: Value(isOpenedByAll ? actionTimestamp : null), - ), - ); Log.info( - 'handleMessagesOpened updated $rowsUpdated rows for message $messageId', + 'handleMessagesOpened completed for message $messageId', ); } catch (e) { Log.error('handleMessagesOpened failed for $messageId: $e'); @@ -302,18 +327,20 @@ class MessagesDao extends DatabaseAccessor with _$MessagesDaoMixin { String messageId, DateTime timestamp, ) async { - await into(messageActions).insertOnConflictUpdate( - MessageActionsCompanion( - messageId: Value(messageId), - contactId: Value(contactId), - type: const Value(MessageActionType.ackByServerAt), - actionAt: Value(timestamp), - ), - ); - await twonlyDB.messagesDao.updateMessageId( - messageId, - MessagesCompanion(ackByServer: Value(timestamp)), - ); + await transaction(() async { + await into(messageActions).insertOnConflictUpdate( + MessageActionsCompanion( + messageId: Value(messageId), + contactId: Value(contactId), + type: const Value(MessageActionType.ackByServerAt), + actionAt: Value(timestamp), + ), + ); + await twonlyDB.messagesDao.updateMessageId( + messageId, + MessagesCompanion(ackByServer: Value(timestamp)), + ); + }); } Future haveAllMembers( @@ -347,18 +374,20 @@ class MessagesDao extends DatabaseAccessor with _$MessagesDaoMixin { String messageId, MessagesCompanion updatedValues, ) async { - await (update( + final count = await (update( messages, )..where((c) => c.messageId.equals(messageId))).write(updatedValues); + Log.info('Updated $count message(s) with messageId $messageId'); } Future updateMessagesByMediaId( String mediaId, MessagesCompanion updatedValues, - ) { - return (update( + ) async { + final count = await (update( messages, )..where((c) => c.mediaId.equals(mediaId))).write(updatedValues); + Log.info('Updated $count message(s) with mediaId $mediaId'); } Future insertMessage(MessagesCompanion message) async { diff --git a/lib/src/database/drift_logging_interceptor.dart b/lib/src/database/drift_logging_interceptor.dart new file mode 100644 index 00000000..63ff94eb --- /dev/null +++ b/lib/src/database/drift_logging_interceptor.dart @@ -0,0 +1,164 @@ +import 'dart:async'; +import 'package:drift/drift.dart'; +import 'package:twonly/locator.dart'; +import 'package:twonly/src/utils/log.dart'; + +class DriftLoggingInterceptor extends QueryInterceptor { + bool get _isEnabled { + try { + if (!userService.isUserCreated) return false; + return userService.currentUser.enableDatabaseLogging; + } catch (_) { + return false; + } + } + + List _findUuids(dynamic value) { + if (value == null) return const []; + final uuids = []; + final uuidRegex = RegExp( + '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}', + ); + if (value is String) { + for (final match in uuidRegex.allMatches(value)) { + uuids.add(match.group(0)!); + } + } else if (value is Iterable) { + for (final element in value) { + uuids.addAll(_findUuids(element)); + } + } else if (value is Map) { + for (final element in value.values) { + uuids.addAll(_findUuids(element)); + } + } else { + final str = value.toString(); + for (final match in uuidRegex.allMatches(str)) { + uuids.add(match.group(0)!); + } + } + return uuids.toSet().toList(); + } + + Future _run( + String operation, + String statement, + List args, + Future Function() query, + ) async { + if (!_isEnabled) { + return query(); + } + final stopwatch = Stopwatch()..start(); + try { + final result = await query(); + final elapsed = stopwatch.elapsedMilliseconds; + final uuids = _findUuids(args); + if (uuids.isNotEmpty) { + Log.info( + '[DriftDB] $operation succeeded in ${elapsed}ms: "$statement" | UUIDs: $uuids', + ); + } else { + Log.info( + '[DriftDB] $operation succeeded in ${elapsed}ms: "$statement"', + ); + } + return result; + } catch (e) { + final elapsed = stopwatch.elapsedMilliseconds; + final uuids = _findUuids(args); + if (uuids.isNotEmpty) { + Log.info( + '[DriftDB] $operation failed after ${elapsed}ms ($e): "$statement" | UUIDs: $uuids', + ); + } else { + Log.info( + '[DriftDB] $operation failed after ${elapsed}ms ($e): "$statement"', + ); + } + rethrow; + } + } + + @override + Future runInsert( + QueryExecutor executor, + String statement, + List args, + ) { + return _run('INSERT', statement, args, () => executor.runInsert(statement, args)); + } + + @override + Future runUpdate( + QueryExecutor executor, + String statement, + List args, + ) { + return _run('UPDATE', statement, args, () => executor.runUpdate(statement, args)); + } + + @override + Future runDelete( + QueryExecutor executor, + String statement, + List args, + ) { + return _run('DELETE', statement, args, () => executor.runDelete(statement, args)); + } + + @override + Future runCustom( + QueryExecutor executor, + String statement, + List args, + ) { + return _run('CUSTOM', statement, args, () => executor.runCustom(statement, args)); + } + + @override + Future runBatched( + QueryExecutor executor, + BatchedStatements statements, + ) async { + if (!_isEnabled) { + return executor.runBatched(statements); + } + final stopwatch = Stopwatch()..start(); + try { + await executor.runBatched(statements); + final elapsed = stopwatch.elapsedMilliseconds; + final uuids = []; + for (final batchArg in statements.arguments) { + uuids.addAll(_findUuids(batchArg.arguments)); + } + final statementsStr = statements.statements.join('; '); + if (uuids.isNotEmpty) { + Log.info( + '[DriftDB] BATCH succeeded in ${elapsed}ms: "$statementsStr" | UUIDs: $uuids', + ); + } else { + Log.info( + '[DriftDB] BATCH succeeded in ${elapsed}ms: "$statementsStr"', + ); + } + } catch (e) { + final elapsed = stopwatch.elapsedMilliseconds; + final uuids = []; + for (final batchArg in statements.arguments) { + uuids.addAll(_findUuids(batchArg.arguments)); + } + final statementsStr = statements.statements.join('; '); + if (uuids.isNotEmpty) { + Log.info( + '[DriftDB] BATCH failed after ${elapsed}ms ($e): "$statementsStr" | UUIDs: $uuids', + ); + } else { + Log.info( + '[DriftDB] BATCH failed after ${elapsed}ms ($e): "$statementsStr"', + ); + } + rethrow; + } + } +} diff --git a/lib/src/database/twonly.db.dart b/lib/src/database/twonly.db.dart index 5ab35682..812b03e9 100644 --- a/lib/src/database/twonly.db.dart +++ b/lib/src/database/twonly.db.dart @@ -1,8 +1,8 @@ -import 'package:clock/clock.dart'; import 'package:drift/drift.dart'; import 'package:drift_flutter/drift_flutter.dart' show DriftNativeOptions, driftDatabase; import 'package:path_provider/path_provider.dart'; +import 'package:twonly/locator.dart'; import 'package:twonly/src/database/daos/contacts.dao.dart'; import 'package:twonly/src/database/daos/groups.dao.dart'; import 'package:twonly/src/database/daos/key_verification.dao.dart'; @@ -12,6 +12,7 @@ import 'package:twonly/src/database/daos/reactions.dao.dart'; import 'package:twonly/src/database/daos/receipts.dao.dart'; import 'package:twonly/src/database/daos/shortcuts.dao.dart'; import 'package:twonly/src/database/daos/user_discovery.dao.dart'; +import 'package:twonly/src/database/drift_logging_interceptor.dart'; import 'package:twonly/src/database/tables/contacts.table.dart'; import 'package:twonly/src/database/tables/groups.table.dart'; import 'package:twonly/src/database/tables/mediafiles.table.dart'; @@ -84,19 +85,26 @@ class TwonlyDB extends _$TwonlyDB { int get schemaVersion => 17; static QueryExecutor _openConnection() { - return driftDatabase( + final connection = driftDatabase( name: 'twonly', native: DriftNativeOptions( databaseDirectory: getApplicationSupportDirectory, shareAcrossIsolates: true, setup: (rawDb) { rawDb - ..execute('PRAGMA journal_mode=WAL;') + ..execute('PRAGMA journal_mode=DELETE;') ..execute('PRAGMA synchronous=FULL;') ..execute('PRAGMA busy_timeout=5000;'); }, ), ); + try { + if (userService.isUserCreated && + userService.currentUser.enableDatabaseLogging) { + return connection.interceptWith(DriftLoggingInterceptor()); + } + } catch (_) {} + return connection; } @override @@ -246,38 +254,4 @@ class TwonlyDB extends _$TwonlyDB { Log.info('Table: $tableName, Size: $tableSize bytes'); } } - - Future deleteDataForTwonlySafe() async { - await (delete(messages)..where( - (t) => - (t.mediaStored.equals(false) & - t.isDeletedFromSender.equals(false)), - )) - .go(); - await update(messages).write( - const MessagesCompanion( - downloadToken: Value(null), - ), - ); - await (delete(mediaFiles)..where( - (t) => (t.stored.equals(false)), - )) - .go(); - await delete(receipts).go(); - await delete(receivedReceipts).go(); - await update(contacts).write( - const ContactsCompanion( - avatarSvgCompressed: Value(null), - senderProfileCounter: Value(0), - ), - ); - await (delete(signalPreKeyStores)..where( - (t) => (t.createdAt.isSmallerThanValue( - clock.now().subtract( - const Duration(days: 25), - ), - )), - )) - .go(); - } } diff --git a/lib/src/localization/generated/app_localizations.dart b/lib/src/localization/generated/app_localizations.dart index 3050dcf0..e9b1c99e 100644 --- a/lib/src/localization/generated/app_localizations.dart +++ b/lib/src/localization/generated/app_localizations.dart @@ -1460,6 +1460,12 @@ abstract class AppLocalizations { /// **'Delete for all'** String get deleteOkBtnForAll; + /// No description provided for @memoriesDeleteSnackbarSuccess. + /// + /// In en, this message translates to: + /// **'{count, plural, =1 {Deleted 1 item successfully} other {Deleted {count} items successfully}}'** + String memoriesDeleteSnackbarSuccess(num count); + /// No description provided for @deleteOkBtnForMe. /// /// In en, this message translates to: @@ -1478,6 +1484,12 @@ abstract class AppLocalizations { /// **'The image will be irrevocably deleted.'** String get deleteImageBody; + /// No description provided for @deleteMemoriesBody. + /// + /// In en, this message translates to: + /// **'{count, plural, =1 {The image will be irrevocably deleted.} other {The {count} images will be irrevocably deleted.}}'** + String deleteMemoriesBody(num count); + /// No description provided for @settingsBackup. /// /// In en, this message translates to: @@ -3505,6 +3517,178 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Yesterday'** String get yesterday; + + /// No description provided for @galleryDisableWarningTitle. + /// + /// In en, this message translates to: + /// **'Disable gallery saving?'** + String get galleryDisableWarningTitle; + + /// No description provided for @galleryDisableWarningBody. + /// + /// In en, this message translates to: + /// **'If you disable this, your media files will not be saved to your gallery and could be permanently lost if twonly is removed or has an issue, as media files are not yet backed up.'** + String get galleryDisableWarningBody; + + /// No description provided for @galleryDisableWarningConfirm. + /// + /// In en, this message translates to: + /// **'Disable'** + String get galleryDisableWarningConfirm; + + /// No description provided for @settingsStorageScanGalleryTitle. + /// + /// In en, this message translates to: + /// **'Import from Gallery'** + String get settingsStorageScanGalleryTitle; + + /// No description provided for @importGalleryDeselectAll. + /// + /// In en, this message translates to: + /// **'Deselect all'** + String get importGalleryDeselectAll; + + /// No description provided for @importGallerySelectAll. + /// + /// In en, this message translates to: + /// **'Select all'** + String get importGallerySelectAll; + + /// No description provided for @importGalleryPermissionRequired. + /// + /// In en, this message translates to: + /// **'Permission to access your gallery is required to import previous twonly media files.'** + String get importGalleryPermissionRequired; + + /// No description provided for @importGalleryPermissionError. + /// + /// In en, this message translates to: + /// **'An error occurred while requesting permission: {error}'** + String importGalleryPermissionError(Object error); + + /// No description provided for @importGalleryLoadError. + /// + /// In en, this message translates to: + /// **'Failed to load assets: {error}'** + String importGalleryLoadError(Object error); + + /// No description provided for @importGalleryImportingOf. + /// + /// In en, this message translates to: + /// **'Importing {current} of {total}...'** + String importGalleryImportingOf(Object current, Object total); + + /// No description provided for @importGalleryStarting. + /// + /// In en, this message translates to: + /// **'Starting import...'** + String get importGalleryStarting; + + /// No description provided for @importGalleryComplete. + /// + /// In en, this message translates to: + /// **'Import complete: {imported} successfully imported, {duplicated} duplicated and {failed} failed.'** + String importGalleryComplete( + Object imported, + Object duplicated, + Object failed, + ); + + /// No description provided for @importGalleryGrantAccess. + /// + /// In en, this message translates to: + /// **'Grant Access'** + String get importGalleryGrantAccess; + + /// No description provided for @importGalleryOpenSettings. + /// + /// In en, this message translates to: + /// **'Open Settings'** + String get importGalleryOpenSettings; + + /// No description provided for @importGalleryPermissionDenied. + /// + /// In en, this message translates to: + /// **'Permission to access gallery denied.'** + String get importGalleryPermissionDenied; + + /// No description provided for @importGalleryTryAgain. + /// + /// In en, this message translates to: + /// **'Try Again'** + String get importGalleryTryAgain; + + /// No description provided for @importGalleryAlbumNotFound. + /// + /// In en, this message translates to: + /// **'\"twonly\" album not found'** + String get importGalleryAlbumNotFound; + + /// No description provided for @importGalleryAlbumNotFoundDesc. + /// + /// In en, this message translates to: + /// **'If you don\'t have this album yet, you can also create it to import photos into twonly.'** + String get importGalleryAlbumNotFoundDesc; + + /// No description provided for @importGalleryNoImagesFound. + /// + /// In en, this message translates to: + /// **'No images found'** + String get importGalleryNoImagesFound; + + /// No description provided for @importGalleryNoImagesFoundDesc. + /// + /// In en, this message translates to: + /// **'There are no images on your device.'** + String get importGalleryNoImagesFoundDesc; + + /// No description provided for @importGalleryShowAllImages. + /// + /// In en, this message translates to: + /// **'Show all images'** + String get importGalleryShowAllImages; + + /// No description provided for @importGalleryShowTwonlyAlbum. + /// + /// In en, this message translates to: + /// **'Show twonly album'** + String get importGalleryShowTwonlyAlbum; + + /// No description provided for @importGalleryToggleDescAll. + /// + /// In en, this message translates to: + /// **'Viewing all images on your device.'** + String get importGalleryToggleDescAll; + + /// No description provided for @importGalleryToggleDescTwonly. + /// + /// In en, this message translates to: + /// **'Viewing the \"twonly\" album.'** + String get importGalleryToggleDescTwonly; + + /// No description provided for @importGalleryFilterTwonly. + /// + /// In en, this message translates to: + /// **'Only show the twonly-Album'** + String get importGalleryFilterTwonly; + + /// No description provided for @importGalleryRefresh. + /// + /// In en, this message translates to: + /// **'Refresh'** + String get importGalleryRefresh; + + /// No description provided for @importGallerySelectToImport. + /// + /// In en, this message translates to: + /// **'Select items to import'** + String get importGallerySelectToImport; + + /// No description provided for @importGalleryImportCount. + /// + /// In en, this message translates to: + /// **'{count, plural, =1{Import 1 item} other{Import {count} items}}'** + String importGalleryImportCount(num count); } class _AppLocalizationsDelegate diff --git a/lib/src/localization/generated/app_localizations_de.dart b/lib/src/localization/generated/app_localizations_de.dart index 21d62e6a..715eb396 100644 --- a/lib/src/localization/generated/app_localizations_de.dart +++ b/lib/src/localization/generated/app_localizations_de.dart @@ -752,6 +752,17 @@ class AppLocalizationsDe extends AppLocalizations { @override String get deleteOkBtnForAll => 'Für alle löschen'; + @override + String memoriesDeleteSnackbarSuccess(num count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count Elemente erfolgreich gelöscht', + one: '1 Element erfolgreich gelöscht', + ); + return '$_temp0'; + } + @override String get deleteOkBtnForMe => 'Für mich löschen'; @@ -761,6 +772,17 @@ class AppLocalizationsDe extends AppLocalizations { @override String get deleteImageBody => 'Das Bild wird unwiderruflich gelöscht.'; + @override + String deleteMemoriesBody(num count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Die $count Bilder werden unwiderruflich gelöscht.', + one: 'Das Bild wird unwiderruflich gelöscht.', + ); + return '$_temp0'; + } + @override String get settingsBackup => 'Backup'; @@ -1994,4 +2016,115 @@ class AppLocalizationsDe extends AppLocalizations { @override String get yesterday => 'Gestern'; + + @override + String get galleryDisableWarningTitle => 'Galeriespeicherung deaktivieren?'; + + @override + String get galleryDisableWarningBody => + 'Wenn du dies deaktivierst, werden deine Mediendateien nicht in deiner Galerie gespeichert und könnten dauerhaft verloren gehen, wenn twonly deinstalliert wird oder ein Problem auftritt, da Mediendateien noch nicht in Backups enthalten sind.'; + + @override + String get galleryDisableWarningConfirm => 'Deaktivieren'; + + @override + String get settingsStorageScanGalleryTitle => 'Aus Galerie importieren'; + + @override + String get importGalleryDeselectAll => 'Alle abwählen'; + + @override + String get importGallerySelectAll => 'Alle auswählen'; + + @override + String get importGalleryPermissionRequired => + 'Zugriff auf deine Galerie ist erforderlich, um frühere twonly-Mediendateien zu importieren.'; + + @override + String importGalleryPermissionError(Object error) { + return 'Beim Anfordern der Berechtigung ist ein Fehler aufgetreten: $error'; + } + + @override + String importGalleryLoadError(Object error) { + return 'Laden der Medien fehlgeschlagen: $error'; + } + + @override + String importGalleryImportingOf(Object current, Object total) { + return '$current von $total wird importiert...'; + } + + @override + String get importGalleryStarting => 'Import wird gestartet...'; + + @override + String importGalleryComplete( + Object imported, + Object duplicated, + Object failed, + ) { + return 'Import abgeschlossen: $imported erfolgreich importiert, $duplicated Duplikate und $failed fehlgeschlagen.'; + } + + @override + String get importGalleryGrantAccess => 'Zugriff erlauben'; + + @override + String get importGalleryOpenSettings => 'Einstellungen öffnen'; + + @override + String get importGalleryPermissionDenied => 'Zugriff auf Galerie verweigert.'; + + @override + String get importGalleryTryAgain => 'Erneut versuchen'; + + @override + String get importGalleryAlbumNotFound => '\"twonly\"-Album nicht gefunden'; + + @override + String get importGalleryAlbumNotFoundDesc => + 'Falls du dieses Album noch nicht hast, kannst du es auch erstellen, um Fotos in twonly zu importieren.'; + + @override + String get importGalleryNoImagesFound => 'Keine Bilder gefunden'; + + @override + String get importGalleryNoImagesFoundDesc => + 'Es befinden sich keine Bilder auf deinem Gerät.'; + + @override + String get importGalleryShowAllImages => 'Alle Bilder anzeigen'; + + @override + String get importGalleryShowTwonlyAlbum => 'twonly-Album anzeigen'; + + @override + String get importGalleryToggleDescAll => + 'Es werden alle Bilder auf deinem Gerät angezeigt.'; + + @override + String get importGalleryToggleDescTwonly => + 'Es wird das \"twonly\"-Album angezeigt.'; + + @override + String get importGalleryFilterTwonly => 'Nur das twonly-Album anzeigen'; + + @override + String get importGalleryRefresh => 'Aktualisieren'; + + @override + String get importGallerySelectToImport => + 'Elemente zum Importieren auswählen'; + + @override + String importGalleryImportCount(num count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count Elemente importieren', + one: '1 Element importieren', + ); + return '$_temp0'; + } } diff --git a/lib/src/localization/generated/app_localizations_en.dart b/lib/src/localization/generated/app_localizations_en.dart index 30dc06cb..f379326c 100644 --- a/lib/src/localization/generated/app_localizations_en.dart +++ b/lib/src/localization/generated/app_localizations_en.dart @@ -746,6 +746,17 @@ class AppLocalizationsEn extends AppLocalizations { @override String get deleteOkBtnForAll => 'Delete for all'; + @override + String memoriesDeleteSnackbarSuccess(num count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Deleted $count items successfully', + one: 'Deleted 1 item successfully', + ); + return '$_temp0'; + } + @override String get deleteOkBtnForMe => 'Delete for me'; @@ -755,6 +766,17 @@ class AppLocalizationsEn extends AppLocalizations { @override String get deleteImageBody => 'The image will be irrevocably deleted.'; + @override + String deleteMemoriesBody(num count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'The $count images will be irrevocably deleted.', + one: 'The image will be irrevocably deleted.', + ); + return '$_temp0'; + } + @override String get settingsBackup => 'Backup'; @@ -1978,4 +2000,113 @@ class AppLocalizationsEn extends AppLocalizations { @override String get yesterday => 'Yesterday'; + + @override + String get galleryDisableWarningTitle => 'Disable gallery saving?'; + + @override + String get galleryDisableWarningBody => + 'If you disable this, your media files will not be saved to your gallery and could be permanently lost if twonly is removed or has an issue, as media files are not yet backed up.'; + + @override + String get galleryDisableWarningConfirm => 'Disable'; + + @override + String get settingsStorageScanGalleryTitle => 'Import from Gallery'; + + @override + String get importGalleryDeselectAll => 'Deselect all'; + + @override + String get importGallerySelectAll => 'Select all'; + + @override + String get importGalleryPermissionRequired => + 'Permission to access your gallery is required to import previous twonly media files.'; + + @override + String importGalleryPermissionError(Object error) { + return 'An error occurred while requesting permission: $error'; + } + + @override + String importGalleryLoadError(Object error) { + return 'Failed to load assets: $error'; + } + + @override + String importGalleryImportingOf(Object current, Object total) { + return 'Importing $current of $total...'; + } + + @override + String get importGalleryStarting => 'Starting import...'; + + @override + String importGalleryComplete( + Object imported, + Object duplicated, + Object failed, + ) { + return 'Import complete: $imported successfully imported, $duplicated duplicated and $failed failed.'; + } + + @override + String get importGalleryGrantAccess => 'Grant Access'; + + @override + String get importGalleryOpenSettings => 'Open Settings'; + + @override + String get importGalleryPermissionDenied => + 'Permission to access gallery denied.'; + + @override + String get importGalleryTryAgain => 'Try Again'; + + @override + String get importGalleryAlbumNotFound => '\"twonly\" album not found'; + + @override + String get importGalleryAlbumNotFoundDesc => + 'If you don\'t have this album yet, you can also create it to import photos into twonly.'; + + @override + String get importGalleryNoImagesFound => 'No images found'; + + @override + String get importGalleryNoImagesFoundDesc => + 'There are no images on your device.'; + + @override + String get importGalleryShowAllImages => 'Show all images'; + + @override + String get importGalleryShowTwonlyAlbum => 'Show twonly album'; + + @override + String get importGalleryToggleDescAll => 'Viewing all images on your device.'; + + @override + String get importGalleryToggleDescTwonly => 'Viewing the \"twonly\" album.'; + + @override + String get importGalleryFilterTwonly => 'Only show the twonly-Album'; + + @override + String get importGalleryRefresh => 'Refresh'; + + @override + String get importGallerySelectToImport => 'Select items to import'; + + @override + String importGalleryImportCount(num count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Import $count items', + one: 'Import 1 item', + ); + return '$_temp0'; + } } diff --git a/lib/src/localization/translations b/lib/src/localization/translations index 9a538845..189bf8f4 160000 --- a/lib/src/localization/translations +++ b/lib/src/localization/translations @@ -1 +1 @@ -Subproject commit 9a538845a340f41ee8d2d23bc4c3e8fd73797203 +Subproject commit 189bf8f4dbe2bee4f19a15b9640b8826e4f2e235 diff --git a/lib/src/model/json/userdata.model.dart b/lib/src/model/json/userdata.model.dart index e3aa59a6..c5b4ce2b 100644 --- a/lib/src/model/json/userdata.model.dart +++ b/lib/src/model/json/userdata.model.dart @@ -13,7 +13,8 @@ class UserData { required this.currentSetupPage, required this.appVersion, }); - factory UserData.fromJson(Map json) => _$UserDataFromJson(json); + factory UserData.fromJson(Map json) => + _$UserDataFromJson(json); final int userId; @@ -64,6 +65,9 @@ class UserData { @JsonKey(defaultValue: false) bool requestedAudioPermission = false; + @JsonKey(defaultValue: false) + bool enableDatabaseLogging = false; + @JsonKey(defaultValue: false) bool automaticallyMarkEqualMediaFilesAsOpened = false; @@ -83,8 +87,8 @@ class UserData { Map>? autoDownloadOptions; - @JsonKey(defaultValue: false) - bool storeMediaFilesInGallery = false; + @JsonKey(defaultValue: true) + bool storeMediaFilesInGallery = true; @JsonKey(defaultValue: false) bool autoStoreAllSendUnlimitedMediaFiles = false; @@ -186,7 +190,8 @@ class TwonlySafeBackup { required this.backupId, required this.encryptionKey, }); - factory TwonlySafeBackup.fromJson(Map json) => _$TwonlySafeBackupFromJson(json); + factory TwonlySafeBackup.fromJson(Map json) => + _$TwonlySafeBackupFromJson(json); int lastBackupSize = 0; LastBackupUploadState backupUploadState = LastBackupUploadState.none; diff --git a/lib/src/model/json/userdata.model.g.dart b/lib/src/model/json/userdata.model.g.dart index 4ae054fd..9cec2fea 100644 --- a/lib/src/model/json/userdata.model.g.dart +++ b/lib/src/model/json/userdata.model.g.dart @@ -42,6 +42,7 @@ UserData _$UserDataFromJson(Map json) => ..defaultShowTime = (json['defaultShowTime'] as num?)?.toInt() ..requestedAudioPermission = json['requestedAudioPermission'] as bool? ?? false + ..enableDatabaseLogging = json['enableDatabaseLogging'] as bool? ?? false ..automaticallyMarkEqualMediaFilesAsOpened = json['automaticallyMarkEqualMediaFilesAsOpened'] as bool? ?? false ..videoStabilizationEnabled = @@ -135,6 +136,7 @@ Map _$UserDataToJson(UserData instance) => { 'themeMode': _$ThemeModeEnumMap[instance.themeMode]!, 'defaultShowTime': instance.defaultShowTime, 'requestedAudioPermission': instance.requestedAudioPermission, + 'enableDatabaseLogging': instance.enableDatabaseLogging, 'automaticallyMarkEqualMediaFilesAsOpened': instance.automaticallyMarkEqualMediaFilesAsOpened, 'videoStabilizationEnabled': instance.videoStabilizationEnabled, diff --git a/lib/src/providers/routing.provider.dart b/lib/src/providers/routing.provider.dart index 967887d0..a807edd2 100644 --- a/lib/src/providers/routing.provider.dart +++ b/lib/src/providers/routing.provider.dart @@ -22,8 +22,7 @@ import 'package:twonly/src/visual/views/settings/backup/backup_setup.view.dart'; import 'package:twonly/src/visual/views/settings/chat/chat_reactions.view.dart'; import 'package:twonly/src/visual/views/settings/chat/chat_settings.view.dart'; import 'package:twonly/src/visual/views/settings/data_and_storage.view.dart'; -import 'package:twonly/src/visual/views/settings/data_and_storage/export_media.view.dart'; -import 'package:twonly/src/visual/views/settings/data_and_storage/import_media.view.dart'; +import 'package:twonly/src/visual/views/settings/data_and_storage/import_from_gallery.view.dart'; import 'package:twonly/src/visual/views/settings/data_and_storage/manage_storage.view.dart'; import 'package:twonly/src/visual/views/settings/developer/automated_testing.view.dart'; import 'package:twonly/src/visual/views/settings/developer/developer.view.dart'; @@ -225,12 +224,8 @@ final routerProvider = GoRouter( builder: (context, state) => const ManageStorageView(), ), GoRoute( - path: 'import', - builder: (context, state) => const ImportMediaView(), - ), - GoRoute( - path: 'export', - builder: (context, state) => const ExportMediaView(), + path: 'import_gallery', + builder: (context, state) => const ImportFromGalleryView(), ), ], ), diff --git a/lib/src/services/android_photo_picker.service.dart b/lib/src/services/android_photo_picker.service.dart new file mode 100644 index 00000000..d4380fdb --- /dev/null +++ b/lib/src/services/android_photo_picker.service.dart @@ -0,0 +1,25 @@ +import 'package:flutter/services.dart'; + +class AndroidPhotoPickerService { + static const MethodChannel _channel = MethodChannel('eu.twonly/photo_picker'); + + /// Launches the native Android Photo Picker and returns a list of URIs. + static Future> pickImages() async { + try { + final result = await _channel.invokeListMethod('pickImages'); + return result ?? []; + } catch (e) { + return []; + } + } + + /// Reads the raw bytes from a content URI using the Android ContentResolver. + static Future getUriBytes(String uri) async { + try { + final bytes = await _channel.invokeMethod('getUriBytes', {'uri': uri}); + return bytes; + } catch (e) { + return null; + } + } +} diff --git a/lib/src/services/api/mediafiles/upload.api.dart b/lib/src/services/api/mediafiles/upload.api.dart index bce9db1d..deb7be04 100644 --- a/lib/src/services/api/mediafiles/upload.api.dart +++ b/lib/src/services/api/mediafiles/upload.api.dart @@ -51,7 +51,7 @@ Future reuploadMediaFiles() async { final contacts = {}; - for (var receipt in receipts) { + for (final receipt in receipts) { if (receipt.retryCount > 1 && receipt.lastRetry != null) { final twentyFourHoursAgo = DateTime.now().subtract( const Duration(hours: 6), @@ -64,20 +64,6 @@ Future reuploadMediaFiles() async { } } - if (receipt.retryCount >= 2) { - // After two retries, change the receiptId. This addresses a bug where the receiver received the message and marked it as received, but the app was closed before the message was fully processed. Because the receipt was already stored, subsequent retries were detected as duplicates and rejected. - final oldReceiptId = receipt.receiptId; - final updatedReceipt = await twonlyDB.receiptsDao.rotateReceiptId( - oldReceiptId, - ); - if (updatedReceipt == null) continue; - - Log.info( - 'Changed receiptId $oldReceiptId to ${updatedReceipt.receiptId} as retryCount is ${receipt.retryCount}', - ); - receipt = updatedReceipt; - } - var messageId = receipt.messageId; if (receipt.messageId == null) { Log.info('Message not in receipt. Loading it from the content.'); diff --git a/lib/src/services/mediafiles/mediafile.service.dart b/lib/src/services/mediafiles/mediafile.service.dart index deae9049..83528eab 100644 --- a/lib/src/services/mediafiles/mediafile.service.dart +++ b/lib/src/services/mediafiles/mediafile.service.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:clock/clock.dart'; import 'package:drift/drift.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter_image_compress/flutter_image_compress.dart'; import 'package:image/image.dart' as img; import 'package:path/path.dart'; @@ -310,6 +311,7 @@ class MediaFileService { } else { await saveImageToGallery( storedPath.readAsBytesSync(), + createdAt: mediaFile.createdAt, ); } } @@ -447,106 +449,41 @@ class MediaFileService { try { final bytes = storedPath.readAsBytesSync(); - final image = img.decodeImage(bytes); - if (image == null) { - await twonlyDB.mediaFilesDao.updateMedia( - mediaFile.mediaId, - const MediaFilesCompanion(hasCropAnalyzed: Value(true)), - ); - return; - } + final result = await compute(_processImageCrop, bytes); - var minY = 0; - var maxY = image.height - 1; - var minX = 0; - var maxX = image.width - 1; - - var found = false; - for (var y = 0; y < image.height; y++) { - for (var x = 0; x < image.width; x++) { - if (image.getPixel(x, y).a > 10) { - minY = y; - found = true; - break; - } - } - if (found) break; - } - - found = false; - for (var y = image.height - 1; y >= minY; y--) { - for (var x = 0; x < image.width; x++) { - if (image.getPixel(x, y).a > 10) { - maxY = y; - found = true; - break; - } - } - if (found) break; - } - - found = false; - for (var x = 0; x < image.width; x++) { - for (var y = minY; y <= maxY; y++) { - if (image.getPixel(x, y).a > 10) { - minX = x; - found = true; - break; - } - } - if (found) break; - } - - found = false; - for (var x = image.width - 1; x >= minX; x--) { - for (var y = minY; y <= maxY; y++) { - if (image.getPixel(x, y).a > 10) { - maxX = x; - found = true; - break; - } - } - if (found) break; - } - - final newWidth = maxX - minX + 1; - final newHeight = maxY - minY + 1; - - if (minY > 0 || - maxY < image.height - 1 || - minX > 0 || - maxX < image.width - 1) { - if (newWidth > 10 && newHeight > 10) { - final cropped = img.copyCrop( - image, - x: minX, - y: minY, - width: newWidth, - height: newHeight, - ); - final pngBytes = img.encodePng(cropped); + if (result.isCropped && result.pngBytes != null) { + try { final webpBytes = await FlutterImageCompress.compressWithList( - pngBytes, + result.pngBytes!, format: CompressFormat.webp, quality: 90, ); - storedPath.writeAsBytesSync(webpBytes); - - if (thumbnailPath.existsSync()) { - thumbnailPath.deleteSync(); + + if (webpBytes.isNotEmpty) { + storedPath.writeAsBytesSync(webpBytes); + } else { + Log.warn('WebP compression returned empty, falling back to PNG'); + storedPath.writeAsBytesSync(result.pngBytes!); } - await createThumbnail(); - final checksum = await sha256File(storedPath); - await twonlyDB.mediaFilesDao.updateMedia( - mediaFile.mediaId, - MediaFilesCompanion( - hasCropAnalyzed: const Value(true), - storedFileHash: Value(Uint8List.fromList(checksum)), - ), - ); - await updateFromDB(); - return; + } catch (e) { + Log.error('Error compressing to WebP, falling back to PNG: $e'); + storedPath.writeAsBytesSync(result.pngBytes!); } + + if (thumbnailPath.existsSync()) { + thumbnailPath.deleteSync(); + } + await createThumbnail(); + final checksum = await sha256File(storedPath); + await twonlyDB.mediaFilesDao.updateMedia( + mediaFile.mediaId, + MediaFilesCompanion( + hasCropAnalyzed: const Value(true), + storedFileHash: Value(Uint8List.fromList(checksum)), + ), + ); + await updateFromDB(); + return; } await twonlyDB.mediaFilesDao.updateMedia( @@ -566,3 +503,89 @@ class MediaFileService { } } } + +class _CropResult { + const _CropResult(this.pngBytes, this.isCropped); + final Uint8List? pngBytes; + final bool isCropped; +} + +_CropResult _processImageCrop(Uint8List bytes) { + final image = img.decodeImage(bytes); + if (image == null) return const _CropResult(null, false); + + var minY = 0; + var maxY = image.height - 1; + var minX = 0; + var maxX = image.width - 1; + + var found = false; + for (var y = 0; y < image.height; y++) { + for (var x = 0; x < image.width; x++) { + if (image.getPixel(x, y).a > 10) { + minY = y; + found = true; + break; + } + } + if (found) break; + } + + found = false; + for (var y = image.height - 1; y >= minY; y--) { + for (var x = 0; x < image.width; x++) { + if (image.getPixel(x, y).a > 10) { + maxY = y; + found = true; + break; + } + } + if (found) break; + } + + found = false; + for (var x = 0; x < image.width; x++) { + for (var y = minY; y <= maxY; y++) { + if (image.getPixel(x, y).a > 10) { + minX = x; + found = true; + break; + } + } + if (found) break; + } + + found = false; + for (var x = image.width - 1; x >= minX; x--) { + for (var y = minY; y <= maxY; y++) { + if (image.getPixel(x, y).a > 10) { + maxX = x; + found = true; + break; + } + } + if (found) break; + } + + final newWidth = maxX - minX + 1; + final newHeight = maxY - minY + 1; + + if (minY > 0 || + maxY < image.height - 1 || + minX > 0 || + maxX < image.width - 1) { + if (newWidth > 10 && newHeight > 10) { + final cropped = img.copyCrop( + image, + x: minX, + y: minY, + width: newWidth, + height: newHeight, + ); + final pngBytes = img.encodePng(cropped); + return _CropResult(pngBytes, true); + } + } + + return const _CropResult(null, false); +} diff --git a/lib/src/services/user.service.dart b/lib/src/services/user.service.dart index e2b8e299..6d3c8018 100644 --- a/lib/src/services/user.service.dart +++ b/lib/src/services/user.service.dart @@ -32,6 +32,13 @@ class UserService { if (userDataMap != null) { final userData = UserData.fromJson(userDataMap); await RustKeyManager.setUserId(userId: userData.userId); + try { + // Ensure that the old userData is removed as it breaks the backup mechanism. + // This code can be removed when all users have updated to the latest version... + await SecureStorage.instance.delete(key: 'userData'); + } catch (e) { + Log.error('Could not delete user data from SecureStorage: $e'); + } return userData; } @@ -58,15 +65,20 @@ class UserService { } static Future _migrateFromSecureStorage(UserData userData) async { - // Currently empty migration logic as requested, but we MUST store the data await KeyValueStore.put('user', userData.toJson()); + try { await RustKeyManager.setUserId(userId: userData.userId); } catch (e) { Log.error('Could not set userId in RustKeyManager during migration: $e'); } - // Optional: Log migration + try { + await SecureStorage.instance.delete(key: 'userData'); + } catch (e) { + Log.error('Could not delete user data from SecureStorage: $e'); + } + Log.info('Migrated user data from SecureStorage to KeyValueStore'); } diff --git a/lib/src/utils/misc.dart b/lib/src/utils/misc.dart index 6d7414bf..b11db174 100644 --- a/lib/src/utils/misc.dart +++ b/lib/src/utils/misc.dart @@ -1,5 +1,6 @@ import 'dart:io'; import 'dart:math'; + import 'package:clock/clock.dart'; import 'package:convert/convert.dart'; import 'package:crypto/crypto.dart'; @@ -7,6 +8,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_image_compress/flutter_image_compress.dart'; import 'package:gal/gal.dart'; +import 'package:image/image.dart' as img; import 'package:intl/intl.dart'; import 'package:local_auth/local_auth.dart'; import 'package:provider/provider.dart'; @@ -31,19 +33,49 @@ extension ShortCutsExtension on BuildContext { } } -Future saveImageToGallery(Uint8List imageBytes) async { +Future saveImageToGallery( + Uint8List imageBytes, { + DateTime? createdAt, +}) async { + var bytesToProcess = imageBytes; + + if (createdAt != null) { + try { + final image = img.decodeImage(imageBytes); + if (image != null) { + final formattedDate = DateFormat( + 'yyyy:MM:dd HH:mm:ss', + ).format(createdAt); + image.exif.imageIfd[0x0132] = img.IfdValueAscii( + formattedDate, + ); // DateTime + image.exif.exifIfd[0x9003] = img.IfdValueAscii( + formattedDate, + ); // DateTimeOriginal + image.exif.exifIfd[0x9004] = img.IfdValueAscii( + formattedDate, + ); // DateTimeDigitized + + bytesToProcess = img.encodeJpg(image); + } + } catch (e) { + Log.error(e); + } + } + final jpgImages = await FlutterImageCompress.compressWithList( // ignore: avoid_redundant_argument_values format: CompressFormat.jpeg, - imageBytes, + bytesToProcess, quality: 100, + keepExif: true, ); - final hasAccess = await Gal.hasAccess(); + final hasAccess = await Gal.hasAccess(toAlbum: true); if (!hasAccess) { - await Gal.requestAccess(); + await Gal.requestAccess(toAlbum: true); } try { - await Gal.putImageBytes(jpgImages); + await Gal.putImageBytes(jpgImages, album: 'twonly'); return null; } on GalException catch (e) { Log.error(e); @@ -52,12 +84,12 @@ Future saveImageToGallery(Uint8List imageBytes) async { } Future saveVideoToGallery(String videoPath) async { - final hasAccess = await Gal.hasAccess(); + final hasAccess = await Gal.hasAccess(toAlbum: true); if (!hasAccess) { - await Gal.requestAccess(); + await Gal.requestAccess(toAlbum: true); } try { - await Gal.putVideo(videoPath); + await Gal.putVideo(videoPath, album: 'twonly'); return null; } on GalException catch (e) { Log.error(e); diff --git a/lib/src/visual/components/selectable_thumbnail.comp.dart b/lib/src/visual/components/selectable_thumbnail.comp.dart new file mode 100644 index 00000000..572b017d --- /dev/null +++ b/lib/src/visual/components/selectable_thumbnail.comp.dart @@ -0,0 +1,77 @@ +import 'package:flutter/material.dart'; +import 'package:twonly/src/utils/misc.dart'; + +class SelectableThumbnailComp extends StatelessWidget { + const SelectableThumbnailComp({ + required this.child, + required this.isSelected, + this.selectionMode = true, + super.key, + }); + + final Widget child; + final bool isSelected; + final bool selectionMode; + + @override + Widget build(BuildContext context) { + return AnimatedContainer( + duration: const Duration(milliseconds: 200), + curve: Curves.easeInOut, + decoration: BoxDecoration( + color: isSelected ? context.color.primary : Colors.transparent, + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 4, + offset: Offset(0, 2), + ), + ], + ), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + curve: Curves.easeInOut, + margin: EdgeInsets.all(isSelected ? 4 : 0), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular( + isSelected ? 12 : 0, + ), + ), + clipBehavior: Clip.antiAlias, + child: Stack( + fit: StackFit.expand, + children: [ + child, + if (selectionMode) + Positioned( + top: 6, + right: 6, + child: Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration( + color: isSelected + ? context.color.primary + : Colors.black38, + shape: BoxShape.circle, + border: Border.all( + color: Theme.of(context).brightness == Brightness.dark + ? Colors.white + : Colors.black, + width: 1.5, + ), + ), + child: isSelected + ? const Icon( + Icons.check, + size: 14, + color: Colors.white, + ) + : const SizedBox(width: 14, height: 14), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/src/visual/helpers/video_player_file.helper.dart b/lib/src/visual/helpers/video_player_file.helper.dart index 06931235..93ffdbf0 100644 --- a/lib/src/visual/helpers/video_player_file.helper.dart +++ b/lib/src/visual/helpers/video_player_file.helper.dart @@ -54,7 +54,7 @@ class _VideoPlayerFileHelperState extends State { aspectRatio: _controller.value.aspectRatio, child: VideoPlayerHelper(controller: _controller), ) - : const CircularProgressIndicator(), + : const CircularProgressIndicator.adaptive(), ); } } diff --git a/lib/src/visual/views/camera/add_new_shortcut.view.dart b/lib/src/visual/views/camera/add_new_shortcut.view.dart index 41291ace..4335a5c1 100644 --- a/lib/src/visual/views/camera/add_new_shortcut.view.dart +++ b/lib/src/visual/views/camera/add_new_shortcut.view.dart @@ -260,7 +260,7 @@ class _StartNewChatView extends State { group: group, fontSize: 15, ), - trailing: Checkbox( + trailing: Checkbox.adaptive( value: _selectedGroups.contains(group.groupId), side: WidgetStateBorderSide.resolveWith( (states) { diff --git a/lib/src/visual/views/camera/camera_preview_components/camera_preview_controller_components/camera_scanned_overlay.dart b/lib/src/visual/views/camera/camera_preview_components/camera_preview_controller_components/camera_scanned_overlay.dart index 8e003fcc..6718ef41 100644 --- a/lib/src/visual/views/camera/camera_preview_components/camera_preview_controller_components/camera_scanned_overlay.dart +++ b/lib/src/visual/views/camera/camera_preview_components/camera_preview_controller_components/camera_scanned_overlay.dart @@ -75,7 +75,7 @@ class CameraScannedOverlay extends StatelessWidget { const SizedBox( width: 12, height: 12, - child: CircularProgressIndicator(strokeWidth: 2), + child: CircularProgressIndicator.adaptive(strokeWidth: 2), ) else ColoredBox( diff --git a/lib/src/visual/views/camera/camera_preview_components/camera_preview_controller_view.dart b/lib/src/visual/views/camera/camera_preview_components/camera_preview_controller_view.dart index 6f638aa6..253e62c8 100644 --- a/lib/src/visual/views/camera/camera_preview_components/camera_preview_controller_view.dart +++ b/lib/src/visual/views/camera/camera_preview_components/camera_preview_controller_view.dart @@ -63,23 +63,25 @@ class CameraPreviewControllerView extends StatefulWidget { final bool hideControllers; @override - State createState() => _CameraPreviewControllerViewState(); + State createState() => + _CameraPreviewControllerViewState(); } -class _CameraPreviewControllerViewState extends State { +class _CameraPreviewControllerViewState + extends State { Future? _permissionsFuture; @override void initState() { super.initState(); - if (!AppState.hasCameraPermissions) { - _permissionsFuture = checkPermissions().then((hasPermission) { - if (hasPermission) { + _permissionsFuture = checkPermissions().then((hasPermission) { + if (hasPermission && mounted) { + setState(() { AppState.hasCameraPermissions = true; - } - return hasPermission; - }); - } + }); + } + return hasPermission; + }); } @override @@ -107,6 +109,10 @@ class _CameraPreviewControllerViewState extends State { Future initAsync() async { _hasAudioPermission = await Permission.microphone.isGranted; - if (!_hasAudioPermission && !userService.currentUser.requestedAudioPermission) { + if (!_hasAudioPermission && + !userService.currentUser.requestedAudioPermission) { await UserService.update((u) => u.requestedAudioPermission = true); await requestMicrophonePermission(); } @@ -262,7 +269,8 @@ class _CameraPreviewViewState extends State { } Future updateScaleFactor(double newScale) async { - if (mc.selectedCameraDetails.scaleFactor == newScale || mc.cameraController == null) { + if (mc.selectedCameraDetails.scaleFactor == newScale || + mc.cameraController == null) { return; } await mc.cameraController?.setZoomLevel( @@ -345,7 +353,9 @@ class _CameraPreviewViewState extends State { bool sharedFromGallery = false, MediaType? mediaType, }) async { - final type = mediaType ?? ((videoFilePath != null) ? MediaType.video : MediaType.image); + final type = + mediaType ?? + ((videoFilePath != null) ? MediaType.video : MediaType.image); final mediaFileService = await initializeMediaUpload( type, userService.currentUser.defaultShowTime, @@ -386,9 +396,10 @@ class _CameraPreviewViewState extends State { mainCameraController: mc, previewLink: mc.sharedLinkForPreview, ), - transitionsBuilder: (context, animation, secondaryAnimation, child) { - return child; - }, + transitionsBuilder: + (context, animation, secondaryAnimation, child) { + return child; + }, transitionDuration: Duration.zero, reverseTransitionDuration: Duration.zero, ), @@ -418,13 +429,16 @@ class _CameraPreviewViewState extends State { return false; } - bool get isFront => mc.cameraController?.description.lensDirection == CameraLensDirection.front; + bool get isFront => + mc.cameraController?.description.lensDirection == + CameraLensDirection.front; Future onPanUpdate(dynamic details) async { if (details == null) { return; } - if (mc.cameraController == null || !mc.cameraController!.value.isInitialized) { + if (mc.cameraController == null || + !mc.cameraController!.value.isInitialized) { return; } @@ -553,7 +567,8 @@ class _CameraPreviewViewState extends State { } Future startVideoRecording() async { - if (mc.cameraController != null && mc.cameraController!.value.isRecordingVideo) { + if (mc.cameraController != null && + mc.cameraController!.value.isRecordingVideo) { return; } setState(() { @@ -573,7 +588,8 @@ class _CameraPreviewViewState extends State { _currentTime = clock.now(); }); if (_videoRecordingStarted != null && - _currentTime.difference(_videoRecordingStarted!).inSeconds >= maxVideoRecordingTime) { + _currentTime.difference(_videoRecordingStarted!).inSeconds >= + maxVideoRecordingTime) { timer.cancel(); _videoRecordingTimer = null; stopVideoRecording(); @@ -610,7 +626,8 @@ class _CameraPreviewViewState extends State { _videoRecordingLocked = false; }); - if (mc.cameraController == null || !mc.cameraController!.value.isRecordingVideo) { + if (mc.cameraController == null || + !mc.cameraController!.value.isRecordingVideo) { return; } @@ -638,7 +655,8 @@ class _CameraPreviewViewState extends State { @override Widget build(BuildContext context) { - if (mc.selectedCameraDetails.cameraId >= AppEnvironment.cameras.length || mc.cameraController == null) { + if (mc.selectedCameraDetails.cameraId >= AppEnvironment.cameras.length || + mc.cameraController == null) { return Container(); } return StreamBuilder( @@ -662,7 +680,9 @@ class _CameraPreviewViewState extends State { _baseScaleFactor = mc.selectedCameraDetails.scaleFactor; }); // Get the position of the pointer - final renderBox = keyTriggerButton.currentContext!.findRenderObject()! as RenderBox; + final renderBox = + keyTriggerButton.currentContext!.findRenderObject()! + as RenderBox; final localPosition = renderBox.globalToLocal( details.globalPosition, ); @@ -698,18 +718,24 @@ class _CameraPreviewViewState extends State { ), ), ), - if (!mc.isSharePreviewIsShown && widget.sendToGroup != null && !mc.isVideoRecording) + if (!mc.isSharePreviewIsShown && + widget.sendToGroup != null && + !mc.isVideoRecording) ShowTitleText( title: widget.sendToGroup!.groupName, desc: context.lang.cameraPreviewSendTo, ), - if (!mc.isSharePreviewIsShown && mc.sharedLinkForPreview != null && !mc.isVideoRecording) + if (!mc.isSharePreviewIsShown && + mc.sharedLinkForPreview != null && + !mc.isVideoRecording) ShowTitleText( title: mc.sharedLinkForPreview?.host ?? '', desc: 'Link', isLink: true, ), - if (!mc.isSharePreviewIsShown && !mc.isVideoRecording && !widget.hideControllers) + if (!mc.isSharePreviewIsShown && + !mc.isVideoRecording && + !widget.hideControllers) CameraTopActions( selectedCameraDetails: mc.selectedCameraDetails, hasAudioPermission: _hasAudioPermission, @@ -753,7 +779,8 @@ class _CameraPreviewViewState extends State { videoRecordingStarted: _videoRecordingStarted, maxVideoRecordingTime: maxVideoRecordingTime, ), - if (!mc.isSharePreviewIsShown && widget.sendToGroup != null || widget.hideControllers) + if (!mc.isSharePreviewIsShown && widget.sendToGroup != null || + widget.hideControllers) Positioned( left: 5, top: 10, diff --git a/lib/src/visual/views/camera/camera_preview_components/permissions_view.dart b/lib/src/visual/views/camera/camera_preview_components/permissions_view.dart index 411fb547..fa14088e 100644 --- a/lib/src/visual/views/camera/camera_preview_components/permissions_view.dart +++ b/lib/src/visual/views/camera/camera_preview_components/permissions_view.dart @@ -1,4 +1,4 @@ -// ignore_for_file: avoid_dynamic_calls +import 'dart:async'; import 'package:flutter/material.dart'; import 'package:permission_handler/permission_handler.dart'; @@ -24,31 +24,56 @@ Future checkPermissions() async { return true; } -class PermissionHandlerViewState extends State { +class PermissionHandlerViewState extends State + with WidgetsBindingObserver { + Timer? _timer; + bool _isSuccessTriggered = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _timer = Timer.periodic(const Duration(milliseconds: 500), (timer) async { + await _checkAndTriggerSuccess(); + }); + } + + @override + void dispose() { + _timer?.cancel(); + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + _checkAndTriggerSuccess(); + } + } + + Future _checkAndTriggerSuccess() async { + if (_isSuccessTriggered) return; + try { + if (await checkPermissions()) { + _isSuccessTriggered = true; + _timer?.cancel(); + // ignore: avoid_dynamic_calls + widget.onSuccess(); + } + } catch (e) { + Log.error(e); + } + } + Future> permissionServices() async { - // try { final statuses = await [ Permission.camera, - // Permission.microphone, Permission.notification, ].request(); - // } catch (e) {} - // You can request multiple permissions at once. - - // if (statuses[Permission.microphone]!.isPermanentlyDenied) { - // openAppSettings(); - // // setState(() {}); - // } else { - // // if (statuses[Permission.microphone]!.isDenied) { - // // } - // } if (statuses[Permission.camera]!.isPermanentlyDenied) { await openAppSettings(); - // setState(() {}); - } else { - // if (statuses[Permission.camera]!.isDenied) { - // } } return statuses; @@ -75,6 +100,7 @@ class PermissionHandlerViewState extends State { try { await permissionServices(); if (await checkPermissions()) { + // ignore: avoid_dynamic_calls widget.onSuccess(); } } catch (e) { diff --git a/lib/src/visual/views/camera/camera_preview_components/save_to_gallery.dart b/lib/src/visual/views/camera/camera_preview_components/save_to_gallery.dart index de92b0e6..9be4b6aa 100644 --- a/lib/src/visual/views/camera/camera_preview_components/save_to_gallery.dart +++ b/lib/src/visual/views/camera/camera_preview_components/save_to_gallery.dart @@ -90,7 +90,7 @@ class SaveToGalleryButtonState extends State { const SizedBox( width: 12, height: 12, - child: CircularProgressIndicator(strokeWidth: 1), + child: CircularProgressIndicator.adaptive(strokeWidth: 1), ) else _imageSaved diff --git a/lib/src/visual/views/camera/share_image_contact_selection.view.dart b/lib/src/visual/views/camera/share_image_contact_selection.view.dart index 4a6f7a40..752157a1 100644 --- a/lib/src/visual/views/camera/share_image_contact_selection.view.dart +++ b/lib/src/visual/views/camera/share_image_contact_selection.view.dart @@ -218,7 +218,7 @@ class _ShareImageView extends State { ), Transform.scale( scale: 0.75, - child: Checkbox( + child: Checkbox.adaptive( value: !hideArchivedUsers, side: WidgetStateBorderSide.resolveWith( (states) { @@ -293,9 +293,9 @@ class _ShareImageView extends State { ? SizedBox( height: 12, width: 12, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, - color: Theme.of(context).colorScheme.inversePrimary, + valueColor: AlwaysStoppedAnimation(Theme.of(context).colorScheme.inversePrimary), ), ) : const FaIcon(FontAwesomeIcons.solidPaperPlane), @@ -382,7 +382,7 @@ class UserList extends StatelessWidget { group: group, fontSize: 15, ), - trailing: Checkbox( + trailing: Checkbox.adaptive( value: selectedGroupIds.contains(group.groupId), side: WidgetStateBorderSide.resolveWith( (states) { diff --git a/lib/src/visual/views/camera/share_image_contact_selection_components/best_friends_selector.dart b/lib/src/visual/views/camera/share_image_contact_selection_components/best_friends_selector.dart index 91f8a70b..efc3ccc5 100644 --- a/lib/src/visual/views/camera/share_image_contact_selection_components/best_friends_selector.dart +++ b/lib/src/visual/views/camera/share_image_contact_selection_components/best_friends_selector.dart @@ -165,7 +165,7 @@ class UserCheckbox extends StatelessWidget { ], ), Expanded(child: Container()), - Checkbox( + Checkbox.adaptive( value: isChecked, side: WidgetStateBorderSide.resolveWith( (states) { diff --git a/lib/src/visual/views/camera/share_image_contact_selection_components/select_show_time.dart b/lib/src/visual/views/camera/share_image_contact_selection_components/select_show_time.dart index a60618f2..2bf8b551 100644 --- a/lib/src/visual/views/camera/share_image_contact_selection_components/select_show_time.dart +++ b/lib/src/visual/views/camera/share_image_contact_selection_components/select_show_time.dart @@ -68,7 +68,7 @@ class _SelectShowTimeState extends State { Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Checkbox( + Checkbox.adaptive( value: _storeAsDefault, onChanged: (value) => setState(() { _storeAsDefault = !_storeAsDefault; diff --git a/lib/src/visual/views/camera/share_image_editor.view.dart b/lib/src/visual/views/camera/share_image_editor.view.dart index d09ad5e5..923f157a 100644 --- a/lib/src/visual/views/camera/share_image_editor.view.dart +++ b/lib/src/visual/views/camera/share_image_editor.view.dart @@ -717,11 +717,9 @@ class _ShareImageEditorView extends State { ? SizedBox( height: 12, width: 12, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, - color: Theme.of( - context, - ).colorScheme.inversePrimary, + valueColor: AlwaysStoppedAnimation(Theme.of(context).colorScheme.inversePrimary), ), ) : const FaIcon(FontAwesomeIcons.solidPaperPlane), diff --git a/lib/src/visual/views/camera/share_image_editor_components/layers/draw.layer.dart b/lib/src/visual/views/camera/share_image_editor_components/layers/draw.layer.dart index fe71acac..5f266195 100644 --- a/lib/src/visual/views/camera/share_image_editor_components/layers/draw.layer.dart +++ b/lib/src/visual/views/camera/share_image_editor_components/layers/draw.layer.dart @@ -172,7 +172,7 @@ class _DrawLayerState extends State { Positioned.fill( child: RotatedBox( quarterTurns: 1, - child: Slider( + child: Slider.adaptive( value: _sliderValue, thumbColor: currentColor, activeColor: Colors.transparent, diff --git a/lib/src/visual/views/camera/share_image_editor_components/layers/link_preview/cards/twitter.card.dart b/lib/src/visual/views/camera/share_image_editor_components/layers/link_preview/cards/twitter.card.dart index 0a076d64..8bdc763c 100644 --- a/lib/src/visual/views/camera/share_image_editor_components/layers/link_preview/cards/twitter.card.dart +++ b/lib/src/visual/views/camera/share_image_editor_components/layers/link_preview/cards/twitter.card.dart @@ -82,7 +82,7 @@ class TwitterPostCard extends StatelessWidget { height: 150, color: const Color(0xFFF5F8FA), child: const Center( - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, valueColor: AlwaysStoppedAnimation(twitterBlue), ), diff --git a/lib/src/visual/views/chats/chat_messages_components/entries/chat_ask_a_friend.entry.dart b/lib/src/visual/views/chats/chat_messages_components/entries/chat_ask_a_friend.entry.dart index d50655e9..83c31467 100644 --- a/lib/src/visual/views/chats/chat_messages_components/entries/chat_ask_a_friend.entry.dart +++ b/lib/src/visual/views/chats/chat_messages_components/entries/chat_ask_a_friend.entry.dart @@ -190,7 +190,7 @@ class _ChatAskAFriendEntryState extends State { child: SizedBox( width: 14, height: 14, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, ), ), @@ -302,7 +302,7 @@ class _ChatAskAFriendEntryState extends State { ? const SizedBox( width: 12, height: 12, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, ), ) diff --git a/lib/src/visual/views/chats/chat_messages_components/entries/chat_contacts.entry.dart b/lib/src/visual/views/chats/chat_messages_components/entries/chat_contacts.entry.dart index 6d02afb0..6ec0371e 100644 --- a/lib/src/visual/views/chats/chat_messages_components/entries/chat_contacts.entry.dart +++ b/lib/src/visual/views/chats/chat_messages_components/entries/chat_contacts.entry.dart @@ -191,7 +191,7 @@ class _ContactRowState extends State<_ContactRow> { const SizedBox( width: 16, height: 16, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, valueColor: AlwaysStoppedAnimation( Colors.white, diff --git a/lib/src/visual/views/chats/chat_messages_components/message_send_state_icon.dart b/lib/src/visual/views/chats/chat_messages_components/message_send_state_icon.dart index 9df84bbb..5beb4bec 100644 --- a/lib/src/visual/views/chats/chat_messages_components/message_send_state_icon.dart +++ b/lib/src/visual/views/chats/chat_messages_components/message_send_state_icon.dart @@ -76,7 +76,7 @@ class _MessageSendStateIconState extends State { SizedBox( width: 10, height: 10, - child: CircularProgressIndicator(strokeWidth: 1, color: color), + child: CircularProgressIndicator.adaptive(strokeWidth: 1, valueColor: AlwaysStoppedAnimation(color)), ), const SizedBox(width: 2), ], diff --git a/lib/src/visual/views/chats/media_viewer.view.dart b/lib/src/visual/views/chats/media_viewer.view.dart index eda8e12e..eaea72cd 100644 --- a/lib/src/visual/views/chats/media_viewer.view.dart +++ b/lib/src/visual/views/chats/media_viewer.view.dart @@ -540,7 +540,7 @@ class _MediaViewerViewState extends State { const SizedBox( width: 10, height: 10, - child: CircularProgressIndicator(strokeWidth: 1), + child: CircularProgressIndicator.adaptive(strokeWidth: 1), ) else imageSaved @@ -573,7 +573,7 @@ class _MediaViewerViewState extends State { ), ), ), - onPressed: () async { + onPressed: () { if (!showShortReactions) { displayShortReactions(); } else { diff --git a/lib/src/visual/views/chats/media_viewer_components/emoji_reactions_row.comp.dart b/lib/src/visual/views/chats/media_viewer_components/emoji_reactions_row.comp.dart index 98ded465..4b5884a8 100644 --- a/lib/src/visual/views/chats/media_viewer_components/emoji_reactions_row.comp.dart +++ b/lib/src/visual/views/chats/media_viewer_components/emoji_reactions_row.comp.dart @@ -67,26 +67,24 @@ class _EmojiReactionWidgetState extends State { @override Widget build(BuildContext context) { - return AnimatedSize( + return GestureDetector( key: _targetKey, - duration: const Duration(milliseconds: 200), - curve: Curves.linearToEaseOut, - child: GestureDetector( - onTap: () async { - await sendReaction(widget.groupId, widget.messageId, widget.emoji); - widget.emojiKey.currentState?.spawn( - getGlobalOffset(_targetKey), - widget.emoji, - ); - widget.hide(); - }, - child: SizedBox( - width: widget.show ? 40 : 10, - child: Center( - child: EmojiAnimationComp( - emoji: widget.emoji, - ), - ), + onTap: () async { + await sendReaction(widget.groupId, widget.messageId, widget.emoji); + widget.emojiKey.currentState?.spawn( + getGlobalOffset(_targetKey), + widget.emoji, + ); + widget.hide(); + }, + child: SizedBox( + width: 40, + child: Center( + child: widget.show + ? EmojiAnimationComp( + emoji: widget.emoji, + ) + : const SizedBox.shrink(), ), ), ); diff --git a/lib/src/visual/views/chats/media_viewer_components/reaction_buttons.comp.dart b/lib/src/visual/views/chats/media_viewer_components/reaction_buttons.comp.dart index 549f2af2..1bdffc4b 100644 --- a/lib/src/visual/views/chats/media_viewer_components/reaction_buttons.comp.dart +++ b/lib/src/visual/views/chats/media_viewer_components/reaction_buttons.comp.dart @@ -39,6 +39,7 @@ class ReactionButtons extends StatefulWidget { class _ReactionButtonsState extends State { int selectedShortReaction = -1; final GlobalKey _keyEmojiPicker = GlobalKey(); + bool _renderAnimations = false; List selectedEmojis = EmojiAnimationComp.animatedIcons.keys .toList() @@ -47,9 +48,28 @@ class _ReactionButtonsState extends State { @override void initState() { super.initState(); + _renderAnimations = widget.show; initAsync(); } + @override + void didUpdateWidget(ReactionButtons oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.show != oldWidget.show) { + if (widget.show) { + _renderAnimations = true; + } else { + Future.delayed(const Duration(milliseconds: 150), () { + if (mounted && !widget.show) { + setState(() { + _renderAnimations = false; + }); + } + }); + } + } + } + Future initAsync() async { if (userService.currentUser.preSelectedEmojies != null) { selectedEmojis = userService.currentUser.preSelectedEmojies!; @@ -71,91 +91,92 @@ class _ReactionButtonsState extends State { ? 50 : widget.mediaViewerDistanceFromBottom) : widget.mediaViewerDistanceFromBottom - 20, - left: widget.show ? 0 : MediaQuery.sizeOf(context).width / 2, - right: widget.show ? 0 : MediaQuery.sizeOf(context).width / 2, + left: 0, + right: 0, curve: Curves.linearToEaseOut, - child: AnimatedOpacity( - opacity: widget.show ? 1.0 : 0.0, // Fade in/out - duration: const Duration(milliseconds: 150), - child: Container( - color: widget.show ? Colors.black.withAlpha(0) : Colors.transparent, - padding: widget.show - ? const EdgeInsets.symmetric(vertical: 32) - : null, - child: Column( - children: [ - if (secondRowEmojis.isNotEmpty) + child: IgnorePointer( + ignoring: !widget.show, + child: AnimatedOpacity( + opacity: widget.show ? 1.0 : 0.0, // Fade in/out + duration: const Duration(milliseconds: 150), + child: Container( + color: widget.show ? Colors.black.withAlpha(0) : Colors.transparent, + padding: const EdgeInsets.symmetric(vertical: 32), + child: Column( + children: [ + if (secondRowEmojis.isNotEmpty) + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + crossAxisAlignment: CrossAxisAlignment.end, + children: secondRowEmojis + .map( + (emoji) => EmojiReactionWidget( + messageId: widget.messageId, + groupId: widget.groupId, + hide: widget.hide, + show: _renderAnimations, + emoji: emoji as String, + emojiKey: widget.emojiKey, + ), + ) + .toList(), + ), + if (secondRowEmojis.isNotEmpty) const SizedBox(height: 15), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.end, - children: secondRowEmojis - .map( - (emoji) => EmojiReactionWidget( - messageId: widget.messageId, - groupId: widget.groupId, - hide: widget.hide, - show: widget.show, - emoji: emoji as String, - emojiKey: widget.emojiKey, + children: [ + ...firstRowEmojis.map( + (emoji) => EmojiReactionWidget( + messageId: widget.messageId, + groupId: widget.groupId, + hide: widget.hide, + show: _renderAnimations, + emoji: emoji, + emojiKey: widget.emojiKey, + ), + ), + GestureDetector( + key: _keyEmojiPicker, + onTap: () async { + final layer = + // ignore: inference_failure_on_function_invocation + await showModalBottomSheet( + context: context, + backgroundColor: context.color.surface, + builder: (context) { + return const EmojiPickerBottom(); + }, + ) + as EmojiLayerData?; + if (layer == null) return; + await sendReaction( + widget.groupId, + widget.messageId, + layer.text, + ); + widget.emojiKey.currentState?.spawn( + getGlobalOffset(_keyEmojiPicker), + layer.text, + ); + widget.hide(); + }, + child: Container( + decoration: BoxDecoration( + color: context.color.surfaceContainer.withAlpha(100), + borderRadius: BorderRadius.circular(12), ), - ) - .toList(), + padding: const EdgeInsets.all(8), + child: const FaIcon( + FontAwesomeIcons.ellipsisVertical, + size: 24, + ), + ), + ), + ], ), - if (secondRowEmojis.isNotEmpty) const SizedBox(height: 15), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - ...firstRowEmojis.map( - (emoji) => EmojiReactionWidget( - messageId: widget.messageId, - groupId: widget.groupId, - hide: widget.hide, - show: widget.show, - emoji: emoji, - emojiKey: widget.emojiKey, - ), - ), - GestureDetector( - key: _keyEmojiPicker, - onTap: () async { - final layer = - // ignore: inference_failure_on_function_invocation - await showModalBottomSheet( - context: context, - backgroundColor: context.color.surface, - builder: (context) { - return const EmojiPickerBottom(); - }, - ) - as EmojiLayerData?; - if (layer == null) return; - await sendReaction( - widget.groupId, - widget.messageId, - layer.text, - ); - widget.emojiKey.currentState?.spawn( - getGlobalOffset(_keyEmojiPicker), - layer.text, - ); - widget.hide(); - }, - child: Container( - decoration: BoxDecoration( - color: context.color.surfaceContainer.withAlpha(100), - borderRadius: BorderRadius.circular(12), - ), - padding: const EdgeInsets.all(8), - child: const FaIcon( - FontAwesomeIcons.ellipsisVertical, - size: 24, - ), - ), - ), - ], - ), - ], + ], + ), ), ), ), diff --git a/lib/src/visual/views/contact/add_contact_via_qr_link.view.dart b/lib/src/visual/views/contact/add_contact_via_qr_link.view.dart index 50ce2c6a..00d86abb 100644 --- a/lib/src/visual/views/contact/add_contact_via_qr_link.view.dart +++ b/lib/src/visual/views/contact/add_contact_via_qr_link.view.dart @@ -129,7 +129,7 @@ class _AddContactViaQrLinkViewState extends State { ? const SizedBox( height: 20, width: 20, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, ), ) diff --git a/lib/src/visual/views/contact/add_new_contact.view.dart b/lib/src/visual/views/contact/add_new_contact.view.dart index 5c631673..94ea78e8 100644 --- a/lib/src/visual/views/contact/add_new_contact.view.dart +++ b/lib/src/visual/views/contact/add_new_contact.view.dart @@ -250,7 +250,7 @@ class _SearchUsernameView extends State { child: SizedBox( width: 18, height: 18, - child: CircularProgressIndicator(strokeWidth: 2), + child: CircularProgressIndicator.adaptive(strokeWidth: 2), ), ) else diff --git a/lib/src/visual/views/contact/add_new_contact_components/friend_suggestions.comp.dart b/lib/src/visual/views/contact/add_new_contact_components/friend_suggestions.comp.dart index 992d6cf5..2f00587c 100644 --- a/lib/src/visual/views/contact/add_new_contact_components/friend_suggestions.comp.dart +++ b/lib/src/visual/views/contact/add_new_contact_components/friend_suggestions.comp.dart @@ -112,7 +112,7 @@ class FriendSuggestionsComp extends StatelessWidget { final contact = f.$1; final isSelected = selectedFriends.contains(contact.userId); - return CheckboxListTile( + return CheckboxListTile.adaptive( contentPadding: EdgeInsets.zero, title: Text(contact.displayName ?? contact.username), value: isSelected, diff --git a/lib/src/visual/views/contact/contact_components/user_discovery_contact_settings.comp.dart b/lib/src/visual/views/contact/contact_components/user_discovery_contact_settings.comp.dart index c60d19c7..783f0c7c 100644 --- a/lib/src/visual/views/contact/contact_components/user_discovery_contact_settings.comp.dart +++ b/lib/src/visual/views/contact/contact_components/user_discovery_contact_settings.comp.dart @@ -52,7 +52,8 @@ class UserDiscoveryContactSettingsComp extends StatelessWidget { icon: FontAwesomeIcons.usersViewfinder, text: context.lang.userDiscoverySettingsTitle, onTap: () => context.navPush(const UserDiscoverySettingsView()), - subtitle: !contact.userDiscoveryExcluded && + subtitle: + !contact.userDiscoveryExcluded && contact.mediaSendCounter < userService.currentUser.requiredSendImages ? Text( @@ -66,7 +67,7 @@ class UserDiscoveryContactSettingsComp extends StatelessWidget { : null, trailing: Transform.scale( scale: 0.8, - child: Switch( + child: Switch.adaptive( value: !contact.userDiscoveryExcluded, onChanged: (a) async { await UserDiscoveryService.changeExclusionForContact( diff --git a/lib/src/visual/views/groups/group_create_select_group_name.view.dart b/lib/src/visual/views/groups/group_create_select_group_name.view.dart index 1bfc7132..774bcf44 100644 --- a/lib/src/visual/views/groups/group_create_select_group_name.view.dart +++ b/lib/src/visual/views/groups/group_create_select_group_name.view.dart @@ -68,7 +68,7 @@ class _GroupCreateSelectGroupNameViewState ? const SizedBox( width: 15, height: 15, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 1, ), ) diff --git a/lib/src/visual/views/groups/group_create_select_members.view.dart b/lib/src/visual/views/groups/group_create_select_members.view.dart index 42930b06..b46a3c90 100644 --- a/lib/src/visual/views/groups/group_create_select_members.view.dart +++ b/lib/src/visual/views/groups/group_create_select_members.view.dart @@ -223,7 +223,7 @@ class _StartNewChatView extends State { contactId: user.userId, fontSize: 13, ), - trailing: Checkbox( + trailing: Checkbox.adaptive( value: selectedUsers.contains(user.userId) | alreadyInGroup.contains(user.userId), diff --git a/lib/src/visual/views/memories/components/memory_thumbnail.comp.dart b/lib/src/visual/views/memories/components/memory_thumbnail.comp.dart index 9991370d..20f5a0de 100644 --- a/lib/src/visual/views/memories/components/memory_thumbnail.comp.dart +++ b/lib/src/visual/views/memories/components/memory_thumbnail.comp.dart @@ -2,9 +2,8 @@ import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:twonly/src/database/tables/mediafiles.table.dart'; import 'package:twonly/src/model/memory_item.model.dart'; -import 'package:twonly/src/utils/misc.dart'; +import 'package:twonly/src/visual/components/selectable_thumbnail.comp.dart'; import 'package:twonly/src/visual/views/memories/components/memory_transition_painter.dart'; - class MemoriesThumbnailComp extends StatefulWidget { const MemoriesThumbnailComp({ required this.galleryItem, @@ -166,115 +165,60 @@ class _MemoriesThumbnailCompState extends State scale: _scaleAnimation, child: FadeTransition( opacity: _scaleController, - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - curve: Curves.easeInOut, - decoration: BoxDecoration( - color: widget.isSelected - ? context.color.primary - : Colors.transparent, - boxShadow: const [ - BoxShadow( - color: Colors.black12, - blurRadius: 4, - offset: Offset(0, 2), - ), - ], - ), - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - curve: Curves.easeInOut, - margin: EdgeInsets.all(widget.isSelected ? 4 : 0), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular( - widget.isSelected ? 12 : 0, - ), - ), - clipBehavior: Clip.antiAlias, - child: Stack( - fit: StackFit.expand, - children: [ - if (cachedInfo != null) - RawImage( - image: cachedInfo.image, - fit: BoxFit.cover, - ) - else if (_imageProvider != null) - Image( - image: _imageProvider!, - fit: BoxFit.cover, - gaplessPlayback: true, - ) - else - ColoredBox( - color: Colors.grey.shade200, - child: const Center( - child: FaIcon( - FontAwesomeIcons.image, - color: Colors.black26, - ), + child: SelectableThumbnailComp( + isSelected: widget.isSelected, + selectionMode: widget.selectionMode, + child: Stack( + fit: StackFit.expand, + children: [ + if (cachedInfo != null) + RawImage( + image: cachedInfo.image, + fit: BoxFit.cover, + ) + else if (_imageProvider != null) + Image( + image: _imageProvider!, + fit: BoxFit.cover, + gaplessPlayback: true, + ) + else + ColoredBox( + color: Colors.grey.shade200, + child: const Center( + child: FaIcon( + FontAwesomeIcons.image, + color: Colors.black26, ), ), - - if (isVideo) - const Positioned.fill( - child: Center( - child: FaIcon( - FontAwesomeIcons.circlePlay, - color: Colors.white, - size: 32, - shadows: [ - Shadow(color: Colors.black54, blurRadius: 6), - ], - ), - ), - ), - - if (widget.selectionMode) - Positioned( - top: 6, - right: 6, - child: Container( - padding: const EdgeInsets.all(2), - decoration: BoxDecoration( - color: widget.isSelected - ? context.color.primary - : Colors.black38, - shape: BoxShape.circle, - border: Border.all( - color: - Theme.of(context).brightness == - Brightness.dark - ? Colors.white - : Colors.black, - width: 1.5, - ), - ), - child: widget.isSelected - ? const Icon( - Icons.check, - size: 14, - color: Colors.white, - ) - : const SizedBox(width: 14, height: 14), - ), - ), - - if (media.mediaFile.isFavorite) - const Positioned( - bottom: 6, - left: 6, - child: Icon( - Icons.favorite, - color: Colors.redAccent, - size: 16, + ), + if (isVideo) + const Positioned.fill( + child: Center( + child: FaIcon( + FontAwesomeIcons.circlePlay, + color: Colors.white, + size: 32, shadows: [ - Shadow(color: Colors.black54, blurRadius: 4), + Shadow(color: Colors.black54, blurRadius: 6), ], ), ), - ], - ), + ), + if (media.mediaFile.isFavorite) + const Positioned( + bottom: 6, + left: 6, + child: Icon( + Icons.favorite, + color: Colors.redAccent, + size: 16, + shadows: [ + Shadow(color: Colors.black54, blurRadius: 4), + ], + ), + ), + ], ), ), ), diff --git a/lib/src/visual/views/memories/components/synchronized_viewer_actions_toolbar.comp.dart b/lib/src/visual/views/memories/components/synchronized_viewer_actions_toolbar.comp.dart index 717067c3..1f786fbd 100644 --- a/lib/src/visual/views/memories/components/synchronized_viewer_actions_toolbar.comp.dart +++ b/lib/src/visual/views/memories/components/synchronized_viewer_actions_toolbar.comp.dart @@ -40,9 +40,9 @@ class SynchronizedViewerActionsToolbarComp extends StatelessWidget { ? const SizedBox( width: 16, height: 16, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, - color: Colors.white, + valueColor: AlwaysStoppedAnimation(Colors.white), ), ) : const FaIcon( diff --git a/lib/src/visual/views/memories/memories.view.dart b/lib/src/visual/views/memories/memories.view.dart index 1a19c44b..12e47292 100644 --- a/lib/src/visual/views/memories/memories.view.dart +++ b/lib/src/visual/views/memories/memories.view.dart @@ -198,7 +198,7 @@ class MemoriesViewState extends State { final confirmed = await showAlertDialog( context, context.lang.deleteImageTitle, - context.lang.deleteImageBody, + context.lang.deleteMemoriesBody(count), ); if (!confirmed) return; @@ -219,7 +219,7 @@ class MemoriesViewState extends State { if (!mounted) return; showSnackbar( context, - 'Deleted $count items successfully', + context.lang.memoriesDeleteSnackbarSuccess(count), level: SnackbarLevel.success, ); } @@ -239,7 +239,7 @@ class MemoriesViewState extends State { } else if (media.mediaFile.type == MediaType.image || media.mediaFile.type == MediaType.gif) { final imageBytes = await media.storedPath.readAsBytes(); - await saveImageToGallery(imageBytes); + await saveImageToGallery(imageBytes, createdAt: media.mediaFile.createdAt); } } } @@ -354,7 +354,7 @@ class MemoriesViewState extends State { controller: _scrollController, labelBuilder: (offset) { final state = _service.currentState; - if (state.isEmpty) return null; + if (state.isEmpty || state.months.isEmpty) return null; // Simple heuristic to find month by offset double currentOffset = 56; @@ -409,7 +409,9 @@ class MemoriesViewState extends State { child: CircularProgressIndicator( value: state.migrationProgress, strokeWidth: 2.5, - color: context.color.primary, + valueColor: AlwaysStoppedAnimation( + context.color.primary, + ), backgroundColor: context.color.primary .withValues(alpha: 0.2), ), @@ -487,8 +489,10 @@ class MemoriesViewState extends State { ), ), ], - const SliverPadding( - padding: EdgeInsets.only(bottom: 32), + SliverPadding( + padding: EdgeInsets.only( + bottom: MediaQuery.of(context).padding.bottom + 150, + ), ), ], ), diff --git a/lib/src/visual/views/memories/synchronized_viewer.view.dart b/lib/src/visual/views/memories/synchronized_viewer.view.dart index b7ebc2b8..19ec6f65 100644 --- a/lib/src/visual/views/memories/synchronized_viewer.view.dart +++ b/lib/src/visual/views/memories/synchronized_viewer.view.dart @@ -197,7 +197,7 @@ class _SynchronizedImageViewerScreenState } else if (item.mediaFile.type == MediaType.image || item.mediaFile.type == MediaType.gif) { final imageBytes = await item.storedPath.readAsBytes(); - await saveImageToGallery(imageBytes); + await saveImageToGallery(imageBytes, createdAt: item.mediaFile.createdAt); } if (!mounted) return; showSnackbar( diff --git a/lib/src/visual/views/onboarding/recover.view.dart b/lib/src/visual/views/onboarding/recover.view.dart index 71ec9f58..39f239cd 100644 --- a/lib/src/visual/views/onboarding/recover.view.dart +++ b/lib/src/visual/views/onboarding/recover.view.dart @@ -219,8 +219,8 @@ class _BackupRecoveryViewState extends State { ? const SizedBox( height: 24, width: 24, - child: CircularProgressIndicator( - color: Colors.white, + child: CircularProgressIndicator.adaptive( + valueColor: AlwaysStoppedAnimation(Colors.white), strokeWidth: 3, ), ) diff --git a/lib/src/visual/views/onboarding/register.view.dart b/lib/src/visual/views/onboarding/register.view.dart index 570456c7..5f1ca260 100644 --- a/lib/src/visual/views/onboarding/register.view.dart +++ b/lib/src/visual/views/onboarding/register.view.dart @@ -299,8 +299,8 @@ class _RegisterViewState extends State { ? const SizedBox( width: 24, height: 24, - child: CircularProgressIndicator( - color: Colors.white, + child: CircularProgressIndicator.adaptive( + valueColor: AlwaysStoppedAnimation(Colors.white), strokeWidth: 3, ), ) diff --git a/lib/src/visual/views/onboarding/setup/components/next_button.comp.dart b/lib/src/visual/views/onboarding/setup/components/next_button.comp.dart index 36962bc9..7a23e134 100644 --- a/lib/src/visual/views/onboarding/setup/components/next_button.comp.dart +++ b/lib/src/visual/views/onboarding/setup/components/next_button.comp.dart @@ -49,7 +49,7 @@ class NextButtonComp extends StatelessWidget { ? const SizedBox( height: 24, width: 24, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, valueColor: AlwaysStoppedAnimation(Colors.white), ), diff --git a/lib/src/visual/views/onboarding/setup/components/setup_switch_card.comp.dart b/lib/src/visual/views/onboarding/setup/components/setup_switch_card.comp.dart index 168a9a98..8dfa6664 100644 --- a/lib/src/visual/views/onboarding/setup/components/setup_switch_card.comp.dart +++ b/lib/src/visual/views/onboarding/setup/components/setup_switch_card.comp.dart @@ -28,7 +28,7 @@ class SetupSwitchCard extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - SwitchListTile( + SwitchListTile.adaptive( value: value, onChanged: onChanged, title: Text( diff --git a/lib/src/visual/views/recovery.view.dart b/lib/src/visual/views/recovery.view.dart index 0708262d..c9d683c2 100644 --- a/lib/src/visual/views/recovery.view.dart +++ b/lib/src/visual/views/recovery.view.dart @@ -127,7 +127,7 @@ class _RecoveryViewState extends State { ? const SizedBox( height: 16, width: 16, - child: CircularProgressIndicator(strokeWidth: 2), + child: CircularProgressIndicator.adaptive(strokeWidth: 2), ) : const Icon(Icons.restore_rounded), style: FilledButton.styleFrom( diff --git a/lib/src/visual/views/settings/appearance.view.dart b/lib/src/visual/views/settings/appearance.view.dart index 84555e36..e01051be 100644 --- a/lib/src/visual/views/settings/appearance.view.dart +++ b/lib/src/visual/views/settings/appearance.view.dart @@ -115,7 +115,7 @@ class _AppearanceViewState extends State { ListTile( title: Text(context.lang.contactUsShortcut), onTap: toggleShowFeedbackIcon, - trailing: Switch( + trailing: Switch.adaptive( value: !userService.currentUser.showFeedbackShortcut, onChanged: (a) => toggleShowFeedbackIcon(), ), @@ -123,7 +123,7 @@ class _AppearanceViewState extends State { ListTile( title: Text(context.lang.startWithCameraOpen), onTap: toggleStartWithCameraOpen, - trailing: Switch( + trailing: Switch.adaptive( value: userService.currentUser.startWithCameraOpen, onChanged: (a) => toggleStartWithCameraOpen(), ), @@ -131,7 +131,7 @@ class _AppearanceViewState extends State { ListTile( title: Text(context.lang.showImagePreviewWhenSending), onTap: toggleShowImagePreviewWhenSending, - trailing: Switch( + trailing: Switch.adaptive( value: userService.currentUser.showShowImagePreviewWhenSending, onChanged: (a) => toggleShowImagePreviewWhenSending(), diff --git a/lib/src/visual/views/settings/backup/backup_setup.view.dart b/lib/src/visual/views/settings/backup/backup_setup.view.dart index 4b00e45e..2eb9638c 100644 --- a/lib/src/visual/views/settings/backup/backup_setup.view.dart +++ b/lib/src/visual/views/settings/backup/backup_setup.view.dart @@ -144,7 +144,7 @@ class _SetupBackupViewState extends State { ? const SizedBox( height: 12, width: 12, - child: CircularProgressIndicator(strokeWidth: 1), + child: CircularProgressIndicator.adaptive(strokeWidth: 1), ) : const Icon(Icons.lock_clock_rounded), label: Text( diff --git a/lib/src/visual/views/settings/chat/chat_settings.view.dart b/lib/src/visual/views/settings/chat/chat_settings.view.dart index 56c1a66b..f9ebc006 100644 --- a/lib/src/visual/views/settings/chat/chat_settings.view.dart +++ b/lib/src/visual/views/settings/chat/chat_settings.view.dart @@ -39,7 +39,7 @@ class _ChatSettingsViewState extends State { title: Text(context.lang.settingsPreSelectedReactions), onTap: () => context.push(Routes.settingsChatsReactions), ), - SwitchListTile( + SwitchListTile.adaptive( title: Text( context .lang diff --git a/lib/src/visual/views/settings/data_and_storage.view.dart b/lib/src/visual/views/settings/data_and_storage.view.dart index 16a38c1d..161adfe2 100644 --- a/lib/src/visual/views/settings/data_and_storage.view.dart +++ b/lib/src/visual/views/settings/data_and_storage.view.dart @@ -1,6 +1,4 @@ import 'dart:async'; -import 'dart:io'; - import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; @@ -39,6 +37,35 @@ class _DataAndStorageViewState extends State { } Future toggleStoreInGallery() async { + final currentlyEnabled = userService.currentUser.storeMediaFilesInGallery; + if (currentlyEnabled) { + final confirm = await showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text(context.lang.galleryDisableWarningTitle), + content: Text(context.lang.galleryDisableWarningBody), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(context.lang.cancel), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text( + context.lang.galleryDisableWarningConfirm, + style: const TextStyle(color: Colors.red), + ), + ), + ], + ); + }, + ); + if (confirm != true) { + return; + } + } + await UserService.update((u) { u.storeMediaFilesInGallery = !u.storeMediaFilesInGallery; }); @@ -83,11 +110,8 @@ class _DataAndStorageViewState extends State { const Divider(), ListTile( title: Text(context.lang.settingsStorageDataStoreInGTitle), - subtitle: Text( - context.lang.settingsStorageDataStoreInGSubtitle, - ), onTap: toggleStoreInGallery, - trailing: Switch( + trailing: Switch.adaptive( value: userService.currentUser.storeMediaFilesInGallery, onChanged: (a) => toggleStoreInGallery(), ), @@ -99,27 +123,19 @@ class _DataAndStorageViewState extends State { style: const TextStyle(fontSize: 9), ), onTap: toggleAutoStoreMediaFiles, - trailing: Switch( + trailing: Switch.adaptive( value: userService .currentUser .autoStoreAllSendUnlimitedMediaFiles, onChanged: (a) => toggleAutoStoreMediaFiles(), ), ), - if (Platform.isAndroid) - ListTile( - title: Text( - context.lang.exportMemories, - ), - onTap: () => context.push(Routes.settingsStorageExport), - ), - if (Platform.isAndroid) - ListTile( - title: Text( - context.lang.importMemories, - ), - onTap: () => context.push(Routes.settingsStorageImport), - ), + ListTile( + title: Text(context.lang.settingsStorageScanGalleryTitle), + onTap: () { + context.push(Routes.settingsStorageImportGallery); + }, + ), const Divider(), ListTile( title: Text( @@ -197,7 +213,7 @@ class _AutoDownloadOptionsDialogState extends State { content: Column( mainAxisSize: MainAxisSize.min, children: [ - CheckboxListTile( + CheckboxListTile.adaptive( title: const Text('Image'), value: autoDownloadOptions[widget.connectionMode.name]!.contains( DownloadMediaTypes.image.name, @@ -206,7 +222,7 @@ class _AutoDownloadOptionsDialogState extends State { await _updateAutoDownloadSetting(DownloadMediaTypes.image, value); }, ), - CheckboxListTile( + CheckboxListTile.adaptive( title: const Text('Video'), value: autoDownloadOptions[widget.connectionMode.name]!.contains( DownloadMediaTypes.video.name, diff --git a/lib/src/visual/views/settings/data_and_storage/export_media.view.dart b/lib/src/visual/views/settings/data_and_storage/export_media.view.dart deleted file mode 100644 index f5e3aeca..00000000 --- a/lib/src/visual/views/settings/data_and_storage/export_media.view.dart +++ /dev/null @@ -1,213 +0,0 @@ -import 'dart:io'; - -import 'package:archive/archive_io.dart'; -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:path/path.dart' as p; -import 'package:path_provider/path_provider.dart'; -import 'package:twonly/globals.dart'; -import 'package:twonly/src/services/mediafiles/mediafile.service.dart'; -import 'package:twonly/src/utils/log.dart'; - -class AndroidMediaStore { - static const androidMediaStoreChannel = MethodChannel('eu.twonly/mediaStore'); - - static Future safeFileToDownload(File sourceFile) async { - try { - Log.info('Storing $sourceFile'); - final storedPath = ( - await androidMediaStoreChannel.invokeMethod('safeFileToDownload', { - 'sourceFile': sourceFile.path, - }), - ); - Log.info(storedPath); - return true; - } catch (e) { - Log.error(e); - return false; - } - } -} - -class ExportMediaView extends StatefulWidget { - const ExportMediaView({super.key}); - - @override - State createState() => _ExportMediaViewState(); -} - -class _ExportMediaViewState extends State { - double _progress = 0; - String? _status; - File? _zipFile; - bool _isZipping = false; - bool _zipSaved = false; - bool _isStoring = false; - - Directory _mediaFolder() { - final dir = MediaFileService.buildDirectoryPath( - 'stored', - AppEnvironment.supportDir, - ); - if (!dir.existsSync()) dir.createSync(recursive: true); - return dir; - } - - Future _createZipFromMediaFolder() async { - setState(() { - _isZipping = true; - _progress = 0.0; - _status = 'Preparing...'; - _zipFile = null; - }); - - try { - final folder = _mediaFolder(); - final allFiles = folder - .listSync(recursive: true) - .whereType() - .toList(); - - final mediaFiles = allFiles.where((f) { - final name = p.basename(f.path).toLowerCase(); - if (name.contains('thumbnail')) return false; - return true; - }).toList(); - - if (mediaFiles.isEmpty) { - setState(() { - _status = 'No memories found.'; - _isZipping = false; - }); - return; - } - - // compute total bytes for progress - var totalBytes = 0; - for (final f in mediaFiles) { - totalBytes += await f.length(); - } - - final tempDir = await getTemporaryDirectory(); - final zipPath = p.join( - tempDir.path, - 'memories.zip', - ); - final encoder = ZipFileEncoder()..create(zipPath); - - var processedBytes = 0; - for (final f in mediaFiles) { - final relative = p.relative(f.path, from: folder.path); - setState(() { - _status = 'Adding $relative'; - }); - - await encoder.addFile(f, relative); - - processedBytes += await f.length(); - setState(() { - _progress = totalBytes > 0 ? processedBytes / totalBytes : 0.0; - }); - - await Future.delayed( - const Duration(milliseconds: 10), - ); - } - - await encoder.close(); - - setState(() { - _zipFile = File(zipPath); - _status = 'ZIP created: ${p.basename(zipPath)}'; - _progress = 1.0; - _isZipping = false; - }); - } catch (e) { - setState(() { - _status = 'Error: $e'; - _isZipping = false; - }); - } - } - - Future _saveZip() async { - if (_zipFile == null) return; - setState(() { - _isStoring = true; - }); - try { - if (Platform.isAndroid) { - if (!await AndroidMediaStore.safeFileToDownload(_zipFile!)) { - return; - } - } else { - final outputFile = await FilePicker.platform.saveFile( - dialogTitle: 'Save your memories to desired location', - fileName: p.basename(_zipFile!.path), - bytes: _zipFile!.readAsBytesSync(), - ); - if (outputFile == null) return; - } - _zipSaved = true; - _isStoring = false; - _status = 'ZIP stored: ${p.basename(_zipFile!.path)}'; - setState(() {}); - } catch (e) { - _isStoring = false; - setState(() => _status = 'Save failed: $e'); - } - } - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: const Text('Export memories'), - ), - body: Container( - margin: const EdgeInsets.all(24), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Text( - 'Here, you can export all you memories.', - textAlign: TextAlign.center, - style: TextStyle( - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 24), - if (_isZipping || _zipFile != null) - LinearProgressIndicator( - value: _isZipping ? _progress : (_zipFile != null ? 1.0 : 0.0), - ), - const SizedBox(height: 8), - if (_status != null) - Text( - _status!, - textAlign: TextAlign.center, - ), - const SizedBox(height: 24), - if (_zipFile == null) - ElevatedButton.icon( - icon: const Icon(Icons.archive), - label: Text( - _isZipping ? 'Zipping...' : 'Create ZIP from mediafiles', - ), - onPressed: _isZipping ? null : _createZipFromMediaFolder, - ) - else if (!_zipSaved) - ElevatedButton.icon( - icon: const Icon(Icons.save_alt), - label: const Text('Save ZIP'), - onPressed: (_zipFile != null && !_isZipping && !_isStoring) - ? _saveZip - : null, - ), - ], - ), - ), - ); - } -} diff --git a/lib/src/visual/views/settings/data_and_storage/import_from_gallery.view.dart b/lib/src/visual/views/settings/data_and_storage/import_from_gallery.view.dart new file mode 100644 index 00000000..d2d9b96d --- /dev/null +++ b/lib/src/visual/views/settings/data_and_storage/import_from_gallery.view.dart @@ -0,0 +1,761 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:drift/drift.dart' show Value; +import 'package:exif/exif.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:photo_manager/photo_manager.dart'; +import 'package:twonly/locator.dart'; +import 'package:twonly/src/database/tables/mediafiles.table.dart'; +import 'package:twonly/src/database/twonly.db.dart'; +import 'package:twonly/src/services/android_photo_picker.service.dart'; +import 'package:twonly/src/services/mediafiles/mediafile.service.dart'; +import 'package:twonly/src/utils/misc.dart' show ShortCutsExtension, sha256File; +import 'package:twonly/src/visual/components/selectable_thumbnail.comp.dart'; +import 'package:twonly/src/visual/components/snackbar.dart'; +import 'package:twonly/src/visual/themes/light.dart'; + +class ImportFromGalleryView extends StatefulWidget { + const ImportFromGalleryView({super.key}); + + @override + State createState() => _ImportFromGalleryViewState(); +} + +class _ImportFromGalleryViewState extends State { + bool _isLoading = true; + bool _isImporting = false; + String? _errorMessage; + bool _hasPermission = false; + List _assets = []; + final Set _selectedAssetIds = {}; + bool _showingAllImages = false; + double _importProgress = 0; + String _importStatus = ''; + + @override + void initState() { + super.initState(); + if (Platform.isAndroid) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _launchAndroidPicker(); + }); + } else { + _checkPermissionAndLoad(); + } + } + + Future _launchAndroidPicker() async { + final uris = await AndroidPhotoPickerService.pickImages(); + if (uris.isEmpty) { + if (mounted) Navigator.pop(context); + return; + } + + setState(() { + _isImporting = true; + _importProgress = 0; + _importStatus = context.lang.importGalleryStarting; + }); + + final total = uris.length; + var importedCount = 0; + var duplicated = 0; + var failedCount = 0; + + for (final uri in uris) { + try { + setState(() { + _importStatus = context.lang.importGalleryImportingOf( + importedCount + failedCount + 1, + total, + ); + _importProgress = (importedCount + failedCount) / total; + }); + + final bytes = await AndroidPhotoPickerService.getUriBytes(uri); + if (bytes == null) { + failedCount++; + continue; + } + + final hash = Uint8List.fromList(sha256.convert(bytes).bytes); + + final exsits = await twonlyDB.mediaFilesDao.getMediaByHash(hash); + if (exsits.isNotEmpty) { + duplicated += 1; + continue; + } + + // Try to get time from EXIF bytes, fallback to current time + final createdAt = + await getCreationTimeFromBytes(bytes) ?? DateTime.now(); + + const type = MediaType.image; + + final mediaFile = await twonlyDB.mediaFilesDao.insertOrUpdateMedia( + MediaFilesCompanion( + type: const Value(type), + createdAt: Value(createdAt), + storedFileHash: Value(hash), + stored: const Value(true), + ), + ); + + if (mediaFile != null) { + final mediaService = MediaFileService(mediaFile); + await mediaService.storedPath.parent.create(recursive: true); + await File(mediaService.storedPath.path).writeAsBytes(bytes); + + await mediaService.calculateAndSaveSize(); + await mediaService.createThumbnail(); + unawaited(mediaService.cropTransparentBorders()); + + importedCount++; + } else { + failedCount++; + } + } catch (e) { + failedCount++; + } + } + + if (mounted) { + setState(() { + _isImporting = false; + _importProgress = 1; + }); + showSnackbar( + context, + context.lang.importGalleryComplete( + importedCount, + duplicated, + failedCount, + ), + level: SnackbarLevel.success, + ); + Navigator.pop(context, true); + } + } + + Future _checkPermissionAndLoad() async { + setState(() { + _isLoading = true; + _errorMessage = null; + }); + + try { + final ps = await PhotoManager.requestPermissionExtend(); + if (ps.isAuth || ps.hasAccess) { + setState(() { + _hasPermission = true; + }); + await _loadMedia(); + } else { + setState(() { + _hasPermission = false; + _isLoading = false; + _errorMessage = context.lang.importGalleryPermissionRequired; + }); + } + } catch (e) { + setState(() { + _isLoading = false; + _errorMessage = context.lang.importGalleryPermissionError(e.toString()); + }); + } + } + + Future _loadMedia() async { + setState(() { + _isLoading = true; + _errorMessage = null; + }); + try { + if (_showingAllImages) { + final albums = await PhotoManager.getAssetPathList(onlyAll: true); + if (albums.isEmpty) { + setState(() { + _assets = []; + _isLoading = false; + }); + return; + } + final recentAlbum = albums.first; + final count = await recentAlbum.assetCountAsync; + final assets = await recentAlbum.getAssetListRange( + start: 0, + end: count, + ); + + setState(() { + _assets = assets; + _isLoading = false; + }); + } else { + final albums = await PhotoManager.getAssetPathList(); + + AssetPathEntity? twonlyAlbum; + for (final album in albums) { + if (album.name.toLowerCase() == 'twonly') { + twonlyAlbum = album; + break; + } + } + + if (twonlyAlbum == null) { + setState(() { + _assets = []; + _isLoading = false; + }); + return; + } + + final count = await twonlyAlbum.assetCountAsync; + final assets = await twonlyAlbum.getAssetListRange( + start: 0, + end: count, + ); + + setState(() { + _assets = assets; + _isLoading = false; + }); + } + } catch (e) { + setState(() { + _errorMessage = context.lang.importGalleryLoadError(e.toString()); + _isLoading = false; + }); + } + } + + Future getImageCreationTime(AssetEntity asset, File file) async { + final dates = [asset.createDateTime]; + + if (!file.existsSync()) { + return asset.createDateTime; + } + + // Read the EXIF data + try { + final bytes = await file.readAsBytes(); + final data = await readExifFromBytes(bytes); + + for (final key in data.keys) { + if (key.toLowerCase().contains('datetime') || key.contains('Time')) { + final time = data[key]?.printable; + if (time != null) { + try { + dates.add( + DateFormat('yyyy:MM:dd HH:mm:ss').parse(time), + ); + } catch (e) { + // Ignore unparseable formats + } + } + } + } + } catch (e) { + // Ignore EXIF reading errors + } + + // Return the oldest available date + return dates.reduce((a, b) => a.isBefore(b) ? a : b); + } + + Future getCreationTimeFromBytes(Uint8List bytes) async { + final dates = []; + + try { + final data = await readExifFromBytes(bytes); + + for (final key in data.keys) { + if (key.toLowerCase().contains('datetime') || key.contains('Time')) { + final time = data[key]?.printable; + if (time != null) { + try { + dates.add( + DateFormat('yyyy:MM:dd HH:mm:ss').parse(time), + ); + } catch (e) { + // Ignore unparseable formats + } + } + } + } + } catch (e) { + // Ignore EXIF reading errors + } + + if (dates.isEmpty) return null; + + // Return the oldest available date + return dates.reduce((a, b) => a.isBefore(b) ? a : b); + } + + void _toggleSelectAll() { + setState(() { + if (_selectedAssetIds.length == _assets.length) { + _selectedAssetIds.clear(); + } else { + _selectedAssetIds.clear(); + for (final asset in _assets) { + _selectedAssetIds.add(asset.id); + } + } + }); + } + + Future _startImport() async { + if (_selectedAssetIds.isEmpty) return; + + setState(() { + _isImporting = true; + _importProgress = 0; + _importStatus = context.lang.importGalleryStarting; + }); + + final selectedAssets = _assets + .where((a) => _selectedAssetIds.contains(a.id)) + .toList(); + final total = selectedAssets.length; + var importedCount = 0; + var duplicated = 0; + var failedCount = 0; + + for (final asset in selectedAssets) { + try { + setState(() { + _importStatus = context.lang.importGalleryImportingOf( + importedCount + failedCount + 1, + total, + ); + _importProgress = (importedCount + failedCount) / total; + }); + + final file = await asset.file; + if (file == null || !file.existsSync()) { + failedCount++; + continue; + } + + final hash = Uint8List.fromList(await sha256File(file)); + + final exsits = await twonlyDB.mediaFilesDao.getMediaByHash(hash); + if (exsits.isNotEmpty) { + duplicated += 1; + continue; + } + + final createdAt = await getImageCreationTime(asset, file); + + // Determine media type + late final MediaType type; + if (asset.type == AssetType.video) { + type = MediaType.video; + } else if (file.path.toLowerCase().endsWith('.gif')) { + type = MediaType.gif; + } else { + type = MediaType.image; + } + + final mediaFile = await twonlyDB.mediaFilesDao.insertOrUpdateMedia( + MediaFilesCompanion( + type: Value(type), + createdAt: Value(createdAt), + storedFileHash: Value(hash), + stored: const Value(true), + ), + ); + + if (mediaFile != null) { + final mediaService = MediaFileService(mediaFile); + await mediaService.storedPath.parent.create(recursive: true); + await file.copy(mediaService.storedPath.path); + + await mediaService.calculateAndSaveSize(); + await mediaService.createThumbnail(); + unawaited(mediaService.cropTransparentBorders()); + + importedCount++; + } else { + failedCount++; + } + } catch (e) { + failedCount++; + } + } + + setState(() { + _isImporting = false; + }); + + if (mounted) { + showSnackbar( + context, + context.lang.importGalleryComplete( + importedCount, + duplicated, + failedCount, + ), + level: SnackbarLevel.success, + ); + Navigator.of(context).pop(); + } + } + + @override + Widget build(BuildContext context) { + final isAllSelected = + _assets.isNotEmpty && _selectedAssetIds.length == _assets.length; + + return Scaffold( + extendBody: true, + appBar: AppBar( + title: Text(context.lang.settingsStorageScanGalleryTitle), + actions: [ + if (!_isLoading && _assets.isNotEmpty && !_isImporting) + IconButton( + icon: Icon( + isAllSelected ? Icons.deselect : Icons.select_all, + color: Theme.of(context).colorScheme.primary, + ), + tooltip: isAllSelected + ? context.lang.importGalleryDeselectAll + : context.lang.importGallerySelectAll, + onPressed: _toggleSelectAll, + ), + ], + ), + body: Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (!_isLoading && !_isImporting && _hasPermission) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + decoration: BoxDecoration( + color: Theme.of(context).cardColor, + border: Border( + bottom: BorderSide( + color: Theme.of( + context, + ).dividerColor.withValues(alpha: 0.1), + ), + ), + ), + child: Row( + children: [ + Expanded( + child: Text( + context.lang.importGalleryFilterTwonly, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w500, + ), + ), + ), + Switch.adaptive( + value: !_showingAllImages, + onChanged: (value) { + setState(() { + _showingAllImages = !value; + _selectedAssetIds.clear(); + }); + _loadMedia(); + }, + ), + ], + ), + ), + Expanded(child: _buildBody()), + ], + ), + if (_isImporting) _buildImportingOverlay(), + ], + ), + bottomNavigationBar: + _assets.isEmpty || + _isLoading || + _isImporting || + _selectedAssetIds.isEmpty + ? null + : SafeArea( + child: Padding( + padding: const EdgeInsets.all(16), + child: ElevatedButton( + style: primaryColorButtonStyle, + onPressed: _startImport, + child: Text( + _selectedAssetIds.isEmpty + ? context.lang.importGallerySelectToImport + : context.lang.importGalleryImportCount( + _selectedAssetIds.length, + ), + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ), + ); + } + + Widget _buildBody() { + if (_isLoading) { + return const Center(child: CircularProgressIndicator.adaptive()); + } + + if (!_hasPermission) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon( + Icons.photo_library_outlined, + size: 64, + color: Colors.grey, + ), + const SizedBox(height: 16), + Text( + _errorMessage ?? context.lang.importGalleryPermissionDenied, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 16), + ), + const SizedBox(height: 24), + ElevatedButton( + onPressed: _checkPermissionAndLoad, + child: Text(context.lang.importGalleryGrantAccess), + ), + const SizedBox(height: 8), + TextButton( + onPressed: PhotoManager.openSetting, + child: Text(context.lang.importGalleryOpenSettings), + ), + ], + ), + ), + ); + } + + if (_errorMessage != null) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.error_outline, size: 64, color: Colors.red), + const SizedBox(height: 16), + Text( + _errorMessage!, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 16), + ), + const SizedBox(height: 24), + ElevatedButton( + onPressed: _checkPermissionAndLoad, + child: Text(context.lang.importGalleryTryAgain), + ), + ], + ), + ), + ); + } + + if (_assets.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon( + Icons.photo_album_outlined, + size: 64, + color: Colors.grey, + ), + const SizedBox(height: 16), + Text( + _showingAllImages + ? context.lang.importGalleryNoImagesFound + : context.lang.importGalleryAlbumNotFound, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Text( + _showingAllImages + ? context.lang.importGalleryNoImagesFoundDesc + : context.lang.importGalleryAlbumNotFoundDesc, + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.grey), + ), + const SizedBox(height: 24), + ElevatedButton( + onPressed: _checkPermissionAndLoad, + child: Text(context.lang.importGalleryRefresh), + ), + ], + ), + ), + ); + } + + return GridView.builder( + padding: EdgeInsets.fromLTRB( + 4, + 4, + 4, + MediaQuery.of(context).padding.bottom + 80, + ), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 4, + mainAxisSpacing: 2, + crossAxisSpacing: 2, + childAspectRatio: 9 / 16, + ), + itemCount: _assets.length, + itemBuilder: (context, index) { + final asset = _assets[index]; + final isSelected = _selectedAssetIds.contains(asset.id); + return GalleryThumbnailWidget( + asset: asset, + isSelected: isSelected, + onTap: () { + setState(() { + if (isSelected) { + _selectedAssetIds.remove(asset.id); + } else { + _selectedAssetIds.add(asset.id); + } + }); + }, + ); + }, + ); + } + + Widget _buildImportingOverlay() { + return ColoredBox( + color: Colors.black54, + child: Center( + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 32), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Theme.of(context).cardColor, + borderRadius: BorderRadius.circular(16), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircularProgressIndicator.adaptive(), + const SizedBox(height: 24), + Text( + _importStatus, + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 16), + LinearProgressIndicator(value: _importProgress), + ], + ), + ), + ), + ); + } +} + +class GalleryThumbnailWidget extends StatefulWidget { + const GalleryThumbnailWidget({ + required this.asset, + required this.isSelected, + required this.onTap, + super.key, + }); + + final AssetEntity asset; + final bool isSelected; + final VoidCallback onTap; + + @override + State createState() => _GalleryThumbnailWidgetState(); +} + +class _GalleryThumbnailWidgetState extends State { + late final Future _thumbnailFuture; + + @override + void initState() { + super.initState(); + _thumbnailFuture = widget.asset.thumbnailData; + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: widget.onTap, + child: SelectableThumbnailComp( + isSelected: widget.isSelected, + child: Stack( + fit: StackFit.expand, + children: [ + FutureBuilder( + future: _thumbnailFuture, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.done && + snapshot.data != null) { + return Image.memory( + snapshot.data!, + fit: BoxFit.cover, + ); + } + return ColoredBox( + color: Colors.grey.withValues(alpha: 0.1), + child: const Center( + child: SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator.adaptive(strokeWidth: 2), + ), + ), + ); + }, + ), + if (widget.asset.type == AssetType.video) + const Positioned.fill( + child: Center( + child: Icon( + Icons.play_circle_outline, + color: Colors.white, + size: 32, + shadows: [ + Shadow(color: Colors.black54, blurRadius: 6), + ], + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/src/visual/views/settings/data_and_storage/import_media.view.dart b/lib/src/visual/views/settings/data_and_storage/import_media.view.dart deleted file mode 100644 index d2ffd6a6..00000000 --- a/lib/src/visual/views/settings/data_and_storage/import_media.view.dart +++ /dev/null @@ -1,194 +0,0 @@ -import 'dart:io'; - -import 'package:archive/archive_io.dart'; -import 'package:drift/drift.dart' show Value; -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/material.dart'; -import 'package:path/path.dart' as p; -import 'package:twonly/locator.dart'; -import 'package:twonly/src/database/tables/mediafiles.table.dart'; -import 'package:twonly/src/database/twonly.db.dart'; -import 'package:twonly/src/services/mediafiles/mediafile.service.dart'; - -class ImportMediaView extends StatefulWidget { - const ImportMediaView({super.key}); - - @override - State createState() => _ImportMediaViewState(); -} - -class _ImportMediaViewState extends State { - double _progress = 0; - String? _status; - File? _zipFile; - bool _isProcessing = false; - - Future _pickAndImportZip() async { - setState(() { - _status = null; - _progress = 0; - _zipFile = null; - _isProcessing = true; - }); - - try { - final result = await FilePicker.platform.pickFiles( - type: FileType.custom, - allowedExtensions: ['zip'], - ); - - if (result == null || result.files.isEmpty) { - setState(() { - _status = 'No file selected.'; - _isProcessing = false; - }); - return; - } - - final pickedPath = result.files.single.path; - if (pickedPath == null) { - setState(() { - _status = 'Selected file has no path.'; - _isProcessing = false; - }); - return; - } - - final pickedFile = File(pickedPath); - if (!pickedFile.existsSync()) { - setState(() { - _status = 'Selected file does not exist.'; - _isProcessing = false; - }); - return; - } - - setState(() { - _zipFile = pickedFile; - _status = 'Selected ${p.basename(pickedPath)}'; - }); - - await _extractZipToMediaFolder(pickedFile); - } catch (e) { - setState(() { - _status = 'Error: $e'; - _isProcessing = false; - }); - } - } - - Future _extractZipToMediaFolder(File zipFile) async { - setState(() { - _status = 'Reading archive...'; - _progress = 0; - }); - - try { - final stream = InputFileStream(zipFile.path); - - final archive = ZipDecoder().decodeStream(stream); - - // Optionally: compute total entries to show progress - final entries = archive.where((e) => e.isFile).toList(); - final total = entries.length; - var processed = 0; - - for (final file in entries) { - if (!file.isFile || file.isSymbolicLink) continue; - - final extSplit = file.name.split('.'); - if (extSplit.isEmpty) continue; - final ext = extSplit.last; - - late MediaType type; - switch (ext) { - case 'webp': - type = MediaType.image; - case 'mp4': - type = MediaType.video; - case 'gif': - type = MediaType.gif; - default: - continue; - } - - final mediaFile = await twonlyDB.mediaFilesDao.insertOrUpdateMedia( - MediaFilesCompanion( - type: Value(type), - createdAt: Value(file.lastModDateTime), - stored: const Value(true), - ), - ); - final mediaService = MediaFileService(mediaFile!); - await mediaService.storedPath.writeAsBytes(file.content); - - processed++; - setState(() { - _progress = total > 0 ? processed / total : 0; - _status = 'Imported ${file.name}'; - }); - - // allow UI to update for large archives - await Future.delayed(const Duration(milliseconds: 10)); - } - - setState(() { - _status = 'Import complete. ${entries.length} entries processed.'; - _isProcessing = false; - _progress = 1; - }); - } catch (e) { - setState(() { - _status = 'Extraction failed: $e'; - _isProcessing = false; - }); - } - } - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: const Text('Import memories'), - ), - body: Container( - margin: const EdgeInsets.all(24), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Text( - 'Here, you can import exported memories.', - textAlign: TextAlign.center, - style: TextStyle( - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 24), - if (_isProcessing || _zipFile != null) - LinearProgressIndicator( - value: _isProcessing - ? _progress - : (_zipFile != null ? 1.0 : 0.0), - ), - const SizedBox(height: 8), - if (_status != null) - Text( - _status!, - textAlign: TextAlign.center, - ), - const SizedBox(height: 24), - ElevatedButton.icon( - icon: const Icon(Icons.file_upload), - label: Text( - _isProcessing - ? 'Processing...' - : 'Select memories.zip to import', - ), - onPressed: _isProcessing ? null : _pickAndImportZip, - ), - ], - ), - ), - ); - } -} diff --git a/lib/src/visual/views/settings/developer/developer.view.dart b/lib/src/visual/views/settings/developer/developer.view.dart index 8200b965..7926d295 100644 --- a/lib/src/visual/views/settings/developer/developer.view.dart +++ b/lib/src/visual/views/settings/developer/developer.view.dart @@ -263,6 +263,12 @@ class _DeveloperSettingsViewState extends State { ); } + Future toggleDatabaseLogging() async { + await UserService.update( + (u) => u.enableDatabaseLogging = !u.enableDatabaseLogging, + ); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -277,11 +283,19 @@ class _DeveloperSettingsViewState extends State { ListTile( title: const Text('Show Developer Settings'), onTap: toggleDeveloperSettings, - trailing: Switch( + trailing: Switch.adaptive( value: userService.currentUser.isDeveloper, onChanged: (_) => toggleDeveloperSettings(), ), ), + ListTile( + title: const Text('Enable Database Logging'), + onTap: toggleDatabaseLogging, + trailing: Switch.adaptive( + value: userService.currentUser.enableDatabaseLogging, + onChanged: (_) => toggleDatabaseLogging(), + ), + ), ListTile( title: const Text('User ID'), subtitle: Text(userService.currentUser.userId.toString()), @@ -312,7 +326,7 @@ class _DeveloperSettingsViewState extends State { await SharePlus.instance.share( ShareParams( files: [XFile(dbCopyPath)], - text: 'Twonly Database', + text: 'twonly Database', ), ); } @@ -324,7 +338,7 @@ class _DeveloperSettingsViewState extends State { ListTile( title: const Text('Toggle Video Stabilization'), onTap: toggleVideoStabilization, - trailing: Switch( + trailing: Switch.adaptive( value: userService.currentUser.videoStabilizationEnabled, onChanged: (a) => toggleVideoStabilization(), ), @@ -386,7 +400,7 @@ class _DeveloperSettingsViewState extends State { ? const SizedBox( width: 24, height: 24, - child: CircularProgressIndicator(strokeWidth: 2), + child: CircularProgressIndicator.adaptive(strokeWidth: 2), ) : null, onTap: _isGeneratingMockImages diff --git a/lib/src/visual/views/settings/help/changelog.view.dart b/lib/src/visual/views/settings/help/changelog.view.dart index a8520418..c4f05891 100644 --- a/lib/src/visual/views/settings/help/changelog.view.dart +++ b/lib/src/visual/views/settings/help/changelog.view.dart @@ -112,7 +112,7 @@ class _ChangeLogViewState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(context.lang.openChangeLog), - Switch( + Switch.adaptive( value: !userService.currentUser.hideChangeLog, onChanged: (_) => UserService.update( (u) => u.hideChangeLog = !u.hideChangeLog, diff --git a/lib/src/visual/views/settings/help/contact_us.view.dart b/lib/src/visual/views/settings/help/contact_us.view.dart index 47916631..bbaeb18d 100644 --- a/lib/src/visual/views/settings/help/contact_us.view.dart +++ b/lib/src/visual/views/settings/help/contact_us.view.dart @@ -243,9 +243,9 @@ $debugLogToken ? SizedBox( height: 12, width: 12, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, - color: Theme.of(context).colorScheme.inversePrimary, + valueColor: AlwaysStoppedAnimation(Theme.of(context).colorScheme.inversePrimary), ), ) : const FaIcon(FontAwesomeIcons.angleRight), @@ -291,7 +291,7 @@ class _IncludeDebugLogState extends State { Widget build(BuildContext context) { return Row( children: [ - Checkbox( + Checkbox.adaptive( value: widget.isChecked, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, onChanged: (value) { diff --git a/lib/src/visual/views/settings/help/faq.view.dart b/lib/src/visual/views/settings/help/faq.view.dart index 83a56626..9e73e859 100644 --- a/lib/src/visual/views/settings/help/faq.view.dart +++ b/lib/src/visual/views/settings/help/faq.view.dart @@ -117,7 +117,7 @@ class _FaqViewState extends State { appBar: AppBar( title: Text(context.lang.settingsHelpFAQ), ), - body: const Center(child: CircularProgressIndicator()), + body: const Center(child: CircularProgressIndicator.adaptive()), ); } diff --git a/lib/src/visual/views/settings/help/help.view.dart b/lib/src/visual/views/settings/help/help.view.dart index ef09109a..0fac5845 100644 --- a/lib/src/visual/views/settings/help/help.view.dart +++ b/lib/src/visual/views/settings/help/help.view.dart @@ -51,7 +51,7 @@ class _HelpViewState extends State { style: const TextStyle(fontSize: 10), ), onTap: toggleAllowErrorTrackingViaSentry, - trailing: Switch( + trailing: Switch.adaptive( value: userService.currentUser.allowErrorTrackingViaSentry, onChanged: (a) => toggleAllowErrorTrackingViaSentry(), ), diff --git a/lib/src/visual/views/settings/notification.view.dart b/lib/src/visual/views/settings/notification.view.dart index 2a5343f9..c8e3696e 100644 --- a/lib/src/visual/views/settings/notification.view.dart +++ b/lib/src/visual/views/settings/notification.view.dart @@ -123,7 +123,7 @@ class _NotificationViewState extends State { ? const SizedBox( width: 16, height: 16, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, ), ) @@ -138,7 +138,7 @@ class _NotificationViewState extends State { ? const SizedBox( width: 16, height: 16, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, ), ) diff --git a/lib/src/visual/views/settings/privacy.view.dart b/lib/src/visual/views/settings/privacy.view.dart index 88d43c01..5040d160 100644 --- a/lib/src/visual/views/settings/privacy.view.dart +++ b/lib/src/visual/views/settings/privacy.view.dart @@ -96,7 +96,7 @@ class _PrivacyViewState extends State { title: Text(context.lang.settingsTypingIndication), subtitle: Text(context.lang.settingsTypingIndicationSubtitle), onTap: toggleTypingIndicators, - trailing: Switch( + trailing: Switch.adaptive( value: userService.currentUser.typingIndicators, onChanged: (a) => toggleTypingIndicators(), ), @@ -106,7 +106,7 @@ class _PrivacyViewState extends State { title: Text(context.lang.settingsScreenLock), subtitle: Text(context.lang.settingsScreenLockSubtitle), onTap: toggleAuthRequirementOnStartup, - trailing: Switch( + trailing: Switch.adaptive( value: userService.currentUser.screenLockEnabled, onChanged: (a) => toggleAuthRequirementOnStartup(), ), diff --git a/lib/src/visual/views/settings/privacy/block_users.view.dart b/lib/src/visual/views/settings/privacy/block_users.view.dart index 3947133c..3523a740 100644 --- a/lib/src/visual/views/settings/privacy/block_users.view.dart +++ b/lib/src/visual/views/settings/privacy/block_users.view.dart @@ -119,7 +119,7 @@ class UserList extends StatelessWidget { ], ), leading: AvatarIcon(contactId: user.userId, fontSize: 15), - trailing: Checkbox( + trailing: Checkbox.adaptive( value: user.blocked, onChanged: (value) async { await block(context, user.userId, value); diff --git a/lib/src/visual/views/settings/privacy/user_discovery/components/user_discovery_setup.comp.dart b/lib/src/visual/views/settings/privacy/user_discovery/components/user_discovery_setup.comp.dart index cb474d59..56a1a897 100644 --- a/lib/src/visual/views/settings/privacy/user_discovery/components/user_discovery_setup.comp.dart +++ b/lib/src/visual/views/settings/privacy/user_discovery/components/user_discovery_setup.comp.dart @@ -292,7 +292,7 @@ class UserDiscoverySetupComp extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - SwitchListTile( + SwitchListTile.adaptive( value: state.isUserDiscoveryEnabled, onChanged: (val) => state.update(() { state.isUserDiscoveryEnabled = val; @@ -323,7 +323,7 @@ class UserDiscoverySetupComp extends StatelessWidget { ), ), ), - SwitchListTile( + SwitchListTile.adaptive( value: state.isManualApprovalEnabled, onChanged: (val) => state.update( () => state.isManualApprovalEnabled = val, @@ -547,7 +547,7 @@ class UserDiscoverySetupComp extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - SwitchListTile( + SwitchListTile.adaptive( value: state.sharePromotion, onChanged: (val) => state.update(() { state.sharePromotion = val; diff --git a/lib/src/visual/views/settings/subscription/select_additional_users.view.dart b/lib/src/visual/views/settings/subscription/select_additional_users.view.dart index 051d4982..6f5b45b8 100644 --- a/lib/src/visual/views/settings/subscription/select_additional_users.view.dart +++ b/lib/src/visual/views/settings/subscription/select_additional_users.view.dart @@ -195,7 +195,7 @@ class _SelectAdditionalUsers extends State { contactId: user.userId, fontSize: 13, ), - trailing: Checkbox( + trailing: Checkbox.adaptive( value: selectedUsers.contains(user.userId) | _alreadySelected.contains(user.userId), diff --git a/lib/src/visual/views/settings/subscription/subscription.view.dart b/lib/src/visual/views/settings/subscription/subscription.view.dart index a0964385..c6f73b38 100644 --- a/lib/src/visual/views/settings/subscription/subscription.view.dart +++ b/lib/src/visual/views/settings/subscription/subscription.view.dart @@ -330,7 +330,7 @@ class _PlanCardState extends State { ? const SizedBox( width: 10, height: 10, - child: CircularProgressIndicator(strokeWidth: 1), + child: CircularProgressIndicator.adaptive(strokeWidth: 1), ) : null, label: Text( @@ -350,7 +350,7 @@ class _PlanCardState extends State { ? const SizedBox( width: 10, height: 10, - child: CircularProgressIndicator(strokeWidth: 1), + child: CircularProgressIndicator.adaptive(strokeWidth: 1), ) : null, label: Text( diff --git a/lib/src/visual/views/shared/select_contacts.view.dart b/lib/src/visual/views/shared/select_contacts.view.dart index 3564e050..ff67b08f 100644 --- a/lib/src/visual/views/shared/select_contacts.view.dart +++ b/lib/src/visual/views/shared/select_contacts.view.dart @@ -208,7 +208,7 @@ class _SelectAdditionalUsers extends State { contactId: user.userId, fontSize: 13, ), - trailing: Checkbox( + trailing: Checkbox.adaptive( value: selectedUsers.contains(user.userId) | _alreadySelected.contains(user.userId), diff --git a/lib/src/visual/views/user_study/user_study_questionnaire.view.dart b/lib/src/visual/views/user_study/user_study_questionnaire.view.dart index ed86d82e..997c328a 100644 --- a/lib/src/visual/views/user_study/user_study_questionnaire.view.dart +++ b/lib/src/visual/views/user_study/user_study_questionnaire.view.dart @@ -176,7 +176,7 @@ class _UserStudyQuestionnaireViewState 'Welche der folgenden Messenger hast du schon einmal benutzt?', ), ..._messengerOptions.map( - (m) => CheckboxListTile( + (m) => CheckboxListTile.adaptive( title: Text(m), visualDensity: const VisualDensity(vertical: -4), value: (_responses['messengers'] as List).contains(m), diff --git a/pubspec.lock b/pubspec.lock index aafa95ea..6c86ebd9 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -448,6 +448,13 @@ packages: url: "https://github.com/otsmr/emoji_picker_flutter.git" source: git version: "4.4.0" + exif: + dependency: "direct main" + description: + path: "dependencies/exif" + relative: true + source: path + version: "3.3.0" fake_async: dependency: transitive description: @@ -1506,6 +1513,14 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.2" + photo_manager: + dependency: "direct main" + description: + name: photo_manager + sha256: fb3bc8ea653370f88742b3baa304700107c83d12748aa58b2b9f2ed3ef15e6c2 + url: "https://pub.dev" + source: hosted + version: "3.9.0" photo_view: dependency: "direct main" description: @@ -1792,6 +1807,13 @@ packages: url: "https://pub.dev" source: hosted version: "1.10.2" + sprintf: + dependency: "direct overridden" + description: + path: "dependencies/sprintf" + relative: true + source: path + version: "7.0.0" sqflite: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 1294c242..31b7386e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: "twonly, a privacy-friendly way to connect with friends through sec publish_to: 'none' -version: 0.2.23+132 +version: 0.2.26+135 environment: sdk: ^3.11.0 @@ -86,6 +86,7 @@ dependencies: flutter_sharing_intent: ^2.0.4 screen_protector: ^1.5.1 flutter_markdown_plus: ^1.0.7 + exif: ^3.3.0 # With high download. (But should be checked nonetheless.) app_links: ^7.0.0 # 1.6 mio @@ -107,6 +108,7 @@ dependencies: flutter_image_compress: ^2.4.0 flutter_volume_controller: ^1.3.4 gal: ^2.3.1 + photo_manager: ^3.9.0 google_mlkit_barcode_scanning: ^0.14.1 google_mlkit_face_detection: ^0.13.1 pro_video_editor: ^1.6.1 @@ -172,6 +174,10 @@ dependency_overrides: git: url: https://github.com/yenchieh/flutter_android_volume_keydown.git ref: fix/lStar-not-found-error + exif: + path: ./dependencies/exif + sprintf: + path: ./dependencies/sprintf dev_dependencies: build_runner: ^2.4.15 diff --git a/rust/src/backup/backup_archive.rs b/rust/src/backup/backup_archive.rs index bcbd73a4..d1dac2e7 100644 --- a/rust/src/backup/backup_archive.rs +++ b/rust/src/backup/backup_archive.rs @@ -55,15 +55,29 @@ impl BackupArchive { } if is_db { + // To avoid write-lock conflicts with Dart (which has the live database open in write mode), + // we copy the database file first, then open the copy in write mode to perform the backup. + let temp_copy_path = backup_data_dir.join(format!("{}.temp_copy", file_name)); + std::fs::copy(&file_path, &temp_copy_path)?; + let db = Database::new( - &file_path.display().to_string(), + &temp_copy_path.display().to_string(), encryption_key.as_deref(), - false, + false, // Open the copy in write mode required for encrypted backups ) .await?; let backup_database_file = backup_data_dir.join(file_name).display().to_string(); db.create_backup(backup_database_file.as_str(), encryption_key.as_deref()) .await?; + + // Close database connection to release file lock before removing it + drop(db); + remove_file(&temp_copy_path)?; + + // Perform integrity check of the new database file + let backup_db = + Database::new(&backup_database_file, encryption_key.as_deref(), false).await?; + backup_db.check_integrity().await?; } else { let file_backup = backup_data_dir.join(file_name); std::fs::copy(file_path, file_backup)?; diff --git a/rust/src/context.rs b/rust/src/context.rs index 53361e38..d409b523 100644 --- a/rust/src/context.rs +++ b/rust/src/context.rs @@ -63,14 +63,14 @@ impl Context { key_manager.store_to_keychain(&secure_storage)?; let rust_db_path = database_dir.join("rust_db.sqlite"); - let rust_db = Arc::new( - Database::new( - &rust_db_path.display().to_string(), - Some(&key_manager.main_key.get_database_key(DatabaseKey::RustDb)), - false, - ) - .await?, - ); + let rust_db = Database::new( + &rust_db_path.display().to_string(), + Some(&key_manager.main_key.get_database_key(DatabaseKey::RustDb)), + false, + ) + .await?; + rust_db.run_migrations().await?; + let rust_db = Arc::new(rust_db); Ok(Context::from_standalone(TwonlyStandalone { config, @@ -120,14 +120,14 @@ impl Context { let mut rust_db_key = key_manager.main_key.get_database_key(DatabaseKey::RustDb); - let rust_db = Arc::new( - Database::new( - &rust_db_path.display().to_string(), - Some(rust_db_key.as_str()), - false, - ) - .await?, - ); + let rust_db = Database::new( + &rust_db_path.display().to_string(), + Some(rust_db_key.as_str()), + false, + ) + .await?; + rust_db.run_migrations().await?; + let rust_db = Arc::new(rust_db); rust_db_key.zeroize(); diff --git a/rust/src/database/mod.rs b/rust/src/database/mod.rs index 46721db9..665459dc 100644 --- a/rust/src/database/mod.rs +++ b/rust/src/database/mod.rs @@ -26,10 +26,11 @@ impl Database { let mut connect_options = format!("{db_url}?mode=rwc") .parse::()? .log_statements(log_statements_level) - .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) + .journal_mode(sqlx::sqlite::SqliteJournalMode::Delete) .foreign_keys(true) .read_only(read_only) .busy_timeout(Duration::from_millis(5000)) + .pragma("synchronous", "FULL") .pragma("recursive_triggers", "ON") .log_slow_statements(tracing::log::LevelFilter::Warn, Duration::from_millis(500)); @@ -43,15 +44,18 @@ impl Database { .connect_with(connect_options) .await?; + Ok(Self { pool }) + } + + pub(crate) async fn run_migrations(&self) -> Result<()> { sqlx::migrate!("./src/database/migrations") - .run(&pool) + .run(&self.pool) .await .map_err(|e| { tracing::error!("migration error: {:?}", e); TwonlyError::Generic(format!("Migration error: {}", e)) })?; - - Ok(Self { pool }) + Ok(()) } pub(crate) async fn create_backup( @@ -91,6 +95,22 @@ impl Database { } Ok(()) } + + pub(crate) async fn check_integrity(&self) -> Result<()> { + let row: (String,) = sqlx::query_as("PRAGMA integrity_check") + .fetch_one(&self.pool) + .await + .map_err(|e| TwonlyError::Generic(format!("Integrity check query failed: {}", e)))?; + + if row.0.to_lowercase() == "ok" { + Ok(()) + } else { + Err(TwonlyError::Generic(format!( + "Database integrity check failed: {}", + row.0 + ))) + } + } } #[cfg(test)] @@ -109,6 +129,7 @@ mod tests { // 1. Create and initialize database with key let db = Database::new(&db_path, Some(key), false).await.unwrap(); + db.run_migrations().await.unwrap(); ReceivedMessage::insert(&db.pool, 1, b"hello world") .await .unwrap(); @@ -137,6 +158,7 @@ mod tests { let key = "secure_password"; let db = Database::new(&db_path, Some(key), false).await.unwrap(); + db.run_migrations().await.unwrap(); ReceivedMessage::insert(&db.pool, 1, b"hello world") .await .unwrap(); @@ -165,6 +187,7 @@ mod tests { let backup_path = dir.path().join("backup_plain.sqlite").display().to_string(); let db = Database::new(&db_path, None, false).await.unwrap(); + db.run_migrations().await.unwrap(); ReceivedMessage::insert(&db.pool, 1, b"hello world") .await .unwrap(); diff --git a/rust/src/database/tables/mod.rs b/rust/src/database/tables/mod.rs index c8a04d57..7d27b9ea 100644 --- a/rust/src/database/tables/mod.rs +++ b/rust/src/database/tables/mod.rs @@ -71,6 +71,7 @@ macro_rules! generate_table_tests { let dir = tempdir().unwrap(); let db_path = dir.path().join("test.sqlite").display().to_string(); let db = Database::new(&db_path, None, false).await.unwrap(); + db.run_migrations().await.unwrap(); let _id = $struct::$insert_fn(&db.pool, $($arg),+).await.unwrap(); let all = $struct::$select_all_fn(&db.pool).await.unwrap(); @@ -92,6 +93,7 @@ macro_rules! generate_test_select { let dir = tempdir().unwrap(); let db_path = dir.path().join("test.sqlite").display().to_string(); let db = Database::new(&db_path, None, false).await.unwrap(); + db.run_migrations().await.unwrap(); $struct::$insert_fn(&db.pool, $($arg),+).await.unwrap(); let results = $struct::$select_fn(&db.pool, $($sel_arg),+).await.unwrap(); diff --git a/test.jpg b/test.jpg new file mode 100644 index 00000000..c91ed5da Binary files /dev/null and b/test.jpg differ