diff options
Diffstat (limited to 'android/app')
220 files changed, 20577 insertions, 0 deletions
diff --git a/android/app/agconnect-services.json b/android/app/agconnect-services.json new file mode 100644 index 0000000..d406d5c --- /dev/null +++ b/android/app/agconnect-services.json @@ -0,0 +1,82 @@ +{ + "agcgw_all":{ + "CN":"connect-drcn.dbankcloud.cn", + "CN_back":"connect-drcn.hispace.hicloud.com", + "DE":"connect-dre.dbankcloud.cn", + "DE_back":"connect-dre.hispace.hicloud.com", + "RU":"connect-drru.hispace.dbankcloud.ru", + "RU_back":"connect-drru.hispace.dbankcloud.cn", + "SG":"connect-dra.dbankcloud.cn", + "SG_back":"connect-dra.hispace.hicloud.com" + }, + "websocketgw_all":{ + "CN":"connect-ws-drcn.hispace.dbankcloud.cn", + "CN_back":"connect-ws-drcn.hispace.dbankcloud.com", + "DE":"connect-ws-dre.hispace.dbankcloud.cn", + "DE_back":"connect-ws-dre.hispace.dbankcloud.com", + "RU":"connect-ws-drru.hispace.dbankcloud.ru", + "RU_back":"connect-ws-drru.hispace.dbankcloud.cn", + "SG":"connect-ws-dra.hispace.dbankcloud.cn", + "SG_back":"connect-ws-dra.hispace.dbankcloud.com" + }, + "client":{ + "cp_id":"2640082000020010713", + "product_id":"99536292102197525", + "project_id":"99536292102197525", + "app_id":"106014023", + "package_name":"deckers.thibault.aves" + }, + "oauth_client":{ + "client_id":"106014023", + "client_type":1 + }, + "app_info":{ + "app_id":"106014023", + "package_name":"deckers.thibault.aves" + }, + "configuration_version":"3.0", + "appInfos":[ + { + "package_name":"deckers.thibault.aves", + "client":{ + "app_id":"106014023" + }, + "app_info":{ + "package_name":"deckers.thibault.aves", + "app_id":"106014023" + }, + "oauth_client":{ + "client_type":1, + "client_id":"106014023" + } + }, + { + "package_name":"deckers.thibault.aves.debug", + "client":{ + "app_id":"106014297" + }, + "app_info":{ + "package_name":"deckers.thibault.aves.debug", + "app_id":"106014297" + }, + "oauth_client":{ + "client_type":1, + "client_id":"106014297" + } + }, + { + "package_name":"deckers.thibault.aves.profile", + "client":{ + "app_id":"106031461" + }, + "app_info":{ + "package_name":"deckers.thibault.aves.profile", + "app_id":"106031461" + }, + "oauth_client":{ + "client_type":1, + "client_id":"106031461" + } + } + ] +}
\ No newline at end of file diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..6afa8ea --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,220 @@ +plugins { + id 'com.android.application' + id 'com.google.devtools.ksp' + id 'kotlin-android' + id 'dev.flutter.flutter-gradle-plugin' +} + +def packageName = "deckers.thibault.aves" + +// Keys + +def keystoreProperties = new Properties() +def keystorePropertiesFile = rootProject.file('key.properties') +if (keystorePropertiesFile.exists()) { + // for release using credentials stored in a local file + keystorePropertiesFile.withReader('UTF-8') { reader -> keystoreProperties.load(reader) + } +} else { + // for release using credentials in environment variables set up by GitHub Actions + // warning: in property file, single quotes should be escaped with a backslash + // but they should not be escaped when stored in env variables + keystoreProperties["storeFile"] = System.getenv("AVES_STORE_FILE") ?: "<NONE>" + keystoreProperties["storePassword"] = System.getenv("AVES_STORE_PASSWORD") ?: "<NONE>" + keystoreProperties["keyAlias"] = System.getenv("AVES_KEY_ALIAS") ?: "<NONE>" + keystoreProperties["keyPassword"] = System.getenv("AVES_KEY_PASSWORD") ?: "<NONE>" + keystoreProperties["googleApiKey"] = System.getenv("AVES_GOOGLE_API_KEY") ?: "<NONE>" +} + +kotlin { + jvmToolchain 17 +} + +android { + namespace = 'deckers.thibault.aves' + compileSdk = 36 + + compileOptions { + // enable support for the new language APIs on older devices + // e.g. `java/util/function/Supplier` on Android 5.0 (API 21) + coreLibraryDesugaringEnabled = true + // should match `kotlin.jvmToolchain` + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + applicationId = packageName + minSdk = flutter.minSdkVersion + targetSdk = 36 + versionCode = flutter.versionCode + versionName = flutter.versionName + manifestPlaceholders = [googleApiKey: keystoreProperties["googleApiKey"] ?: "<NONE>"] + multiDexEnabled = true + } + + signingConfigs { + release { + keyAlias keystoreProperties["keyAlias"] + keyPassword keystoreProperties["keyPassword"] + storeFile keystoreProperties["storeFile"] ? file(keystoreProperties["storeFile"]) : null + storePassword keystoreProperties["storePassword"] + } + } + + flavorDimensions += "store" + + productFlavors { + play { + // Google Play + dimension "store" + // generate a universal APK without x86 native libs + ext.useNdkAbiFilters = true + } + + izzy { + // IzzyOnDroid + // check offending libraries with `scanapk` + // cf https://android.izzysoft.de/articles/named/app-modules-2 + dimension "store" + // generate APK by ABI, but NDK ABI filters are incompatible with split APK generation + ext.useNdkAbiFilters = false + } + + libre { + // F-Droid + // check offending libraries with `fdroidserver` + // cf https://f-droid.org/en/docs/Submitting_to_F-Droid_Quick_Start_Guide/ + dimension "store" + // generate APK by ABI, but NDK ABI filters are incompatible with split APK generation + ext.useNdkAbiFilters = false + applicationIdSuffix ".libre" + } + + libre_rom { + // integration in custom ROM + dimension "store" + // generate a universal APK without x86 native libs + ext.useNdkAbiFilters = true + applicationIdSuffix ".libre" + + packagingOptions { + // disable compression for native libraries (.so files) + jniLibs.useLegacyPackaging false + } + } + } + + buildTypes { + debug { + applicationIdSuffix ".debug" + } + profile { + applicationIdSuffix ".profile" + } + release { + signingConfig = signingConfigs.release + minifyEnabled = true + shrinkResources = true + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + + applicationVariants.all { variant -> + variant.resValue 'string', 'screen_saver_settings_activity', "${applicationId}/${packageName}.ScreenSaverSettingsActivity" + variant.resValue 'string', 'search_provider', "${applicationId}.search_provider" + + variant.outputs.each { output -> + def baseAbiVersionCode = rootProject.ext.abiCodes.get(output.getFilter('ABI')) + if (baseAbiVersionCode != null) { + output.versionCodeOverride = variant.versionCode * 100 + baseAbiVersionCode + } + } + } + + android.productFlavors.each { flavor -> + def tasks = gradle.startParameter.taskNames.toString().toLowerCase() + if (tasks.contains(flavor.name) && flavor.ext.useNdkAbiFilters) { + release { + // specify architectures, to specifically exclude native libs for x86, + // which lead to: UnsatisfiedLinkError...couldn't find "libflutter.so" + // cf https://github.com/flutter/flutter/issues/37566#issuecomment-640879500 + ndk { + //noinspection ChromeOsAbiSupport + abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86_64' + } + } + } + } + } +} + +flutter { + source '../..' +} + +repositories { + maven { + url = 'https://jitpack.io' + content { + includeGroup "com.github.deckerst" + includeGroup "com.github.deckerst.mp4parser" + } + } + maven { + url = 'https://s3.amazonaws.com/repo.commonsware.com' + content { + excludeGroupByRegex "com\\.github\\.deckerst.*" + } + } +} + +dependencies { + // cf https://developer.android.com/studio/write/java8-support#library-desugaring + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5") + + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2' + + implementation 'androidx.annotation:annotation:1.9.1' + implementation "androidx.appcompat:appcompat:1.7.1" + implementation 'androidx.core:core-ktx:1.17.0' + // `lifecycle-process:2.10.0` requires `minSdkVersion` 23+ + implementation 'androidx.lifecycle:lifecycle-process:2.9.4' + implementation 'androidx.media:media:1.7.1' + implementation 'androidx.multidex:multidex:2.0.1' + // Jetpack `security-crypto` library is deprecated: + // https://developer.android.com/privacy-and-security/cryptography#security-crypto-jetpack-deprecated + implementation 'androidx.security:security-crypto:1.1.0' + // `work-runtime:2.11.0` requires `minSdkVersion` 23+ + implementation 'androidx.work:work-runtime:2.10.5' + + implementation 'com.commonsware.cwac:document:0.5.0' + implementation 'com.drewnoakes:metadata-extractor:2.19.0' + implementation "com.github.bumptech.glide:glide:$glide_version" + implementation 'com.google.android.material:material:1.13.0' + // SLF4J implementation for `mp4parser` + implementation 'org.slf4j:slf4j-simple:2.0.17' + + // forked, built by JitPack: + // - https://jitpack.io/p/deckerst/Android-TiffBitmapFactory + // - https://jitpack.io/p/deckerst/androidsvg + // - https://jitpack.io/p/deckerst/mp4parser + // - https://jitpack.io/p/deckerst/pixymeta-android + implementation 'com.github.deckerst:Android-TiffBitmapFactory:424b18a4ae' + implementation 'com.github.deckerst:androidsvg:c7e58e8e59' + implementation 'com.github.deckerst.mp4parser:isoparser:c2898f1832' + implementation 'com.github.deckerst.mp4parser:muxer:c2898f1832' + implementation 'com.github.deckerst:pixymeta-android:f4513291b7' + implementation project(':exifinterface') + + testImplementation 'org.junit.jupiter:junit-jupiter-engine:6.0.1' + + ksp "com.github.bumptech.glide:ksp:$glide_version" + + compileOnly rootProject.findProject(':streams_channel') +} + +if (useCrashlytics) { + println("Building flavor with Crashlytics plugin") + apply plugin: 'com.google.gms.google-services' + apply plugin: 'com.google.firebase.crashlytics' +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..06e861e --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,6 @@ +-keep class org.beyka.tiffbitmapfactory.**{ *; } +-keep class org.mp4parser.**{ *; } + +# referenced from: com.google.crypto.tink +-dontwarn com.google.errorprone.annotations.** +-dontwarn javax.annotation.** diff --git a/android/app/src/debug/res/values/colors.xml b/android/app/src/debug/res/values/colors.xml new file mode 100644 index 0000000..023cc20 --- /dev/null +++ b/android/app/src/debug/res/values/colors.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <color name="ic_launcher_flavour">#815AFA</color> +</resources>
\ No newline at end of file diff --git a/android/app/src/debug/res/values/strings.xml b/android/app/src/debug/res/values/strings.xml new file mode 100644 index 0000000..e5c92d3 --- /dev/null +++ b/android/app/src/debug/res/values/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves [Debug]</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/libre/res/values/strings.xml b/android/app/src/libre/res/values/strings.xml new file mode 100644 index 0000000..b451c08 --- /dev/null +++ b/android/app/src/libre/res/values/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves Libre</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/libreDebug/res/values/strings.xml b/android/app/src/libreDebug/res/values/strings.xml new file mode 100644 index 0000000..4c84517 --- /dev/null +++ b/android/app/src/libreDebug/res/values/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves Libre [Debug]</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/libreProfile/res/values/strings.xml b/android/app/src/libreProfile/res/values/strings.xml new file mode 100644 index 0000000..2918b24 --- /dev/null +++ b/android/app/src/libreProfile/res/values/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves Libre [Profile]</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..98fd6f8 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,350 @@ +<?xml version="1.0" encoding="utf-8"?> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:installLocation="auto"> + + <uses-feature + android:name="android.hardware.touchscreen" + android:required="false" /> + <uses-feature + android:name="android.hardware.wifi" + android:required="false" /> + <uses-feature + android:name="android.software.leanback" + android:required="false" /> + + <uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" /> + <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> + <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /> + <uses-permission + android:name="android.permission.READ_EXTERNAL_STORAGE" + android:maxSdkVersion="32" /> + <!-- + Scoped storage on Android 10 (API 29) is inconvenient because users need to confirm edition on each individual file. + So we request `WRITE_EXTERNAL_STORAGE` until Android 10 (API 29), and enable `requestLegacyExternalStorage` + --> + <uses-permission + android:name="android.permission.WRITE_EXTERNAL_STORAGE" + android:maxSdkVersion="29" + tools:ignore="ScopedStorage" /> + + <!-- to access media with original metadata with scoped storage (API >=29) --> + <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" /> + <!-- to provide a foreground service type, as required from Android 14 (API 34) --> + <uses-permission + android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" + android:maxSdkVersion="34" + tools:ignore="SystemPermissionTypo" /> + <uses-permission + android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROCESSING" + tools:ignore="SystemPermissionTypo" /> + <!-- TODO TLAD still needed to fetch map tiles / reverse geocoding / else ? check in release mode --> + <uses-permission android:name="android.permission.INTERNET" /> + <!-- from Android 12 (API 31), users can optionally grant access to the media management special permission --> + <uses-permission + android:name="android.permission.MANAGE_MEDIA" + tools:ignore="ProtectedPermissions" /> + <!-- to show analysis service progress via notification --> + <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> + <!-- to change wallpaper --> + <uses-permission android:name="android.permission.SET_WALLPAPER" /> + <!-- TODO TLAD remove this permission when this is fixed: https://github.com/flutter/flutter/issues/42451 --> + <uses-permission android:name="android.permission.WAKE_LOCK" /> + + <uses-permission + android:name="com.android.launcher.permission.INSTALL_SHORTCUT" + android:maxSdkVersion="25" /> + + <!-- additional permissions added by plugins: + + `{package}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION` by `androidx.appcompat:appcompat` + + `android.permission.ACCESS_NETWORK_STATE`, + `android.permission.FOREGROUND_SERVICE`, + `android.permission.RECEIVE_BOOT_COMPLETED`, + `android.permission.WAKE_LOCK` by `androidx.work:work-runtime-ktx`, to analyze media in a service + + `android.permission.ACCESS_NETWORK_STATE` by `dev.fluttercommunity.plus.connectivity`, TODO TLAD still needed? + + `android.permission.USE_BIOMETRIC` by `io.flutter.plugins.localauth`, to unlock vaults (API >=28) + --> + + <!-- + allow install on API 21, despite the `minSdk` declared in dependencies: + - FFmpegKit for Flutter is from API 24 (when not LTS) + --> + <uses-sdk tools:overrideLibrary="com.arthenica.ffmpegkit.flutter" /> + + <!-- from Android 11 (API 30), we should define <queries> to make other apps visible to this app --> + <queries> + <intent> + <action android:name="android.intent.action.MAIN" /> + </intent> + <!-- necessary to resolve image editor apps that are not visible in the launcher --> + <intent> + <action android:name="android.intent.action.EDIT" /> + <data android:mimeType="image/*" /> + </intent> + <!-- necessary to resolve video editor apps that are not visible in the launcher --> + <intent> + <action android:name="android.intent.action.EDIT" /> + <data android:mimeType="video/*" /> + </intent> + <!-- + from Android 11 (API 30), `url_launcher` method `canLaunchUrl()` will return false, + if appropriate intents are not declared, cf https://pub.dev/packages/url_launcher#configuration= + --> + <!-- to open https URLs --> + <intent> + <action android:name="android.intent.action.VIEW" /> + <data android:scheme="https" /> + </intent> + </queries> + + <!-- + as of Flutter v3.22.2, predictive back gesture does not work + as expected when extending `FlutterFragmentActivity` + so we disable `enableOnBackInvokedCallback` + --> + <application + android:allowBackup="true" + android:appCategory="image" + android:banner="@drawable/banner" + android:dataExtractionRules="@xml/data_extraction_rules" + android:enableOnBackInvokedCallback="false" + android:fullBackupContent="@xml/full_backup_content" + android:fullBackupOnly="true" + android:icon="@mipmap/ic_launcher" + android:label="@string/app_name" + android:requestLegacyExternalStorage="true" + android:roundIcon="@mipmap/ic_launcher_round" + android:supportsRtl="true" + tools:targetApi="tiramisu"> + <activity + android:name=".MainActivity" + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" + android:exported="true" + android:hardwareAccelerated="true" + android:launchMode="singleTop" + android:supportsPictureInPicture="true" + android:theme="@style/NormalTheme" + android:windowSoftInputMode="adjustResize"> + <intent-filter> + <!-- main entry point, navigating to home page --> + <action android:name="android.intent.action.MAIN" /> + + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.LAUNCHER" /> + <category android:name="android.intent.category.LEANBACK_LAUNCHER" /> + <category android:name="android.intent.category.APP_GALLERY" /> + </intent-filter> + <intent-filter tools:ignore="AppLinkUrlError"> + <!-- viewer for media with no specified scheme --> + <action android:name="android.intent.action.GET_CONTENT" /> + <action android:name="android.intent.action.PICK" /> + <action android:name="android.intent.action.SEND" /> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.provider.action.REVIEW" /> + <action android:name="android.provider.action.REVIEW_SECURE" /> + <action android:name="com.android.camera.action.REVIEW" /> + <action android:name="com.android.camera.action.SPLIT_SCREEN_REVIEW" /> + + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.BROWSABLE" /> + <category android:name="android.intent.category.OPENABLE" /> + + <data android:mimeType="image/*" /> + <data android:mimeType="video/*" /> + <data android:mimeType="vnd.android.cursor.dir/image" /> + <data android:mimeType="vnd.android.cursor.dir/video" /> + + <!-- no specified scheme --> + </intent-filter> + <intent-filter tools:ignore="AppLinkUrlError"> + <!-- viewer for media with a specified scheme --> + <action android:name="android.intent.action.GET_CONTENT" /> + <action android:name="android.intent.action.PICK" /> + <action android:name="android.intent.action.SEND" /> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.provider.action.REVIEW" /> + <action android:name="android.provider.action.REVIEW_SECURE" /> + <action android:name="com.android.camera.action.REVIEW" /> + <action android:name="com.android.camera.action.SPLIT_SCREEN_REVIEW" /> + + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.BROWSABLE" /> + <category android:name="android.intent.category.OPENABLE" /> + + <data android:mimeType="image/*" /> + <data android:mimeType="video/*" /> + <data android:mimeType="vnd.android.cursor.dir/image" /> + <data android:mimeType="vnd.android.cursor.dir/video" /> + + <data android:scheme="content" /> + <data android:scheme="file" /> + </intent-filter> + <intent-filter> + <!-- `geo` URI handling (view on map, or fill location editor) --> + <action android:name="android.intent.action.VIEW" /> + + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.BROWSABLE" /> + + <data android:scheme="geo" /> + </intent-filter> + <!-- + <intent-filter> + <action android:name="android.intent.action.EDIT" /> + <category android:name="android.intent.category.DEFAULT" /> + + <data android:mimeType="image/*" /> + <data android:mimeType="vnd.android.cursor.dir/image" /> + </intent-filter> + --> + <intent-filter> + <action android:name="android.intent.action.SEARCH" /> + </intent-filter> + + <!-- Specifies an Android theme to apply to this Activity as soon as + the Android process has started. This theme is visible to the user + while the Flutter UI initializes. After that, this theme continues + to determine the Window background behind the Flutter UI. --> + <meta-data + android:name="io.flutter.embedding.android.NormalTheme" + android:resource="@style/NormalTheme" /> + <meta-data + android:name="android.app.searchable" + android:resource="@xml/searchable" /> + <!-- launch size in desktop environments, like ChromeOS --> + <meta-data + android:name="WindowManagerPreference:FreeformWindowSize" + android:value="maximize" /> + <meta-data + android:name="WindowManagerPreference:FreeformWindowOrientation" + android:value="landscape" /> + </activity> + + <activity + android:name=".ScreenSaverSettingsActivity" + android:exported="true" + android:theme="@style/NormalTheme" /> + + <activity + android:name=".WallpaperActivity" + android:exported="true" + android:label="@string/wallpaper" + android:theme="@style/NormalTheme"> + <intent-filter> + <action android:name="android.intent.action.ATTACH_DATA" /> + <category android:name="android.intent.category.DEFAULT" /> + + <data android:mimeType="image/*" /> + <data android:mimeType="video/*" /> + </intent-filter> + + <intent-filter> + <action android:name="android.intent.action.SET_WALLPAPER" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + + <!-- exported for Android API 19 launcher to access this activity --> + <activity + android:name=".HomeWidgetSettingsActivity" + android:exported="true" + android:theme="@style/NormalTheme"> + <intent-filter> + <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /> + </intent-filter> + </activity> + + <receiver + android:name=".HomeWidgetProvider" + android:exported="false" + android:label="@string/app_widget_label"> + <intent-filter> + <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> + </intent-filter> + + <meta-data + android:name="android.appwidget.provider" + android:resource="@xml/app_widget_info" /> + </receiver> + + <receiver + android:name="androidx.media.session.MediaButtonReceiver" + android:exported="false"> + <intent-filter> + <action android:name="android.intent.action.MEDIA_BUTTON" /> + </intent-filter> + </receiver> + + <!-- + anonymous service for analysis worker is specified here to provide service type: + - `dataSync` for Android 14 (API 34) + - `mediaProcessing` from Android 15 (API 35) + --> + <service + android:name="androidx.work.impl.foreground.SystemForegroundService" + android:foregroundServiceType="dataSync|mediaProcessing" + tools:node="merge" /> + + <service + android:name=".MediaPlaybackService" + android:exported="false" + android:foregroundServiceType="mediaPlayback"> + <intent-filter> + <action android:name="android.media.browse.MediaBrowserService" /> + </intent-filter> + </service> + + <service + android:name=".ScreenSaverService" + android:exported="true" + android:icon="@mipmap/ic_launcher" + android:label="@string/app_name" + android:permission="android.permission.BIND_DREAM_SERVICE"> + <intent-filter> + <action android:name="android.service.dreams.DreamService" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + + <meta-data + android:name="android.service.dream" + android:resource="@xml/screen_saver" /> + </service> + + <!-- file provider to share files having a file:// URI --> + <provider + android:name="androidx.core.content.FileProvider" + android:authorities="${applicationId}.file_provider" + android:exported="false" + android:grantUriPermissions="true"> + <meta-data + android:name="android.support.FILE_PROVIDER_PATHS" + android:resource="@xml/provider_paths" /> + </provider> + + <provider + android:name=".SearchSuggestionsProvider" + android:authorities="@string/search_provider" + android:exported="true" + tools:ignore="ExportedContentProvider" /> + + <meta-data + android:name="com.google.android.geo.API_KEY" + android:value="${googleApiKey}" /> + <meta-data + android:name="firebase_crashlytics_collection_enabled" + android:value="false" /> + <!-- Don't delete the meta-data below. + This is used by the Flutter tool to generate GeneratedPluginRegistrant.java --> + <meta-data + android:name="flutterEmbedding" + android:value="2" /> + <meta-data + android:name="io.flutter.embedding.android.EnableImpeller" + android:value="false" /> + </application> +</manifest> diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/AnalysisWorker.kt b/android/app/src/main/kotlin/deckers/thibault/aves/AnalysisWorker.kt new file mode 100644 index 0000000..9fa7496 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/AnalysisWorker.kt @@ -0,0 +1,234 @@ +package deckers.thibault.aves + +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.util.Log +import androidx.core.app.NotificationChannelCompat +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.work.CoroutineWorker +import androidx.work.ForegroundInfo +import androidx.work.WorkInfo +import androidx.work.WorkManager +import androidx.work.WorkerParameters +import app.loup.streams_channel.StreamsChannel +import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend +import deckers.thibault.aves.channel.calls.DeviceHandler +import deckers.thibault.aves.channel.calls.GeocodingHandler +import deckers.thibault.aves.channel.calls.MediaFetchObjectHandler +import deckers.thibault.aves.channel.calls.MediaStoreHandler +import deckers.thibault.aves.channel.calls.MetadataFetchHandler +import deckers.thibault.aves.channel.calls.StorageHandler +import deckers.thibault.aves.channel.streams.darttoplatform.ImageByteStreamHandler +import deckers.thibault.aves.channel.streams.darttoplatform.MediaStoreStreamHandler +import deckers.thibault.aves.utils.FlutterUtils +import deckers.thibault.aves.utils.LogUtils +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import kotlinx.coroutines.CancellableContinuation +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException + +class AnalysisWorker(context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters) { + private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private var workCont: CancellableContinuation<Any?>? = null + private var flutterEngine: FlutterEngine? = null + private var backgroundChannel: MethodChannel? = null + + override suspend fun doWork(): Result { + Log.i(LOG_TAG, "Start analysis worker $id") + createNotificationChannel() + val foregroundInfo = createForegroundInfo() + if (!isStopped) { + setForeground(foregroundInfo) + suspendCancellableCoroutine { cont -> + workCont = cont + cont.invokeOnCancellation { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val stopReasonString = when(stopReason) { + WorkInfo.STOP_REASON_CANCELLED_BY_APP -> "CANCELLED_BY_APP" + WorkInfo.STOP_REASON_FOREGROUND_SERVICE_TIMEOUT -> "FOREGROUND_SERVICE_TIMEOUT" + else -> "[$stopReason]" + } + Log.i(LOG_TAG, "Analysis worker got cancelled with stopReason=$stopReasonString") + } else { + Log.i(LOG_TAG, "Analysis worker got cancelled") + } + stopDartAnalysisService() + workCont?.resumeWithException(CancellationException()) + } + onStart() + } + dispose() + } + return Result.success() + } + + private suspend fun dispose() { + Log.i(LOG_TAG, "Clean analysis worker $id") + flutterEngine?.let { + FlutterUtils.runOnUiThread { + it.destroy() + } + flutterEngine = null + } + } + + private fun onStart() { + runBlocking { + FlutterUtils.initFlutterEngine(applicationContext, SHARED_PREFERENCES_KEY, PREF_CALLBACK_HANDLE_KEY) { + flutterEngine = it + } + } + + try { + initChannels(applicationContext) + + val preferences = applicationContext.getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE) + val entryIdStrings = preferences.getStringSet(PREF_ENTRY_IDS_KEY, null) + startDartAnalysisService(entryIdStrings) + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to initialize worker", e) + workCont?.resumeWithException(e) + } + } + + private fun initChannels(context: Context) { + val engine = flutterEngine + engine ?: throw Exception("Flutter engine is not initialized") + + val messenger = engine.dartExecutor + + // channels for analysis + + // dart -> platform -> dart + // - need Context + MethodChannel(messenger, DeviceHandler.CHANNEL).setMethodCallHandler(DeviceHandler(context)) + MethodChannel(messenger, GeocodingHandler.CHANNEL).setMethodCallHandler(GeocodingHandler(context)) + MethodChannel(messenger, MediaFetchObjectHandler.CHANNEL).setMethodCallHandler(MediaFetchObjectHandler(context)) + MethodChannel(messenger, MediaStoreHandler.CHANNEL).setMethodCallHandler(MediaStoreHandler(context)) + MethodChannel(messenger, MetadataFetchHandler.CHANNEL).setMethodCallHandler(MetadataFetchHandler(context)) + MethodChannel(messenger, StorageHandler.CHANNEL).setMethodCallHandler(StorageHandler(context)) + + // result streaming: dart -> platform ->->-> dart + // - need Context + StreamsChannel(messenger, ImageByteStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageByteStreamHandler(context, args) } + StreamsChannel(messenger, MediaStoreStreamHandler.CHANNEL).setStreamHandlerFactory { args -> MediaStoreStreamHandler(context, args) } + + // channel for service management + backgroundChannel = MethodChannel(messenger, BACKGROUND_CHANNEL).apply { + setMethodCallHandler { call, result -> onMethodCall(call, result) } + } + } + + private fun startDartAnalysisService(entryIdStrings: Set<String>?) { + runBlocking { + FlutterUtils.runOnUiThread { + backgroundChannel?.invokeMethod( + "start", hashMapOf( + "entryIds" to entryIdStrings?.map { Integer.parseUnsignedInt(it) }?.toList(), + "force" to inputData.getBoolean(KEY_FORCE, false), + ) + ) + } + } + } + + private fun stopDartAnalysisService() { + runBlocking { + FlutterUtils.runOnUiThread { + backgroundChannel?.invokeMethod("stop", null) + } + } + } + + private fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "initialized" -> { + Log.d(LOG_TAG, "Analysis background channel is ready") + result.success(null) + } + + "updateNotification" -> defaultScope.launch { safeSuspend(call, result, ::updateNotification) } + + "stop" -> { + workCont?.takeIf { it.isActive }?.resume(null) + result.success(null) + } + + else -> result.notImplemented() + } + } + + private fun createNotificationChannel() { + val channel = NotificationChannelCompat.Builder(NOTIFICATION_CHANNEL, NotificationManagerCompat.IMPORTANCE_LOW) + .setName(applicationContext.getText(R.string.analysis_channel_name)) + .setShowBadge(false) + .build() + NotificationManagerCompat.from(applicationContext).createNotificationChannel(channel) + } + + private fun createForegroundInfo(title: String? = null, message: String? = null): ForegroundInfo { + val pendingIntentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + } else { + PendingIntent.FLAG_UPDATE_CURRENT + } + val openAppIntent = Intent(applicationContext, MainActivity::class.java).let { + PendingIntent.getActivity(applicationContext, MainActivity.OPEN_FROM_ANALYSIS_SERVICE, it, pendingIntentFlags) + } + val stopAction = NotificationCompat.Action.Builder( + R.drawable.ic_outline_stop_24, + applicationContext.getString(R.string.analysis_notification_action_stop), + WorkManager.getInstance(applicationContext).createCancelPendingIntent(id) + ).build() + val contentTitle = title ?: applicationContext.getText(R.string.analysis_notification_default_title) + val notification = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL) + .setContentTitle(contentTitle) + .setTicker(contentTitle) + .setContentText(message) + .setSmallIcon(R.drawable.ic_notification) + .setOngoing(true) + .setContentIntent(openAppIntent) + .addAction(stopAction) + .build() + // from Android 14 (API 34), foreground service type is mandatory for long-running workers: + // https://developer.android.com/guide/background/persistent/how-to/long-running + return when { + Build.VERSION.SDK_INT >= 35 -> ForegroundInfo(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING) + Build.VERSION.SDK_INT == 34 -> ForegroundInfo(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) + else -> ForegroundInfo(NOTIFICATION_ID, notification) + } + } + + private suspend fun updateNotification(call: MethodCall, result: MethodChannel.Result) { + val title = call.argument<String>("title") + val message = call.argument<String>("message") + setForeground(createForegroundInfo(title, message)) + result.success(null) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<AnalysisWorker>() + private const val BACKGROUND_CHANNEL = "deckers.thibault/aves/analysis_service_background" + const val SHARED_PREFERENCES_KEY = "analysis_service" + const val PREF_CALLBACK_HANDLE_KEY = "callback_handle" + const val PREF_ENTRY_IDS_KEY = "entry_ids" + + const val NOTIFICATION_CHANNEL = "analysis" + const val NOTIFICATION_ID = 1 + + const val KEY_FORCE = "force" + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetConfigureActivity.kt b/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetConfigureActivity.kt new file mode 100644 index 0000000..dad5ed8 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetConfigureActivity.kt @@ -0,0 +1,66 @@ +package deckers.thibault.aves + +import android.appwidget.AppWidgetManager +import android.content.Intent +import android.os.Bundle +import deckers.thibault.aves.model.FieldMap +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel + +class HomeWidgetSettingsActivity : MainActivity() { + private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID + + public override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + // cancel if user does not complete widget setup + setResult(RESULT_CANCELED) + + intent.extras?.let { + appWidgetId = it.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) + intentDataMap = extractIntentData(intent) + } + + if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { + finish() + return + } + } + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + + val messenger = flutterEngine.dartExecutor + MethodChannel(messenger, CHANNEL).setMethodCallHandler { call, result -> + when (call.method) { + "configure" -> { + result.success(null) + saveWidget() + } + else -> result.notImplemented() + } + } + } + + private fun saveWidget() { + val appWidgetManager = AppWidgetManager.getInstance(this) + val widgetInfo = appWidgetManager.getAppWidgetOptions(appWidgetId) + HomeWidgetProvider().onAppWidgetOptionsChanged(this, appWidgetManager, appWidgetId, widgetInfo) + + val intent = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) + setResult(RESULT_OK, intent) + finish() + } + + override fun extractIntentData(intent: Intent?): FieldMap { + return hashMapOf( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_WIDGET_SETTINGS, + INTENT_DATA_KEY_WIDGET_ID to appWidgetId, + ) + } + + companion object { + private const val CHANNEL = "deckers.thibault/aves/widget_configure" + } +} + diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetProvider.kt new file mode 100644 index 0000000..0d0b2ba --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetProvider.kt @@ -0,0 +1,342 @@ +package deckers.thibault.aves + +import android.app.PendingIntent +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProvider +import android.content.Context +import android.content.Intent +import android.content.res.Configuration +import android.graphics.Bitmap +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.util.Log +import android.util.SizeF +import android.widget.RemoteViews +import androidx.core.graphics.createBitmap +import androidx.core.net.toUri +import app.loup.streams_channel.StreamsChannel +import deckers.thibault.aves.channel.calls.DeviceHandler +import deckers.thibault.aves.channel.calls.MediaFetchObjectHandler +import deckers.thibault.aves.channel.calls.MediaStoreHandler +import deckers.thibault.aves.channel.calls.StorageHandler +import deckers.thibault.aves.channel.streams.darttoplatform.ImageByteStreamHandler +import deckers.thibault.aves.channel.streams.darttoplatform.MediaStoreStreamHandler +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.ContextUtils.devicePixelRatio +import deckers.thibault.aves.utils.FlutterUtils +import deckers.thibault.aves.utils.LogUtils +import io.flutter.FlutterInjector +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.embedding.engine.dart.DartExecutor +import io.flutter.plugin.common.MethodChannel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import java.nio.ByteBuffer +import kotlin.coroutines.Continuation +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlin.coroutines.suspendCoroutine +import kotlin.math.roundToInt + +class HomeWidgetProvider : AppWidgetProvider() { + private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { + Log.d(LOG_TAG, "Widget onUpdate widgetIds=${appWidgetIds.contentToString()}") + val pendingResult = goAsync() + defaultScope.launch { + for (widgetId in appWidgetIds) { + val widgetInfo = appWidgetManager.getAppWidgetOptions(widgetId) + + val backgroundProps = getProps(context, widgetId, widgetInfo, drawEntryImage = false) + updateWidgetImage(context, appWidgetManager, widgetId, backgroundProps) + + val imageProps = getProps(context, widgetId, widgetInfo, drawEntryImage = true, reuseEntry = false) + updateWidgetImage(context, appWidgetManager, widgetId, imageProps) + } + try { + pendingResult?.finish() + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to finish update for widgetIds=${appWidgetIds.contentToString()}", e) + } + } + } + + override fun onAppWidgetOptionsChanged(context: Context, appWidgetManager: AppWidgetManager?, widgetId: Int, widgetInfo: Bundle?) { + Log.d(LOG_TAG, "Widget onAppWidgetOptionsChanged widgetId=$widgetId") + appWidgetManager ?: return + widgetInfo ?: return + + if (imageByteFetchJob != null) { + imageByteFetchJob?.cancel() + } + imageByteFetchJob = defaultScope.launch { + delay(500) + val imageProps = getProps(context, widgetId, widgetInfo, drawEntryImage = true, reuseEntry = true) + updateWidgetImage(context, appWidgetManager, widgetId, imageProps) + } + } + + private fun getWidgetSizesDip(context: Context, widgetInfo: Bundle): List<SizeF> { + var sizes: List<SizeF>? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + widgetInfo.getParcelableArrayList(AppWidgetManager.OPTION_APPWIDGET_SIZES, SizeF::class.java) + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + @Suppress("deprecation") + widgetInfo.getParcelableArrayList(AppWidgetManager.OPTION_APPWIDGET_SIZES) + } else { + null + } + + if (sizes.isNullOrEmpty()) { + val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT + val widthKey = if (isPortrait) AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH else AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH + val heightKey = if (isPortrait) AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT else AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT + val widthDip = widgetInfo.getInt(widthKey) + val heightDip = widgetInfo.getInt(heightKey) + sizes = listOf(SizeF(widthDip.toFloat(), heightDip.toFloat())) + } + + return sizes + } + + private suspend fun getProps( + context: Context, + widgetId: Int, + widgetInfo: Bundle, + drawEntryImage: Boolean, + reuseEntry: Boolean = false, + ): FieldMap? { + val sizesDip = getWidgetSizesDip(context, widgetInfo) + if (sizesDip.isEmpty()) return null + + val sizeDip = sizesDip.first() + if (sizeDip.width == 0f || sizeDip.height == 0f) return null + + val sizesDipMap = sizesDip.map { size -> hashMapOf("widthDip" to size.width, "heightDip" to size.height) } + val isNightModeOn = (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES + + val params = hashMapOf( + "widgetId" to widgetId, + "sizesDip" to sizesDipMap, + "devicePixelRatio" to context.devicePixelRatio(), + "drawEntryImage" to drawEntryImage, + "reuseEntry" to reuseEntry, + "isSystemThemeDark" to isNightModeOn, + ).apply { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + put("cornerRadiusPx", context.resources.getDimension(android.R.dimen.system_app_widget_background_radius)) + } + } + + initFlutterEngine(context) + try { + val props = suspendCoroutine { cont -> + defaultScope.launch { + FlutterUtils.runOnUiThread { + tryDrawWidget(params, cont, 0) + } + } + } + @Suppress("unchecked_cast") + return props as FieldMap? + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to draw widget for widgetId=$widgetId sizesPx=$sizesDip", e) + } + return null + } + + private fun tryDrawWidget(params: HashMap<String, Any>, cont: Continuation<Any?>, drawRetry: Int) { + val messenger = flutterEngine!!.dartExecutor + val channel = MethodChannel(messenger, WIDGET_DRAW_CHANNEL) + channel.invokeMethod("drawWidget", params, object : MethodChannel.Result { + override fun success(result: Any?) { + cont.resume(result) + } + + override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) { + cont.resumeWithException(Exception("$errorCode: $errorMessage\n$errorDetails")) + } + + override fun notImplemented() { + if (drawRetry > DRAW_RETRY_MAX) { + cont.resumeWithException(Exception("not implemented")) + } else { + Handler(Looper.getMainLooper()).postDelayed({ + tryDrawWidget(params, cont, drawRetry + 1) + }, 2000L) + } + } + }) + } + + private fun updateWidgetImage( + context: Context, + appWidgetManager: AppWidgetManager, + widgetId: Int, + props: FieldMap?, + ) { + props ?: return + + val bytesBySizeDip = (props["bytesBySizeDip"] as List<*>?)?.mapNotNull { + if (it is Map<*, *>) { + val widthDip = (it["widthDip"] as Number?)?.toFloat() + val heightDip = (it["heightDip"] as Number?)?.toFloat() + val bytes = it["bytes"] as ByteArray? + if (widthDip != null && heightDip != null && bytes != null) { + Pair(SizeF(widthDip, heightDip), bytes) + } else null + } else null + } + val updateOnTap = props["updateOnTap"] as Boolean? + if (bytesBySizeDip == null || updateOnTap == null) { + Log.e(LOG_TAG, "missing arguments") + return + } + + if (bytesBySizeDip.isEmpty()) { + Log.e(LOG_TAG, "empty image list") + return + } + + val bitmaps = ArrayList<Bitmap>() + + fun createRemoteViewsForSize( + context: Context, + widgetId: Int, + sizeDip: SizeF, + bytes: ByteArray, + updateOnTap: Boolean, + ): RemoteViews? { + val density = context.devicePixelRatio() + val widthPx = (sizeDip.width * density).roundToInt() + val heightPx = (sizeDip.height * density).roundToInt() + + try { + val bitmap = createBitmap(widthPx, heightPx, Bitmap.Config.ARGB_8888).also { + bitmaps.add(it) + it.copyPixelsFromBuffer(ByteBuffer.wrap(bytes)) + } + + val pendingIntent = if (updateOnTap) buildUpdateIntent(context, widgetId) else buildOpenAppIntent(context, widgetId) + + return RemoteViews(context.packageName, R.layout.app_widget).apply { + setImageViewBitmap(R.id.widget_img, bitmap) + setOnClickPendingIntent(R.id.widget_img, pendingIntent) + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to draw widget", e) + } + return null + } + + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + // multiple rendering for all possible sizes + val views = RemoteViews( + bytesBySizeDip.associateBy( + { (sizeDip, _) -> sizeDip }, + { (sizeDip, bytes) -> createRemoteViewsForSize(context, widgetId, sizeDip, bytes, updateOnTap) }, + ).filterValues { it != null }.mapValues { (_, view) -> view!! } + ) + appWidgetManager.updateAppWidget(widgetId, views) + } else { + // single rendering + val (sizeDip, bytes) = bytesBySizeDip.first() + val views = createRemoteViewsForSize(context, widgetId, sizeDip, bytes, updateOnTap) + appWidgetManager.updateAppWidget(widgetId, views) + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to draw widget", e) + } finally { + bitmaps.forEach { it.recycle() } + bitmaps.clear() + } + } + + private fun buildUpdateIntent(context: Context, widgetId: Int): PendingIntent { + val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, "widget://$widgetId".toUri(), context, HomeWidgetProvider::class.java) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(widgetId)) + + return PendingIntent.getBroadcast( + context, + 0, + intent, + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + } else { + PendingIntent.FLAG_UPDATE_CURRENT + } + ) + } + + private fun buildOpenAppIntent(context: Context, widgetId: Int): PendingIntent { + // set a unique URI to prevent the intent (and its extras) from being shared by different widgets + val intent = Intent(MainActivity.INTENT_ACTION_WIDGET_OPEN, "widget://$widgetId".toUri(), context, MainActivity::class.java) + .putExtra(MainActivity.EXTRA_KEY_WIDGET_ID, widgetId) + + return PendingIntent.getActivity( + context, + 0, + intent, + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + } else { + PendingIntent.FLAG_UPDATE_CURRENT + } + ) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<HomeWidgetProvider>() + private const val WIDGET_DART_ENTRYPOINT = "widgetMain" + private const val WIDGET_DRAW_CHANNEL = "deckers.thibault/aves/widget_draw" + private const val DRAW_RETRY_MAX = 5 + + private var flutterEngine: FlutterEngine? = null + private var imageByteFetchJob: Job? = null + + private suspend fun initFlutterEngine(context: Context) { + if (flutterEngine != null) return + + FlutterUtils.runOnUiThread { + flutterEngine = FlutterEngine(context.applicationContext) + } + initChannels(context) + + flutterEngine!!.apply { + if (!dartExecutor.isExecutingDart) { + val appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath() + val entrypoint = DartExecutor.DartEntrypoint(appBundlePathOverride, WIDGET_DART_ENTRYPOINT) + FlutterUtils.runOnUiThread { + dartExecutor.executeDartEntrypoint(entrypoint) + } + } + } + } + + private fun initChannels(context: Context) { + val engine = flutterEngine + engine ?: throw Exception("Flutter engine is not initialized") + + val messenger = engine.dartExecutor + + // dart -> platform -> dart + // - need Context + MethodChannel(messenger, DeviceHandler.CHANNEL).setMethodCallHandler(DeviceHandler(context)) + MethodChannel(messenger, MediaStoreHandler.CHANNEL).setMethodCallHandler(MediaStoreHandler(context)) + MethodChannel(messenger, MediaFetchObjectHandler.CHANNEL).setMethodCallHandler(MediaFetchObjectHandler(context)) + MethodChannel(messenger, StorageHandler.CHANNEL).setMethodCallHandler(StorageHandler(context)) + + // result streaming: dart -> platform ->->-> dart + // - need Context + StreamsChannel(messenger, ImageByteStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageByteStreamHandler(context, args) } + StreamsChannel(messenger, MediaStoreStreamHandler.CHANNEL).setStreamHandlerFactory { args -> MediaStoreStreamHandler(context, args) } + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/MainActivity.kt b/android/app/src/main/kotlin/deckers/thibault/aves/MainActivity.kt new file mode 100644 index 0000000..84d56fd --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/MainActivity.kt @@ -0,0 +1,656 @@ +package deckers.thibault.aves + +import android.annotation.SuppressLint +import android.app.KeyguardManager +import android.app.SearchManager +import android.appwidget.AppWidgetManager +import android.content.ClipData +import android.content.Intent +import android.content.res.Configuration +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.os.TransactionTooLargeException +import android.provider.MediaStore +import android.util.Log +import androidx.annotation.RequiresApi +import androidx.core.content.pm.ShortcutInfoCompat +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.graphics.drawable.IconCompat +import androidx.core.net.toUri +import app.loup.streams_channel.StreamsChannel +import deckers.thibault.aves.channel.calls.AccessibilityHandler +import deckers.thibault.aves.channel.calls.AnalysisHandler +import deckers.thibault.aves.channel.calls.AppAdapterHandler +import deckers.thibault.aves.channel.calls.AppProfileHandler +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.channel.calls.DebugHandler +import deckers.thibault.aves.channel.calls.DeviceHandler +import deckers.thibault.aves.channel.calls.EmbeddedDataHandler +import deckers.thibault.aves.channel.calls.GeocodingHandler +import deckers.thibault.aves.channel.calls.GlobalSearchHandler +import deckers.thibault.aves.channel.calls.HomeWidgetHandler +import deckers.thibault.aves.channel.calls.MediaEditHandler +import deckers.thibault.aves.channel.calls.MediaFetchObjectHandler +import deckers.thibault.aves.channel.calls.MediaSessionHandler +import deckers.thibault.aves.channel.calls.MediaStoreHandler +import deckers.thibault.aves.channel.calls.MetadataEditHandler +import deckers.thibault.aves.channel.calls.MetadataFetchHandler +import deckers.thibault.aves.channel.calls.SecurityHandler +import deckers.thibault.aves.channel.calls.StorageHandler +import deckers.thibault.aves.channel.calls.WallpaperHandler +import deckers.thibault.aves.channel.calls.window.ActivityWindowHandler +import deckers.thibault.aves.channel.calls.window.WindowHandler +import deckers.thibault.aves.channel.streams.darttoplatform.ActivityResultStreamHandler +import deckers.thibault.aves.channel.streams.darttoplatform.ImageByteStreamHandler +import deckers.thibault.aves.channel.streams.darttoplatform.ImageOpStreamHandler +import deckers.thibault.aves.channel.streams.darttoplatform.MediaStoreStreamHandler +import deckers.thibault.aves.channel.streams.platformtodart.AnalysisStreamHandler +import deckers.thibault.aves.channel.streams.platformtodart.ErrorStreamHandler +import deckers.thibault.aves.channel.streams.platformtodart.IntentStreamHandler +import deckers.thibault.aves.channel.streams.platformtodart.MediaCommandStreamHandler +import deckers.thibault.aves.channel.streams.platformtodart.MediaStoreChangeStreamHandler +import deckers.thibault.aves.channel.streams.platformtodart.SettingsChangeStreamHandler +import deckers.thibault.aves.channel.streams.platformtodart.WindowChangeStreamHandler +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.anyCauseIs +import deckers.thibault.aves.utils.getParcelableExtraCompat +import io.flutter.embedding.android.FlutterFragmentActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ConcurrentHashMap + +// `FlutterFragmentActivity` because of local auth plugin +open class MainActivity : FlutterFragmentActivity() { + private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + private lateinit var mediaStoreChangeStreamHandler: MediaStoreChangeStreamHandler + private lateinit var settingsChangeStreamHandler: SettingsChangeStreamHandler + private lateinit var windowChangeStreamHandler: WindowChangeStreamHandler + private lateinit var intentStreamHandler: IntentStreamHandler + private lateinit var analysisStreamHandler: AnalysisStreamHandler + internal lateinit var intentDataMap: MutableMap<String, Any?> + private lateinit var analysisHandler: AnalysisHandler + private lateinit var mediaSessionHandler: MediaSessionHandler + + override fun onCreate(savedInstanceState: Bundle?) { + Log.i(LOG_TAG, "onCreate intent=$intent") + logExtras(intent, "onCreate") + +// StrictMode.setThreadPolicy( +// StrictMode.ThreadPolicy.Builder() +// .detectAll() +// .penaltyLog() +// .build() +// ) +// StrictMode.setVmPolicy( +// StrictMode.VmPolicy.Builder() +// .detectAll() +// .penaltyLog() +// .build() +// ) + super.onCreate(savedInstanceState) + } + + private fun logExtras(intent: Intent?, method: String) { + try { + intent?.extras?.takeUnless { it.isEmpty }?.let { + Log.i(LOG_TAG, "$method intent extras=$it") + } + } catch (e: Exception) { + // accessing extras may fail if their type comes from sending app + Log.w(LOG_TAG, "failed to parse extras", e) + } + } + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + + val messenger = flutterEngine.dartExecutor + + // notification: platform -> dart + analysisStreamHandler = AnalysisStreamHandler().apply { + EventChannel(messenger, AnalysisStreamHandler.CHANNEL).setStreamHandler(this) + } + errorStreamHandler = ErrorStreamHandler().apply { + EventChannel(messenger, ErrorStreamHandler.CHANNEL).setStreamHandler(this) + } + mediaStoreChangeStreamHandler = MediaStoreChangeStreamHandler(this).apply { + EventChannel(messenger, MediaStoreChangeStreamHandler.CHANNEL).setStreamHandler(this) + } + settingsChangeStreamHandler = SettingsChangeStreamHandler(this).apply { + EventChannel(messenger, SettingsChangeStreamHandler.CHANNEL).setStreamHandler(this) + } + windowChangeStreamHandler = WindowChangeStreamHandler().apply { + EventChannel(messenger, WindowChangeStreamHandler.CHANNEL).setStreamHandler(this) + } + val mediaCommandStreamHandler = MediaCommandStreamHandler().apply { + EventChannel(messenger, MediaCommandStreamHandler.CHANNEL).setStreamHandler(this) + } + + // dart -> platform -> dart + // - need Context + analysisHandler = AnalysisHandler(this, ::onAnalysisCompleted) + mediaSessionHandler = MediaSessionHandler(this, mediaCommandStreamHandler) + MethodChannel(messenger, AnalysisHandler.CHANNEL).setMethodCallHandler(analysisHandler) + MethodChannel(messenger, AppAdapterHandler.CHANNEL).setMethodCallHandler(AppAdapterHandler(this)) + MethodChannel(messenger, DebugHandler.CHANNEL).setMethodCallHandler(DebugHandler(this)) + MethodChannel(messenger, DeviceHandler.CHANNEL).setMethodCallHandler(DeviceHandler(this)) + MethodChannel(messenger, EmbeddedDataHandler.CHANNEL).setMethodCallHandler(EmbeddedDataHandler(this)) + MethodChannel(messenger, GeocodingHandler.CHANNEL).setMethodCallHandler(GeocodingHandler(this)) + MethodChannel(messenger, GlobalSearchHandler.CHANNEL).setMethodCallHandler(GlobalSearchHandler(this)) + MethodChannel(messenger, HomeWidgetHandler.CHANNEL).setMethodCallHandler(HomeWidgetHandler(this)) + MethodChannel(messenger, MediaFetchObjectHandler.CHANNEL).setMethodCallHandler(MediaFetchObjectHandler(this)) + MethodChannel(messenger, MediaSessionHandler.CHANNEL).setMethodCallHandler(mediaSessionHandler) + MethodChannel(messenger, MediaStoreHandler.CHANNEL).setMethodCallHandler(MediaStoreHandler(this)) + MethodChannel(messenger, MetadataFetchHandler.CHANNEL).setMethodCallHandler(MetadataFetchHandler(this)) + MethodChannel(messenger, SecurityHandler.CHANNEL).setMethodCallHandler(SecurityHandler(this)) + MethodChannel(messenger, StorageHandler.CHANNEL).setMethodCallHandler(StorageHandler(this)) + // - need ContextWrapper + MethodChannel(messenger, AccessibilityHandler.CHANNEL).setMethodCallHandler(AccessibilityHandler(this)) + MethodChannel(messenger, MediaEditHandler.CHANNEL).setMethodCallHandler(MediaEditHandler(this)) + MethodChannel(messenger, MetadataEditHandler.CHANNEL).setMethodCallHandler(MetadataEditHandler(this)) + MethodChannel(messenger, WallpaperHandler.CHANNEL).setMethodCallHandler(WallpaperHandler(this)) + // - need Activity + MethodChannel(messenger, AppProfileHandler.CHANNEL).setMethodCallHandler(AppProfileHandler(this)) + MethodChannel(messenger, WindowHandler.CHANNEL).setMethodCallHandler(ActivityWindowHandler(this)) + + // result streaming: dart -> platform ->->-> dart + // - need Context + StreamsChannel(messenger, ImageByteStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageByteStreamHandler(this, args) } + StreamsChannel(messenger, MediaStoreStreamHandler.CHANNEL).setStreamHandlerFactory { args -> MediaStoreStreamHandler(this, args) } + // - need Activity + StreamsChannel(messenger, ImageOpStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageOpStreamHandler(this, args) } + StreamsChannel(messenger, ActivityResultStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ActivityResultStreamHandler(this, args) } + + // intent handling + // notification: platform -> dart + intentStreamHandler = IntentStreamHandler().apply { + EventChannel(messenger, IntentStreamHandler.CHANNEL).setStreamHandler(this) + } + // intent detail & result: dart -> platform + intentDataMap = extractIntentData(intent) + MethodChannel(messenger, INTENT_CHANNEL).setMethodCallHandler { call, result -> + when (call.method) { + "getIntentData" -> { + result.success(intentDataMap) + intentDataMap.clear() + } + + "submitPickedItems" -> safe(call, result, ::submitPickedItems) + "submitPickedCollectionFilters" -> submitPickedCollectionFilters(call) + } + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { + defaultScope.launch { setupShortcuts() } + } + } + + override fun onStart() { + Log.i(LOG_TAG, "onStart") + super.onStart() + analysisHandler.attachToActivity() + + // as of Flutter v3.0.1, the window `viewInsets` and `viewPadding` + // are incorrect on startup in some environments (e.g. API 29 emulator), + // so we manually request to apply the insets to update the window metrics + Handler(Looper.getMainLooper()).postDelayed({ + window.decorView.requestApplyInsets() + }, 100) + } + + override fun onStop() { + Log.i(LOG_TAG, "onStop") + super.onStop() + } + + override fun onDestroy() { + Log.i(LOG_TAG, "onDestroy") + mediaSessionHandler.dispose() + mediaStoreChangeStreamHandler.dispose() + settingsChangeStreamHandler.dispose() + try { + super.onDestroy() + } catch (e: Exception) { + // on Android 11, app may crash as follows: + // `Fatal Exception:` + // `java.lang.RuntimeException: Unable to destroy activity {deckers.thibault.aves/deckers.thibault.aves.MainActivity}:` + // `java.lang.IllegalArgumentException: NetworkCallback was not registered` + // related to this error: + // `Package android does not belong to 10162` + // cf https://issuetracker.google.com/issues/175055271 + Log.e(LOG_TAG, "failed while destroying activity", e) + } + } + + override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean) { + super.onMultiWindowModeChanged(isInMultiWindowMode) + notifyWindowModeChanged() + } + + override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean, newConfig: Configuration) { + super.onMultiWindowModeChanged(isInMultiWindowMode, newConfig) + notifyWindowModeChanged() + } + + override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) { + super.onPictureInPictureModeChanged(isInPictureInPictureMode) + notifyWindowModeChanged() + } + + override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { + super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) + notifyWindowModeChanged() + } + + private fun notifyWindowModeChanged() = windowChangeStreamHandler.notifyWindowModeChange() + + override fun onNewIntent(intent: Intent) { + Log.i(LOG_TAG, "onNewIntent intent=$intent") + logExtras(intent, "onNewIntent") + super.onNewIntent(intent) + intentStreamHandler.notifyNewIntent(extractIntentData(intent)) + } + + @Deprecated("Deprecated in Java") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + Log.i(LOG_TAG, "onActivityResult requestCode=$requestCode resultCode=$resultCode data=$data") + logExtras(data, "onActivityResult") + super.onActivityResult(requestCode, resultCode, data) + when (requestCode) { + DOCUMENT_TREE_ACCESS_REQUEST -> onDocumentTreeAccessResult(requestCode, resultCode, data) + DELETE_SINGLE_PERMISSION_REQUEST, + MEDIA_WRITE_BULK_PERMISSION_REQUEST -> onScopedStoragePermissionResult(resultCode) + + CREATE_FILE_REQUEST, + OPEN_FILE_REQUEST -> onStorageAccessResult(requestCode, data?.data) + + PICK_COLLECTION_FILTERS_REQUEST -> onCollectionFiltersPickResult(resultCode, data) + EDIT_REQUEST -> onEditResult(resultCode, data) + } + } + + private fun onCollectionFiltersPickResult(resultCode: Int, intent: Intent?) { + val filters = if (resultCode == RESULT_OK) extractFiltersFromIntent(intent) else null + pendingCollectionFilterPickHandler?.let { it(filters) } + } + + private fun onEditResult(resultCode: Int, intent: Intent?) { + val fields: FieldMap? = if (resultCode == RESULT_OK) hashMapOf( + "uri" to intent?.data?.toString(), + "mimeType" to intent?.type, + ) else null + pendingEditIntentHandler?.let { it(fields) } + } + + private fun onDocumentTreeAccessResult(requestCode: Int, resultCode: Int, intent: Intent?) { + val treeUri = intent?.data + if (resultCode != RESULT_OK || treeUri == null) { + onStorageAccessResult(requestCode, null) + return + } + + val canPersist = (intent.flags and Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0 + @SuppressLint("WrongConstant") + if (canPersist) { + // save access permissions across reboots + val takeFlags = (intent.flags + and (Intent.FLAG_GRANT_READ_URI_PERMISSION + or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) + try { + contentResolver.takePersistableUriPermission(treeUri, takeFlags) + } catch (e: SecurityException) { + Log.w(LOG_TAG, "failed to take persistable URI permission for uri=$treeUri", e) + } + } + + // resume pending action + onStorageAccessResult(requestCode, treeUri) + } + + private fun onScopedStoragePermissionResult(resultCode: Int) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + pendingScopedStoragePermissionCompleter?.complete(resultCode == RESULT_OK) + } + } + + open fun extractIntentData(intent: Intent?): FieldMap { + when (val action = intent?.action) { + Intent.ACTION_MAIN -> { + return hashMapOf( + INTENT_DATA_KEY_PAGE to intent.getStringExtra(EXTRA_KEY_PAGE), + INTENT_DATA_KEY_FILTERS to extractFiltersFromIntent(intent), + INTENT_DATA_KEY_EXPLORER_PATH to intent.getStringExtra(EXTRA_KEY_EXPLORER_PATH), + ) + } + + Intent.ACTION_VIEW, + Intent.ACTION_SEND, + MediaStore.ACTION_REVIEW, + MediaStore.ACTION_REVIEW_SECURE, + "com.android.camera.action.REVIEW", + "com.android.camera.action.SPLIT_SCREEN_REVIEW" -> { + (intent.data ?: intent.getParcelableExtraCompat<Uri>(Intent.EXTRA_STREAM))?.let { uri -> + if (uri.scheme == "geo") { + return hashMapOf( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_VIEW_GEO, + INTENT_DATA_KEY_URI to uri.toString(), + INTENT_DATA_KEY_FILTERS to extractFiltersFromIntent(intent), + ) + } + + // MIME type is optional + val type = intent.type ?: intent.resolveType(this) + val fields = hashMapOf<String, Any?>( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_VIEW, + INTENT_DATA_KEY_MIME_TYPE to type, + INTENT_DATA_KEY_URI to uri.toString(), + ) + + val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager + val isLocked = keyguardManager.isKeyguardLocked + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { + setShowWhenLocked(isLocked) + } + if (isLocked) { + // device is locked, so access to content is limited to intent URI by default + fields[INTENT_DATA_KEY_SECURE_URIS] = listOf(uri.toString()) + } + + if (action == MediaStore.ACTION_REVIEW_SECURE) { + val uris = ArrayList<String>() + intent.clipData?.let { clipData -> + for (i in 0 until clipData.itemCount) { + clipData.getItemAt(i).uri?.let { uris.add(it.toString()) } + } + } + if (uris.isNotEmpty()) { + fields[INTENT_DATA_KEY_SECURE_URIS] = uris + } + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && intent.hasExtra(MediaStore.EXTRA_BRIGHTNESS)) { + fields[INTENT_DATA_KEY_BRIGHTNESS] = intent.getFloatExtra(MediaStore.EXTRA_BRIGHTNESS, 0f) + } + + return fields + } + } + + Intent.ACTION_EDIT -> { + (intent.data ?: intent.getParcelableExtraCompat<Uri>(Intent.EXTRA_STREAM))?.let { uri -> + // MIME type is optional + val type = intent.type ?: intent.resolveType(this) + return hashMapOf( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_EDIT, + INTENT_DATA_KEY_MIME_TYPE to type, + INTENT_DATA_KEY_URI to uri.toString(), + ) + } + } + + Intent.ACTION_GET_CONTENT, Intent.ACTION_PICK -> { + return hashMapOf( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_PICK_ITEMS, + INTENT_DATA_KEY_MIME_TYPE to intent.type, + INTENT_DATA_KEY_MIME_TYPES to intent.getStringArrayExtra(Intent.EXTRA_MIME_TYPES)?.toList(), + INTENT_DATA_KEY_ALLOW_MULTIPLE to intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false), + ) + } + + Intent.ACTION_SEARCH -> { + val viewUri = intent.dataString + return if (viewUri != null) hashMapOf( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_VIEW, + INTENT_DATA_KEY_MIME_TYPE to intent.getStringExtra(SearchManager.EXTRA_DATA_KEY), + INTENT_DATA_KEY_URI to viewUri, + ) else hashMapOf( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_SEARCH, + INTENT_DATA_KEY_QUERY to intent.getStringExtra(SearchManager.QUERY), + ) + } + + INTENT_ACTION_PICK_COLLECTION_FILTERS -> { + val initialFilters = extractFiltersFromIntent(intent) + return hashMapOf( + INTENT_DATA_KEY_ACTION to action, + INTENT_DATA_KEY_FILTERS to initialFilters, + ) + } + + INTENT_ACTION_WIDGET_OPEN -> { + val widgetId = intent.getIntExtra(EXTRA_KEY_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) + if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) { + return hashMapOf( + INTENT_DATA_KEY_ACTION to action, + INTENT_DATA_KEY_WIDGET_ID to widgetId, + ) + } + } + + Intent.ACTION_RUN -> { + // flutter run + } + + else -> { + Log.w(LOG_TAG, "unhandled intent action=${intent?.action}") + } + } + return HashMap() + } + + private fun extractFiltersFromIntent(intent: Intent?): List<String>? { + intent ?: return null + + val filters = intent.getStringArrayExtra(EXTRA_KEY_FILTERS_ARRAY)?.toList() + if (filters != null) return filters + + // fallback for shortcuts created on API <26 + val filterString = intent.getStringExtra(EXTRA_KEY_FILTERS_STRING) + if (filterString != null) { + return filterString.split(EXTRA_STRING_ARRAY_SEPARATOR) + } + + return null + } + + open fun submitPickedItems(call: MethodCall, result: MethodChannel.Result) { + val pickedUris = call.argument<List<String>>("uris") + if (pickedUris.isNullOrEmpty()) { + setResult(RESULT_CANCELED) + // move code triggering `Binder` call off the main thread + defaultScope.launch { finish() } + return + } + + val toUri = { uriString: String -> AppAdapterHandler.getShareableUri(this@MainActivity, uriString.toUri()) } + val intent = Intent().apply { + val firstUri = toUri(pickedUris.first()) + if (pickedUris.size == 1) { + data = firstUri + } else { + clipData = ClipData.newUri(contentResolver, null, firstUri).apply { + pickedUris.drop(1).forEach { + addItem(ClipData.Item(toUri(it))) + } + } + } + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + } + // move code triggering `Binder` call off the main thread + defaultScope.launch { + submitPickedItemsIntent(intent, result) + } + } + + private fun submitPickedItemsIntent(intent: Intent, result: MethodChannel.Result) { + try { + setResult(RESULT_OK, intent) + finish() + } catch (e: Exception) { + setResult(RESULT_CANCELED) + if (e is SecurityException && intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0) { + // in some environments, providing the write flag yields a `SecurityException`: + // "UID XXXX does not have permission to content://XXXX" + // so we retry without it + Log.i(LOG_TAG, "retry submitting picked items without FLAG_GRANT_WRITE_URI_PERMISSION") + intent.flags = intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION.inv() + submitPickedItemsIntent(intent, result) + } else if (e.anyCauseIs<TransactionTooLargeException>()) { + result.error("submitPickedItems-large", "transaction too large with ${intent.clipData?.itemCount} URIs", e) + } else { + result.error("submitPickedItems-exception", "failed to pick ${intent.clipData?.itemCount} URIs", e) + } + } + } + + private fun submitPickedCollectionFilters(call: MethodCall) { + val filters = call.argument<List<String>>("filters") + if (filters != null) { + val intent = Intent() + .putExtra(EXTRA_KEY_FILTERS_ARRAY, filters.toTypedArray()) + .putExtra(EXTRA_KEY_FILTERS_STRING, filters.joinToString(EXTRA_STRING_ARRAY_SEPARATOR)) + setResult(RESULT_OK, intent) + } else { + setResult(RESULT_CANCELED) + } + finish() + } + + @RequiresApi(Build.VERSION_CODES.N_MR1) + private fun setupShortcuts() { + // do not use 'route' as extra key, as the Flutter framework acts on it + + // shortcut adaptive icons are placed in `mipmap`, not `drawable`, + // so that foreground is rendered at the intended scale + val supportAdaptiveIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O + + val search = ShortcutInfoCompat.Builder(this, "search") + .setShortLabel(getString(R.string.search_shortcut_short_label)) + .setIcon(IconCompat.createWithResource(this, if (supportAdaptiveIcon) R.mipmap.ic_shortcut_search else R.drawable.ic_shortcut_search)) + .setIntent( + Intent(Intent.ACTION_MAIN, null, this, MainActivity::class.java) + .putExtra(EXTRA_KEY_PAGE, SEARCH_PAGE_ROUTE_NAME) + ) + .build() + + val map = ShortcutInfoCompat.Builder(this, "map") + .setShortLabel(getString(R.string.map_shortcut_short_label)) + .setIcon(IconCompat.createWithResource(this, if (supportAdaptiveIcon) R.mipmap.ic_shortcut_map else R.drawable.ic_shortcut_map)) + .setIntent( + Intent(Intent.ACTION_MAIN, null, this, MainActivity::class.java) + .putExtra(EXTRA_KEY_PAGE, MAP_PAGE_ROUTE_NAME) + ) + .build() + + val videos = ShortcutInfoCompat.Builder(this, "videos") + .setShortLabel(getString(R.string.videos_shortcut_short_label)) + .setIcon(IconCompat.createWithResource(this, if (supportAdaptiveIcon) R.mipmap.ic_shortcut_movie else R.drawable.ic_shortcut_movie)) + .setIntent( + Intent(Intent.ACTION_MAIN, null, this, MainActivity::class.java) + .putExtra(EXTRA_KEY_PAGE, COLLECTION_PAGE_ROUTE_NAME) + .putExtra("filters", arrayOf("{\"type\":\"mime\",\"mime\":\"video/*\"}")) + ) + .build() + + val shortcutInfoList = listOf(videos, search, map) + ShortcutManagerCompat.setDynamicShortcuts(this, shortcutInfoList) + Log.i(LOG_TAG, "set shortcuts: ${shortcutInfoList.joinToString(", ") { v -> v.id }}") + } + + private fun onAnalysisCompleted() { + analysisStreamHandler.notifyCompletion() + } + + companion object { + private val LOG_TAG = LogUtils.createTag<MainActivity>() + const val INTENT_CHANNEL = "deckers.thibault/aves/intent" + const val EXTRA_STRING_ARRAY_SEPARATOR = "###" + const val DOCUMENT_TREE_ACCESS_REQUEST = 1 + const val OPEN_FROM_ANALYSIS_SERVICE = 2 + const val CREATE_FILE_REQUEST = 3 + const val OPEN_FILE_REQUEST = 4 + const val DELETE_SINGLE_PERMISSION_REQUEST = 5 + const val MEDIA_WRITE_BULK_PERMISSION_REQUEST = 6 + const val PICK_COLLECTION_FILTERS_REQUEST = 7 + const val EDIT_REQUEST = 8 + + const val INTENT_ACTION_EDIT = "edit" + const val INTENT_ACTION_PICK_ITEMS = "pick_items" + const val INTENT_ACTION_PICK_COLLECTION_FILTERS = "pick_collection_filters" + const val INTENT_ACTION_SCREEN_SAVER = "screen_saver" + const val INTENT_ACTION_SCREEN_SAVER_SETTINGS = "screen_saver_settings" + const val INTENT_ACTION_SEARCH = "search" + const val INTENT_ACTION_SET_WALLPAPER = "set_wallpaper" + const val INTENT_ACTION_VIEW = "view" + const val INTENT_ACTION_VIEW_GEO = "view_geo" + const val INTENT_ACTION_WIDGET_OPEN = "widget_open" + const val INTENT_ACTION_WIDGET_SETTINGS = "widget_settings" + + const val INTENT_DATA_KEY_ACTION = "action" + const val INTENT_DATA_KEY_ALLOW_MULTIPLE = "allowMultiple" + const val INTENT_DATA_KEY_BRIGHTNESS = "brightness" + const val INTENT_DATA_KEY_EXPLORER_PATH = "explorerPath" + const val INTENT_DATA_KEY_FILTERS = "filters" + const val INTENT_DATA_KEY_MIME_TYPE = "mimeType" + const val INTENT_DATA_KEY_MIME_TYPES = "mimeTypes" + const val INTENT_DATA_KEY_PAGE = "page" + const val INTENT_DATA_KEY_QUERY = "query" + const val INTENT_DATA_KEY_SECURE_URIS = "secureUris" + const val INTENT_DATA_KEY_URI = "uri" + const val INTENT_DATA_KEY_WIDGET_ID = "widgetId" + + const val EXTRA_KEY_PAGE = "page" + const val EXTRA_KEY_EXPLORER_PATH = "explorerPath" + const val EXTRA_KEY_FILTERS_ARRAY = "filters" + const val EXTRA_KEY_FILTERS_STRING = "filtersString" + const val EXTRA_KEY_WIDGET_ID = "widgetId" + + // dart page routes + const val COLLECTION_PAGE_ROUTE_NAME = "/collection" + const val ENTRY_VIEWER_PAGE_ROUTE_NAME = "/viewer" + const val EXPLORER_PAGE_ROUTE_NAME = "/explorer" + const val MAP_PAGE_ROUTE_NAME = "/map" + const val SEARCH_PAGE_ROUTE_NAME = "/search" + + // request code to pending runnable + val pendingStorageAccessResultHandlers = ConcurrentHashMap<Int, PendingStorageAccessResultHandler>() + + var pendingScopedStoragePermissionCompleter: CompletableFuture<Boolean>? = null + + var pendingCollectionFilterPickHandler: ((filters: List<String>?) -> Unit)? = null + + var pendingEditIntentHandler: ((fields: FieldMap?) -> Unit)? = null + + private fun onStorageAccessResult(requestCode: Int, uri: Uri?) { + Log.i(LOG_TAG, "onStorageAccessResult with requestCode=$requestCode, uri=$uri") + val handler = pendingStorageAccessResultHandlers.remove(requestCode) ?: return + if (uri != null) { + handler.onGranted(uri) + } else { + handler.onDenied() + } + } + + private var errorStreamHandler: ErrorStreamHandler? = null + + fun notifyError(error: String) { + Log.e(LOG_TAG, "notifyError error=$error") + errorStreamHandler?.notifyError(error) + } + } +} + +// onGranted: user selected a directory/file (with no guarantee that it matches the requested `path`) +// onDenied: user cancelled +data class PendingStorageAccessResultHandler(val path: String?, val onGranted: (uri: Uri) -> Unit, val onDenied: () -> Unit) diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/MediaPlaybackService.kt b/android/app/src/main/kotlin/deckers/thibault/aves/MediaPlaybackService.kt new file mode 100644 index 0000000..ed97c54 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/MediaPlaybackService.kt @@ -0,0 +1,18 @@ +package deckers.thibault.aves + +import android.os.Bundle +import android.support.v4.media.MediaBrowserCompat +import androidx.media.MediaBrowserServiceCompat + +// dummy service to handle media button events +// when there is no active media sessions +class MediaPlaybackService : MediaBrowserServiceCompat() { + override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? { + return null + } + + override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) { + val children = mutableListOf<MediaBrowserCompat.MediaItem>() + result.sendResult(children) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverService.kt b/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverService.kt new file mode 100644 index 0000000..d65e708 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverService.kt @@ -0,0 +1,155 @@ +package deckers.thibault.aves + +import android.service.dreams.DreamService +import android.util.Log +import android.view.View +import app.loup.streams_channel.StreamsChannel +import deckers.thibault.aves.channel.calls.AccessibilityHandler +import deckers.thibault.aves.channel.calls.DeviceHandler +import deckers.thibault.aves.channel.calls.EmbeddedDataHandler +import deckers.thibault.aves.channel.calls.MediaFetchObjectHandler +import deckers.thibault.aves.channel.calls.MediaSessionHandler +import deckers.thibault.aves.channel.calls.MediaStoreHandler +import deckers.thibault.aves.channel.calls.MetadataFetchHandler +import deckers.thibault.aves.channel.calls.StorageHandler +import deckers.thibault.aves.channel.calls.window.ServiceWindowHandler +import deckers.thibault.aves.channel.calls.window.WindowHandler +import deckers.thibault.aves.channel.streams.darttoplatform.ImageByteStreamHandler +import deckers.thibault.aves.channel.streams.darttoplatform.MediaStoreStreamHandler +import deckers.thibault.aves.channel.streams.platformtodart.MediaCommandStreamHandler +import deckers.thibault.aves.utils.LogUtils +import io.flutter.FlutterInjector +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.android.FlutterSurfaceView +import io.flutter.embedding.android.FlutterView +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint +import io.flutter.embedding.engine.plugins.util.GeneratedPluginRegister +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodChannel + +// for FlutterView-level integration, cf https://docs.flutter.dev/development/add-to-app/android/add-flutter-view +class ScreenSaverService : DreamService() { + private var flutterEngine: FlutterEngine? = null + private var flutterView: FlutterView? = null + private lateinit var mediaSessionHandler: MediaSessionHandler + + override fun onAttachedToWindow() { + Log.i(LOG_TAG, "onAttachedToWindow") + super.onAttachedToWindow() + initDream() + createEngine() + setContentView(createView()) + } + + override fun onDreamingStarted() { + Log.i(LOG_TAG, "onDreamingStarted") + super.onDreamingStarted() + onStart() + } + + override fun onDreamingStopped() { + Log.i(LOG_TAG, "onDreamingStopped") + release() + super.onDreamingStopped() + } + + override fun onDetachedFromWindow() { + Log.i(LOG_TAG, "onDetachedFromWindow") + destroyView() + super.onDetachedFromWindow() + } + + private fun initDream() { + isInteractive = false + isFullscreen = true + } + + private fun createEngine() { + flutterEngine = flutterEngine ?: FlutterEngine(this, null, false) + GeneratedPluginRegister.registerGeneratedPlugins(flutterEngine!!) + initChannels() + } + + private fun createView(): View { + flutterView = FlutterView(this, FlutterSurfaceView(this)).apply { + id = FlutterActivity.FLUTTER_VIEW_ID + attachToFlutterEngine(flutterEngine!!) + } + return flutterView!! + } + + private fun destroyView() { + flutterEngine?.lifecycleChannel?.appIsDetached() + flutterView?.detachFromFlutterEngine() + } + + private fun release() { + destroyView() + mediaSessionHandler.dispose() + flutterEngine = null + flutterView = null + } + + private fun onStart() { + flutterEngine!!.apply { + if (!dartExecutor.isExecutingDart) { + navigationChannel.setInitialRoute(DEFAULT_INITIAL_ROUTE) + val appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath() + val entrypoint = DartEntrypoint(appBundlePathOverride, DEFAULT_DART_ENTRYPOINT) + dartExecutor.executeDartEntrypoint(entrypoint) + } + lifecycleChannel.appIsResumed() + } + } + + private fun initChannels() { + val messenger = flutterEngine!!.dartExecutor + + // notification: platform -> dart + val mediaCommandStreamHandler = MediaCommandStreamHandler().apply { + EventChannel(messenger, MediaCommandStreamHandler.CHANNEL).setStreamHandler(this) + } + + // dart -> platform -> dart + // - need Context + mediaSessionHandler = MediaSessionHandler(this, mediaCommandStreamHandler) + MethodChannel(messenger, DeviceHandler.CHANNEL).setMethodCallHandler(DeviceHandler(this)) + MethodChannel(messenger, EmbeddedDataHandler.CHANNEL).setMethodCallHandler(EmbeddedDataHandler(this)) + MethodChannel(messenger, MediaFetchObjectHandler.CHANNEL).setMethodCallHandler(MediaFetchObjectHandler(this)) + MethodChannel(messenger, MediaSessionHandler.CHANNEL).setMethodCallHandler(mediaSessionHandler) + MethodChannel(messenger, MediaStoreHandler.CHANNEL).setMethodCallHandler(MediaStoreHandler(this)) + MethodChannel(messenger, MetadataFetchHandler.CHANNEL).setMethodCallHandler(MetadataFetchHandler(this)) + MethodChannel(messenger, StorageHandler.CHANNEL).setMethodCallHandler(StorageHandler(this)) + // - need ContextWrapper + MethodChannel(messenger, AccessibilityHandler.CHANNEL).setMethodCallHandler(AccessibilityHandler(this)) + // - need Service + MethodChannel(messenger, WindowHandler.CHANNEL).setMethodCallHandler(ServiceWindowHandler(this)) + + // result streaming: dart -> platform ->->-> dart + // - need Context + StreamsChannel(messenger, ImageByteStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageByteStreamHandler(this, args) } + StreamsChannel(messenger, MediaStoreStreamHandler.CHANNEL).setStreamHandlerFactory { args -> MediaStoreStreamHandler(this, args) } + + // intent handling + // detail fetch: dart -> platform + MethodChannel(messenger, MainActivity.INTENT_CHANNEL).setMethodCallHandler { call, result -> + when (call.method) { + "getIntentData" -> { + result.success(intentDataMap) + } + } + } + } + + companion object { + private val LOG_TAG = LogUtils.createTag<ScreenSaverService>() + private val intentDataMap: Map<String, Any?> = hashMapOf( + MainActivity.INTENT_DATA_KEY_ACTION to MainActivity.INTENT_ACTION_SCREEN_SAVER, + ) + + // from `FlutterActivityLaunchConfigs` + const val DEFAULT_DART_ENTRYPOINT = "main" + const val DEFAULT_INITIAL_ROUTE = "/" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverSettingsActivity.kt b/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverSettingsActivity.kt new file mode 100644 index 0000000..2d7e070 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverSettingsActivity.kt @@ -0,0 +1,12 @@ +package deckers.thibault.aves + +import android.content.Intent +import deckers.thibault.aves.model.FieldMap + +class ScreenSaverSettingsActivity : MainActivity() { + override fun extractIntentData(intent: Intent?): FieldMap { + return hashMapOf( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_SCREEN_SAVER_SETTINGS, + ) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/SearchSuggestionsProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/SearchSuggestionsProvider.kt new file mode 100644 index 0000000..e182f56 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/SearchSuggestionsProvider.kt @@ -0,0 +1,147 @@ +package deckers.thibault.aves + +import android.app.SearchManager +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.database.Cursor +import android.database.MatrixCursor +import android.net.Uri +import android.os.Build +import android.text.format.DateFormat +import android.util.Log +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.ContextUtils.resourceUri +import deckers.thibault.aves.utils.FlutterUtils +import deckers.thibault.aves.utils.LogUtils +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import java.util.Locale +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlin.coroutines.suspendCoroutine + +class SearchSuggestionsProvider : ContentProvider() { + private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? { + return selectionArgs?.firstOrNull()?.let { query -> + // Samsung Finder does not support: + // - resource ID as value for SUGGEST_COLUMN_ICON_1 + // - SUGGEST_COLUMN_ICON_2 + // - SUGGEST_COLUMN_RESULT_CARD_IMAGE + val columns = arrayOf( + SearchManager.SUGGEST_COLUMN_INTENT_DATA, + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA, + SearchManager.SUGGEST_COLUMN_CONTENT_TYPE, + SearchManager.SUGGEST_COLUMN_TEXT_1, + SearchManager.SUGGEST_COLUMN_TEXT_2, + SearchManager.SUGGEST_COLUMN_ICON_1, + ) + + val matrixCursor = MatrixCursor(columns) + context?.let { context -> + // shortcut adaptive icons are placed in `mipmap`, not `drawable`, + // so that foreground is rendered at the intended scale + val supportAdaptiveIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O + + val searchShortcutTitle = "${context.resources.getString(R.string.search_shortcut_short_label)} $query" + val searchShortcutIcon = context.resourceUri(if (supportAdaptiveIcon) R.mipmap.ic_shortcut_search else R.drawable.ic_shortcut_search) + matrixCursor.addRow(arrayOf(null, null, null, searchShortcutTitle, null, searchShortcutIcon)) + + runBlocking { + getSuggestions(context, query).forEach { + val data = it["data"] + val mimeType = it["mimeType"] + val title = it["title"] + val subtitle = it["subtitle"] + val iconUri = it["iconUri"] + matrixCursor.addRow(arrayOf(data, mimeType, mimeType, title, subtitle, iconUri)) + } + } + } + matrixCursor + } + } + + private suspend fun getSuggestions(context: Context, query: String): List<FieldMap> { + if (flutterEngine == null) { + FlutterUtils.initFlutterEngine(context, SHARED_PREFERENCES_KEY, CALLBACK_HANDLE_KEY) { + flutterEngine = it + } + } + + val engine = flutterEngine + engine ?: throw Exception("Flutter engine is not initialized") + + val messenger = engine.dartExecutor + val backgroundChannel = MethodChannel(messenger, BACKGROUND_CHANNEL).apply { + setMethodCallHandler { call, result -> + when (call.method) { + "initialized" -> { + Log.d(LOG_TAG, "background channel is ready") + result.success(null) + } + else -> result.notImplemented() + } + } + } + + try { + return suspendCoroutine { cont -> + defaultScope.launch { + FlutterUtils.runOnUiThread { + backgroundChannel.invokeMethod("getSuggestions", hashMapOf( + "query" to query, + "locale" to Locale.getDefault().toString(), + "use24hour" to DateFormat.is24HourFormat(context), + ), object : MethodChannel.Result { + override fun success(result: Any?) { + @Suppress("unchecked_cast") + cont.resume(result as List<FieldMap>) + } + + override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) { + cont.resumeWithException(Exception("$errorCode: $errorMessage\n$errorDetails")) + } + + override fun notImplemented() { + cont.resumeWithException(Exception("not implemented")) + } + }) + } + } + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get suggestions", e) + return ArrayList() + } + } + + override fun onCreate(): Boolean = true + + override fun getType(uri: Uri): String? = null + + override fun insert(uri: Uri, values: ContentValues?): Uri = + throw UnsupportedOperationException("`insert` is not supported by this content provider") + + override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = + throw UnsupportedOperationException("`delete` is not supported by this content provider") + + override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = + throw UnsupportedOperationException("`update` is not supported by this content provider") + + companion object { + private val LOG_TAG = LogUtils.createTag<SearchSuggestionsProvider>() + private const val BACKGROUND_CHANNEL = "deckers.thibault/aves/global_search_background" + const val SHARED_PREFERENCES_KEY = "platform_search" + const val CALLBACK_HANDLE_KEY = "callback_handle" + + private var flutterEngine: FlutterEngine? = null + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/WallpaperActivity.kt b/android/app/src/main/kotlin/deckers/thibault/aves/WallpaperActivity.kt new file mode 100644 index 0000000..e06aea9 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/WallpaperActivity.kt @@ -0,0 +1,56 @@ +package deckers.thibault.aves + +import android.content.Intent +import android.net.Uri +import androidx.core.net.toUri +import deckers.thibault.aves.channel.calls.AppAdapterHandler +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.getParcelableExtraCompat +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +class WallpaperActivity : MainActivity() { + private var originalIntent: String? = null + + override fun extractIntentData(intent: Intent?): FieldMap { + if (intent != null) { + when (intent.action) { + Intent.ACTION_ATTACH_DATA, Intent.ACTION_SET_WALLPAPER -> { + (intent.data ?: intent.getParcelableExtraCompat<Uri>(Intent.EXTRA_STREAM))?.let { uri -> + // MIME type is optional + val type = intent.type ?: intent.resolveType(this) + return hashMapOf( + INTENT_DATA_KEY_ACTION to INTENT_ACTION_SET_WALLPAPER, + INTENT_DATA_KEY_MIME_TYPE to type, + INTENT_DATA_KEY_URI to uri.toString(), + ) + } + + // if the media URI is not provided we need to pick one first + originalIntent = intent.action + intent.action = Intent.ACTION_PICK + } + } + } + + return super.extractIntentData(intent) + } + + override fun submitPickedItems(call: MethodCall, result: MethodChannel.Result) { + if (originalIntent != null) { + val pickedUris = call.argument<List<String>>("uris") + if (!pickedUris.isNullOrEmpty()) { + val toUri = { uriString: String -> AppAdapterHandler.getShareableUri(this, uriString.toUri()) } + onNewIntent(Intent().apply { + action = originalIntent + data = toUri(pickedUris.first()) + }) + } else { + setResult(RESULT_CANCELED) + finish() + } + } else { + super.submitPickedItems(call, result) + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AccessibilityHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AccessibilityHandler.kt new file mode 100644 index 0000000..0e61c1f --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AccessibilityHandler.kt @@ -0,0 +1,107 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import android.content.ContextWrapper +import android.content.res.Configuration +import android.os.Build +import android.provider.Settings +import android.util.Log +import android.view.ViewConfiguration +import android.view.accessibility.AccessibilityManager +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.utils.LogUtils +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler + +class AccessibilityHandler(private val contextWrapper: ContextWrapper) : MethodCallHandler { + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "areAnimationsRemoved" -> safe(call, result, ::areAnimationsRemoved) + "getLongPressTimeout" -> safe(call, result, ::getLongPressTimeout) + "hasRecommendedTimeouts" -> safe(call, result, ::hasRecommendedTimeouts) + "getRecommendedTimeoutMillis" -> safe(call, result, ::getRecommendedTimeoutMillis) + "shouldUseBoldFont" -> safe(call, result, ::shouldUseBoldFont) + else -> result.notImplemented() + } + } + + private fun areAnimationsRemoved(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + var removed = false + try { + removed = Settings.Global.getFloat(contextWrapper.contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE) == 0f + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get settings with error=${e.message}", null) + } + result.success(removed) + } + + private fun getLongPressTimeout(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(ViewConfiguration.getLongPressTimeout()) + } + + private fun hasRecommendedTimeouts(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) + } + + private fun getRecommendedTimeoutMillis(call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + result.error("getRecommendedTimeoutMillis-sdk", "unsupported SDK version=${Build.VERSION.SDK_INT}", null) + return + } + + val originalTimeoutMillis = call.argument<Int>("originalTimeoutMillis") + val content = call.argument<List<String>>("content") + if (originalTimeoutMillis == null || content == null) { + result.error("getRecommendedTimeoutMillis-args", "missing arguments", null) + return + } + + var uiContentFlags = 0 + content.forEach { + uiContentFlags = when (it) { + "controls" -> uiContentFlags or AccessibilityManager.FLAG_CONTENT_CONTROLS + "icons" -> uiContentFlags or AccessibilityManager.FLAG_CONTENT_ICONS + "text" -> uiContentFlags or AccessibilityManager.FLAG_CONTENT_TEXT + else -> { + result.error("getRecommendedTimeoutMillis-flag", "unsupported UI content flag=$it", null) + return + } + } + } + + val am = contextWrapper.getSystemService(Context.ACCESSIBILITY_SERVICE) as? AccessibilityManager + if (am == null) { + result.error("getRecommendedTimeoutMillis-service", "failed to get accessibility manager", null) + return + } + + val millis = am.getRecommendedTimeoutMillis(originalTimeoutMillis, uiContentFlags) + result.success(millis) + } + + // Flutter v3.4 already checks the system `Configuration.fontWeightAdjustment` to update `MediaQuery` + // but we need to also check the non-standard Samsung field `bf` representing the bold font toggle + private fun shouldUseBoldFont(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + var shouldBold = false + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val config = contextWrapper.resources.configuration + val fontWeightAdjustment = config.fontWeightAdjustment + shouldBold = if (fontWeightAdjustment != Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED && fontWeightAdjustment != 0) { + fontWeightAdjustment >= BOLD_TEXT_WEIGHT_ADJUSTMENT + } else { + // fallback to Samsung non-standard field + Regex(" bf=([01]) ").find(config.toString())?.groups?.get(1)?.value == "1" + } + } + result.success(shouldBold) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<AccessibilityHandler>() + const val CHANNEL = "deckers.thibault/aves/accessibility" + + // match Flutter way: https://github.com/flutter/engine/blob/main/shell/platform/android/io/flutter/view/AccessibilityBridge.java#L125 + const val BOLD_TEXT_WEIGHT_ADJUSTMENT = 300 + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AnalysisHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AnalysisHandler.kt new file mode 100644 index 0000000..cc7b46e --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AnalysisHandler.kt @@ -0,0 +1,110 @@ +package deckers.thibault.aves.channel.calls + +import android.app.ActivityManager +import android.content.Context +import androidx.core.content.edit +import androidx.work.ExistingWorkPolicy +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkInfo +import androidx.work.WorkManager +import androidx.work.workDataOf +import deckers.thibault.aves.AnalysisWorker +import deckers.thibault.aves.utils.FlutterUtils +import io.flutter.embedding.android.FlutterFragmentActivity +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking + +class AnalysisHandler(private val activity: FlutterFragmentActivity, private val onAnalysisCompleted: () -> Unit) : MethodChannel.MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "registerCallback" -> ioScope.launch { Coresult.safe(call, result, ::registerCallback) } + "startAnalysis" -> Coresult.safe(call, result, ::startAnalysis) + else -> result.notImplemented() + } + } + + private fun registerCallback(call: MethodCall, result: MethodChannel.Result) { + val callbackHandle = call.argument<Number>("callbackHandle")?.toLong() + if (callbackHandle == null) { + result.error("registerCallback-args", "missing arguments", null) + return + } + + val preferences = activity.getSharedPreferences(AnalysisWorker.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE) + preferences.edit { + putLong(AnalysisWorker.PREF_CALLBACK_HANDLE_KEY, callbackHandle) + } + result.success(true) + } + + private fun startAnalysis(call: MethodCall, result: MethodChannel.Result) { + val force = call.argument<Boolean>("force") + if (force == null) { + result.error("startAnalysis-args", "missing arguments", null) + return + } + + val activityManager: ActivityManager = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + val runningAppProcesses = activityManager.runningAppProcesses + if (runningAppProcesses != null) { + val importance = runningAppProcesses[0].importance + if (importance < ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { + // the app is in the background + result.error("startAnalysis-background", "app is in the background (process importance=$importance)", null) + return + } + } + + // can be null or empty + val allEntryIds = call.argument<List<Int>>("entryIds") + + // work `Data` cannot occupy more than 10240 bytes when serialized + // so we save the possibly long list of entry IDs to shared preferences + val preferences = activity.getSharedPreferences(AnalysisWorker.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE) + preferences.edit { + putStringSet(AnalysisWorker.PREF_ENTRY_IDS_KEY, allEntryIds?.map { it.toString() }?.toSet()) + } + + val workData = workDataOf( + AnalysisWorker.KEY_FORCE to force, + ) + + WorkManager.getInstance(activity).beginUniqueWork( + ANALYSIS_WORK_NAME, + ExistingWorkPolicy.KEEP, + OneTimeWorkRequestBuilder<AnalysisWorker>().apply { setInputData(workData) }.build(), + ).enqueue() + + attachToActivity() + result.success(null) + } + + private var attached = false + + fun attachToActivity() { + if (!attached) { + attached = true + WorkManager.getInstance(activity).getWorkInfosForUniqueWorkLiveData(ANALYSIS_WORK_NAME).observe(activity) { list -> + if (list.any { it.state == WorkInfo.State.SUCCEEDED }) { + runBlocking { + FlutterUtils.runOnUiThread { + onAnalysisCompleted() + } + } + } + } + } + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/analysis" + private const val ANALYSIS_WORK_NAME = "analysis_work" + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppAdapterHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppAdapterHandler.kt new file mode 100644 index 0000000..f93d89e --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppAdapterHandler.kt @@ -0,0 +1,500 @@ +package deckers.thibault.aves.channel.calls + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.ContentResolver +import android.content.Context +import android.content.Intent +import android.content.pm.ApplicationInfo +import android.content.res.Configuration +import android.content.res.Resources +import android.graphics.BitmapFactory +import android.net.Uri +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.os.TransactionTooLargeException +import android.util.Log +import androidx.core.content.FileProvider +import androidx.core.content.pm.ShortcutInfoCompat +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.graphics.drawable.IconCompat +import androidx.core.graphics.scale +import androidx.core.net.toUri +import com.bumptech.glide.Glide +import com.bumptech.glide.load.DecodeFormat +import com.bumptech.glide.request.RequestOptions +import deckers.thibault.aves.MainActivity +import deckers.thibault.aves.MainActivity.Companion.COLLECTION_PAGE_ROUTE_NAME +import deckers.thibault.aves.MainActivity.Companion.ENTRY_VIEWER_PAGE_ROUTE_NAME +import deckers.thibault.aves.MainActivity.Companion.EXPLORER_PAGE_ROUTE_NAME +import deckers.thibault.aves.MainActivity.Companion.EXTRA_KEY_EXPLORER_PATH +import deckers.thibault.aves.MainActivity.Companion.EXTRA_KEY_FILTERS_ARRAY +import deckers.thibault.aves.MainActivity.Companion.EXTRA_KEY_FILTERS_STRING +import deckers.thibault.aves.MainActivity.Companion.EXTRA_KEY_PAGE +import deckers.thibault.aves.MainActivity.Companion.EXTRA_STRING_ARRAY_SEPARATOR +import deckers.thibault.aves.MainActivity.Companion.MAP_PAGE_ROUTE_NAME +import deckers.thibault.aves.R +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.ContextUtils.devicePixelRatio +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.anyCauseIs +import deckers.thibault.aves.utils.getApplicationInfoCompat +import deckers.thibault.aves.utils.queryIntentActivitiesCompat +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.util.Locale +import java.util.UUID +import kotlin.math.min +import kotlin.math.roundToInt + +class AppAdapterHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "getPackages" -> ioScope.launch { safe(call, result, ::getPackages) } + "getAppIcon" -> ioScope.launch { safeSuspend(call, result, ::getAppIcon) } + "copyToClipboard" -> ioScope.launch { safe(call, result, ::copyToClipboard) } + "open" -> safe(call, result, ::open) + "openMap" -> safe(call, result, ::openMap) + "setAs" -> safe(call, result, ::setAs) + "share" -> safe(call, result, ::share) + "pinShortcut" -> ioScope.launch { safe(call, result, ::pinShortcut) } + else -> result.notImplemented() + } + } + + private fun getPackages(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + val packages = HashMap<String, FieldMap>() + + fun addPackageDetails(intent: Intent) { + // apps tend to use their name in English when creating directories + // so we get their names in English as well as the current locale + val englishConfig = Configuration().apply { + setLocale(Locale.ENGLISH) + } + + val pm = context.packageManager + for (resolveInfo in pm.queryIntentActivitiesCompat(intent, 0)) { + val appInfo = resolveInfo.activityInfo.applicationInfo + val packageName = appInfo.packageName + if (!packages.containsKey(packageName)) { + val currentLabel = pm.getApplicationLabel(appInfo).toString() + val englishLabel: String? = appInfo.labelRes.takeIf { it != 0 }?.let { labelRes -> + var englishLabel: String? = null + try { + val resources = pm.getResourcesForApplication(appInfo) + // `updateConfiguration` is deprecated but it seems to be the only way + // to query resources from another app with a specific locale. + // The following methods do not work: + // - `resources.getConfiguration().setLocale(...)` + // - getting a package manager from a custom context with `context.createConfigurationContext(config)` + @Suppress("deprecation") + resources.updateConfiguration(englishConfig, resources.displayMetrics) + englishLabel = resources.getString(labelRes) + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get app label in English for packageName=$packageName", e) + } + englishLabel + } + packages[packageName] = hashMapOf( + "packageName" to packageName, + "categoryLauncher" to intent.hasCategory(Intent.CATEGORY_LAUNCHER), + "isSystem" to (appInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0), + "currentLabel" to currentLabel, + "englishLabel" to englishLabel, + ) + } + } + } + + // identify launcher category packages, which typically include user apps + // they should be fetched before the other packages, to be marked as launcher packages + try { + addPackageDetails(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)) + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to list launcher packages", e) + } + + try { + // complete with all the other packages + addPackageDetails(Intent(Intent.ACTION_MAIN)) + } catch (e: Exception) { + // `PackageManager.queryIntentActivities()` may kill the package manager if the response is too large + Log.w(LOG_TAG, "failed to list all packages", e) + + // fallback to the default category packages, which typically include system and OEM tools + try { + addPackageDetails(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_DEFAULT)) + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to list default packages", e) + } + } + + result.success(ArrayList(packages.values)) + } + + private suspend fun getAppIcon(call: MethodCall, result: MethodChannel.Result) { + val packageName = call.argument<String>("packageName") + val sizeDip = call.argument<Number>("sizeDip")?.toDouble() + if (packageName == null || sizeDip == null) { + result.error("getAppIcon-args", "missing arguments", null) + return + } + + // convert DIP to physical pixels here, instead of using `devicePixelRatio` in Flutter + val density = context.devicePixelRatio() + val size = (sizeDip * density).roundToInt() + var bytes: ByteArray? = null + try { + val iconResourceId = context.packageManager.getApplicationInfoCompat(packageName, 0).icon + if (iconResourceId != Resources.ID_NULL) { + val uri = Uri.Builder() + .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) + .authority(packageName) + .path(iconResourceId.toString()) + .build() + + val options = RequestOptions() + .format(DecodeFormat.PREFER_ARGB_8888) + .override(size, size) + val target = Glide.with(context) + .asBitmap() + .apply(options) + .load(uri) + .submit(size, size) + + try { + var bitmap = withContext(Dispatchers.IO) { target.get() } + if (bitmap.width > size && bitmap.height > size) { + // rescale when the resulting bitmap is larger than requested + val scalingFactor: Double = min(bitmap.width.toDouble() / size, bitmap.height.toDouble() / size) + val dstWidth = (bitmap.width / scalingFactor).roundToInt() + val dstHeight = (bitmap.height / scalingFactor).roundToInt() + Log.d( + LOG_TAG, "rescale app icon for packageName=$packageName" + + ", with bitmap byteCount=${bitmap.byteCount} size=${bitmap.width}x${bitmap.height}" + + ", to target=${size}x${size}" + ) + bitmap = bitmap.scale(dstWidth, dstHeight) + } + + // do not recycle bitmaps fetched from `ContentResolver` as their lifecycle is unknown + bytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = true, mimeType = null) + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to decode app icon for packageName=$packageName", e) + } + Glide.with(context).clear(target) + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get app info for packageName=$packageName", e) + return + } + if (bytes != null) { + result.success(bytes) + } else { + result.error("getAppIcon-null", "failed to get icon for packageName=$packageName", null) + } + } + + private fun copyToClipboard(call: MethodCall, result: MethodChannel.Result) { + val uri = call.argument<String>("uri")?.toUri() + val label = call.argument<String>("label") + if (uri == null) { + result.error("copyToClipboard-args", "missing arguments", null) + return + } + + // on older devices, `ClipboardManager` initialization must happen on the main thread + // (e.g. Samsung S7 with Android 8.0 / API 26, but not on Tab A 10.1 with Android 8.1 / API 27) + Handler(Looper.getMainLooper()).post { + try { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager + if (clipboard != null) { + val clip = ClipData.newUri(context.contentResolver, label, getShareableUri(context, uri)) + clipboard.setPrimaryClip(clip) + result.success(true) + } else { + result.success(false) + } + } catch (e: Exception) { + result.error("copyToClipboard-exception", "failed to set clip", e.message) + } + } + } + + private fun open(call: MethodCall, result: MethodChannel.Result) { + val title = call.argument<String>("title") + val uri = call.argument<String>("uri")?.toUri() + val mimeType = call.argument<String>("mimeType") + val forceChooser = call.argument<Boolean>("forceChooser") + if (uri == null || forceChooser == null) { + result.error("open-args", "missing arguments", null) + return + } + + val intent = Intent(Intent.ACTION_VIEW) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + .setDataAndType(getShareableUri(context, uri), mimeType) + val started = if (forceChooser) safeStartActivityChooser(title, intent) else safeStartActivity(intent) + + result.success(started) + } + + private fun openMap(call: MethodCall, result: MethodChannel.Result) { + val geoUri = call.argument<String>("geoUri")?.toUri() + if (geoUri == null) { + result.error("openMap-args", "missing arguments", null) + return + } + + val intent = Intent(Intent.ACTION_VIEW, geoUri) + val started = safeStartActivity(intent) + + result.success(started) + } + + private fun setAs(call: MethodCall, result: MethodChannel.Result) { + val title = call.argument<String>("title") + val uri = call.argument<String>("uri")?.toUri() + val mimeType = call.argument<String>("mimeType") + if (uri == null) { + result.error("setAs-args", "missing arguments", null) + return + } + + val intent = Intent(Intent.ACTION_ATTACH_DATA) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + .setDataAndType(getShareableUri(context, uri), mimeType) + val started = safeStartActivityChooser(title, intent) + + result.success(started) + } + + private fun share(call: MethodCall, result: MethodChannel.Result) { + val title = call.argument<String>("title") + val urisByMimeType = call.argument<Map<String, List<String>>>("urisByMimeType") + if (urisByMimeType == null) { + result.error("share-args", "missing arguments", null) + return + } + + val uriList = ArrayList(urisByMimeType.values.flatten().mapNotNull { getShareableUri(context, it.toUri()) }) + val mimeTypes = urisByMimeType.keys.toTypedArray() + + // simplify share intent for a single item, as some apps can handle one item but not more + val intent = if (uriList.size == 1) { + val uri = uriList.first() + val mimeType = mimeTypes.first() + + Intent(Intent.ACTION_SEND) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + .setType(mimeType) + .putExtra(Intent.EXTRA_STREAM, uri) + } else { + var mimeType = "*/*" + if (mimeTypes.size == 1) { + // items have the same MIME type & subtype + mimeType = mimeTypes.first() + } else { + // items have different subtypes + val mimeTypeTypes = mimeTypes.map { it.split("/") }.distinct() + if (mimeTypeTypes.size == 1) { + // items have the same MIME type + mimeType = "${mimeTypeTypes.first()}/*" + } + } + + Intent(Intent.ACTION_SEND_MULTIPLE) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + .putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList) + .setType(mimeType) + } + try { + val started = safeStartActivityChooser(title, intent) + result.success(started) + } catch (e: Exception) { + if (e.anyCauseIs<TransactionTooLargeException>()) { + result.error("share-large", "transaction too large with ${uriList.size} URIs", e) + } else { + result.error("share-exception", "failed to share ${uriList.size} URIs", e) + } + } + } + + private fun safeStartActivity(intent: Intent): Boolean { + if (intent.resolveActivity(context.packageManager) == null) return false + try { + context.startActivity(intent) + return true + } catch (e: SecurityException) { + if (intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0) { + // in some environments, providing the write flag yields a `SecurityException`: + // "UID XXXX does not have permission to content://XXXX" + // so we retry without it + Log.i(LOG_TAG, "retry intent=$intent without FLAG_GRANT_WRITE_URI_PERMISSION") + intent.flags = intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION.inv() + return safeStartActivity(intent) + } else { + Log.w(LOG_TAG, "failed to start activity for intent=$intent", e) + } + } + return false + } + + private fun safeStartActivityChooser(title: String?, intent: Intent): Boolean { + if (intent.resolveActivity(context.packageManager) == null) return false + try { + context.startActivity(Intent.createChooser(intent, title)) + return true + } catch (e: SecurityException) { + if (intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0) { + // in some environments, providing the write flag yields a `SecurityException`: + // "UID XXXX does not have permission to content://XXXX" + // so we retry without it + Log.i(LOG_TAG, "retry intent=$intent without FLAG_GRANT_WRITE_URI_PERMISSION") + intent.flags = intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION.inv() + return safeStartActivityChooser(title, intent) + } else { + Log.w(LOG_TAG, "failed to start activity chooser for intent=$intent", e) + } + } + return false + } + + // shortcuts + + private fun pinShortcut(call: MethodCall, result: MethodChannel.Result) { + // common arguments + val label = call.argument<String>("label") + val iconBytes = call.argument<ByteArray>("iconBytes") + val route = call.argument<String>("route") + // route dependent arguments + val filters = call.argument<List<String>>("filters") + val explorerPath = call.argument<String>("path") + val viewUri = call.argument<String>("viewUri")?.toUri() + val geoUri = call.argument<String>("geoUri")?.toUri() + + if (label == null || route == null) { + result.error("pin-args", "missing arguments", null) + return + } + + if (!ShortcutManagerCompat.isRequestPinShortcutSupported(context)) { + result.error("pin-unsupported", "failed because the launcher does not support pinning shortcuts", null) + return + } + + var icon: IconCompat? = null + if (iconBytes?.isNotEmpty() == true) { + var bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.size) + bitmap = BitmapUtils.centerSquareCrop(context, bitmap, 256) + if (bitmap != null) { + // adaptive, so the bitmap is used as background and covers the whole icon + icon = IconCompat.createWithAdaptiveBitmap(bitmap) + } + } + if (icon == null) { + // shortcut adaptive icons are placed in `mipmap`, not `drawable`, + // so that foreground is rendered at the intended scale + val supportAdaptiveIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O + + val resId = when (route) { + MAP_PAGE_ROUTE_NAME -> if (supportAdaptiveIcon) R.mipmap.ic_shortcut_map else R.drawable.ic_shortcut_map + else -> if (supportAdaptiveIcon) R.mipmap.ic_shortcut_collection else R.drawable.ic_shortcut_collection + } + icon = IconCompat.createWithResource(context, resId) + } + + val intent: Intent = when (route) { + COLLECTION_PAGE_ROUTE_NAME -> { + if (filters == null) { + result.error("pin-filters", "collection shortcut requires filters", null) + return + } + Intent(Intent.ACTION_MAIN, null, context, MainActivity::class.java) + .putExtra(EXTRA_KEY_PAGE, route) + .putExtra(EXTRA_KEY_FILTERS_ARRAY, filters.toTypedArray()) + // on API 25, `String[]` or `ArrayList` extras are null when using the shortcut + // so we use a joined `String` as fallback + .putExtra(EXTRA_KEY_FILTERS_STRING, filters.joinToString(EXTRA_STRING_ARRAY_SEPARATOR)) + } + + ENTRY_VIEWER_PAGE_ROUTE_NAME -> { + if (viewUri == null) { + result.error("pin-viewUri", "viewer shortcut requires URI", null) + return + } + Intent(Intent.ACTION_VIEW, viewUri, context, MainActivity::class.java) + } + + EXPLORER_PAGE_ROUTE_NAME -> { + Intent(Intent.ACTION_MAIN, null, context, MainActivity::class.java) + .putExtra(EXTRA_KEY_PAGE, route) + .putExtra(EXTRA_KEY_EXPLORER_PATH, explorerPath) + } + + MAP_PAGE_ROUTE_NAME -> { + if (geoUri == null) { + result.error("pin-geoUri", "map shortcut requires URI", null) + return + } + Intent(Intent.ACTION_VIEW, geoUri, context, MainActivity::class.java).apply { + putExtra(EXTRA_KEY_PAGE, route) + // filters are optional + filters?.let { + putExtra(EXTRA_KEY_FILTERS_ARRAY, it.toTypedArray()) + // on API 25, `String[]` or `ArrayList` extras are null when using the shortcut + // so we use a joined `String` as fallback + putExtra(EXTRA_KEY_FILTERS_STRING, it.joinToString(EXTRA_STRING_ARRAY_SEPARATOR)) + } + } + } + + else -> { + result.error("pin-route", "unsupported shortcut route=$route", null) + return + } + } + + // multiple shortcuts sharing the same ID cannot be created with different labels or icons + // so we provide a unique ID for each one, and let the user manage duplicates (i.e. same filter set), if any + val shortcut = ShortcutInfoCompat.Builder(context, UUID.randomUUID().toString()) + .setShortLabel(label) + .setIcon(icon) + .setIntent(intent) + .build() + ShortcutManagerCompat.requestPinShortcut(context, shortcut, null) + + result.success(true) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<AppAdapterHandler>() + const val CHANNEL = "deckers.thibault/aves/app" + + fun getShareableUri(context: Context, uri: Uri): Uri? { + return when (uri.scheme?.lowercase(Locale.ROOT)) { + ContentResolver.SCHEME_FILE -> { + uri.path?.let { path -> + val authority = "${context.applicationContext.packageName}.file_provider" + FileProvider.getUriForFile(context, authority, File(path)) + } + } + + else -> uri + } + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppProfileHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppProfileHandler.kt new file mode 100644 index 0000000..41682c0 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppProfileHandler.kt @@ -0,0 +1,97 @@ +package deckers.thibault.aves.channel.calls + +import android.app.Activity +import android.content.Context +import android.content.pm.CrossProfileApps +import android.os.Build +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler + +class AppProfileHandler(private val activity: Activity) : MethodCallHandler { + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "canInteractAcrossProfiles" -> safe(call, result, ::canInteractAcrossProfiles) + "canRequestInteractAcrossProfiles" -> safe(call, result, ::canRequestInteractAcrossProfiles) + "requestInteractAcrossProfiles" -> safe(call, result, ::requestInteractAcrossProfiles) + "switchProfile" -> safe(call, result, ::switchProfile) + "getProfileSwitchingLabel" -> safe(call, result, ::getProfileSwitchingLabel) + "getTargetUserProfiles" -> safe(call, result, ::getTargetUserProfiles) + else -> result.notImplemented() + } + } + + private fun canInteractAcrossProfiles(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + result.success(false) + return + } + + val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps + result.success(crossProfileApps.canInteractAcrossProfiles()) + } + + private fun canRequestInteractAcrossProfiles(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + result.success(false) + return + } + + val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps + result.success(crossProfileApps.canRequestInteractAcrossProfiles()) + } + + private fun requestInteractAcrossProfiles(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + result.success(false) + return + } + + val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps + val intent = crossProfileApps.createRequestInteractAcrossProfilesIntent() + val started = activity.startActivity(intent) + + result.success(started) + } + + private fun switchProfile(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + result.success(false) + return + } + + val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps + val userHandles = crossProfileApps.targetUserProfiles + crossProfileApps.startMainActivity(activity.componentName, userHandles.first()) + result.success(null) + } + + private fun getProfileSwitchingLabel(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + result.success(null) + return + } + + val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps + val userHandles = crossProfileApps.targetUserProfiles + val label = if (userHandles.isEmpty()) "" else crossProfileApps.getProfileSwitchingLabel(userHandles.first()) + + result.success(label) + } + + private fun getTargetUserProfiles(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + result.success(false) + return + } + + val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps + val userProfiles = crossProfileApps.targetUserProfiles.map { it.toString() }.toList() + result.success(userProfiles) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/app_profile" + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/Coresult.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/Coresult.kt new file mode 100644 index 0000000..c447a76 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/Coresult.kt @@ -0,0 +1,71 @@ +package deckers.thibault.aves.channel.calls + +import deckers.thibault.aves.MainActivity +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch + +// ensure `result` methods are called on the main looper thread +class Coresult internal constructor(private val call: MethodCall, private val methodResult: MethodChannel.Result) : MethodChannel.Result { + private val mainScope = CoroutineScope(Dispatchers.Main) + + override fun success(result: Any?) { + mainScope.launch { + try { + methodResult.success(result) + } catch (e: Exception) { + MainActivity.notifyError("failed to reply success for method=${call.method}, result=$result, exception=\n${e.stackTraceToString()}") + } + } + } + + override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) { + mainScope.launch { + try { + methodResult.error(errorCode, errorMessage, errorDetails) + } catch (e: Exception) { + MainActivity.notifyError("failed to reply error for method=${call.method}, errorCode=$errorCode, errorMessage=$errorMessage, errorDetails=$errorDetails, exception=\n${e.stackTraceToString()}") + } + } + } + + override fun notImplemented() { + mainScope.launch { + try { + methodResult.notImplemented() + } catch (e: Exception) { + MainActivity.notifyError("failed to reply notImplemented for method=${call.method}, exception=\n${e.stackTraceToString()}") + } + } + } + + companion object { + fun safe( + call: MethodCall, + result: MethodChannel.Result, + function: (call: MethodCall, result: MethodChannel.Result) -> Unit + ) { + val res = Coresult(call, result) + try { + function(call, res) + } catch (e: Exception) { + res.error("safe-exception", e.message, e.stackTraceToString()) + } + } + + suspend fun safeSuspend( + call: MethodCall, + result: MethodChannel.Result, + function: suspend (call: MethodCall, result: MethodChannel.Result) -> Unit + ) { + val res = Coresult(call, result) + try { + function(call, res) + } catch (e: Exception) { + res.error("safeSuspend-exception", e.message, e.stackTraceToString()) + } + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DebugHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DebugHandler.kt new file mode 100644 index 0000000..1af8699 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DebugHandler.kt @@ -0,0 +1,436 @@ +package deckers.thibault.aves.channel.calls + +import android.content.ContentUris +import android.content.Context +import android.database.Cursor +import android.graphics.BitmapFactory +import android.media.MediaCodecInfo +import android.media.MediaCodecList +import android.net.Uri +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.provider.MediaStore +import android.util.Log +import androidx.core.net.toUri +import com.drew.metadata.file.FileTypeDirectory +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.glide.TiffFetcher +import deckers.thibault.aves.metadata.ExifInterfaceHelper +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper +import deckers.thibault.aves.metadata.Metadata +import deckers.thibault.aves.metadata.Mp4ParserHelper +import deckers.thibault.aves.metadata.Mp4ParserHelper.dumpBoxes +import deckers.thibault.aves.metadata.PixyMetaHelper +import deckers.thibault.aves.metadata.metadataextractor.Helper +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.canReadWithExifInterface +import deckers.thibault.aves.utils.MimeTypes.canReadWithMetadataExtractor +import deckers.thibault.aves.utils.MimeTypes.canReadWithPixyMeta +import deckers.thibault.aves.utils.MimeTypes.isImage +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.UriUtils.tryParseId +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import io.flutter.util.PathUtils +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import org.beyka.tiffbitmapfactory.TiffBitmapFactory +import org.mp4parser.IsoFile +import java.io.FileInputStream +import java.io.IOException +import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface + +class DebugHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "crash" -> Handler(Looper.getMainLooper()).postDelayed({ throw TestException() }, 50) + "exception" -> throw TestException() + "safeException" -> safe(call, result) { _, _ -> throw TestException() } + "exceptionInCoroutine" -> ioScope.launch { throw TestException() } + "safeExceptionInCoroutine" -> ioScope.launch { safe(call, result) { _, _ -> throw TestException() } } + + "getContextDirs" -> ioScope.launch { safe(call, result, ::getContextDirs) } + "getCodecs" -> safe(call, result, ::getCodecs) + "getEnv" -> safe(call, result, ::getEnv) + + "getBitmapFactoryInfo" -> ioScope.launch { safe(call, result, ::getBitmapFactoryInfo) } + "getContentResolverMetadata" -> ioScope.launch { safe(call, result, ::getContentResolverMetadata) } + "getExifInterfaceMetadata" -> ioScope.launch { safe(call, result, ::getExifInterfaceMetadata) } + "getMediaMetadataRetrieverMetadata" -> ioScope.launch { safe(call, result, ::getMediaMetadataRetrieverMetadata) } + "getMetadataExtractorSummary" -> ioScope.launch { safe(call, result, ::getMetadataExtractorSummary) } + "getMp4ParserDump" -> ioScope.launch { safe(call, result, ::getMp4ParserDump) } + "getPixyMetadata" -> ioScope.launch { safe(call, result, ::getPixyMetadata) } + "getTiffStructure" -> ioScope.launch { safe(call, result, ::getTiffStructure) } + else -> result.notImplemented() + } + } + + private fun getContextDirs(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + val dirs = hashMapOf( + "cacheDir" to context.cacheDir, + "filesDir" to context.filesDir, + "obbDir" to context.obbDir, + "externalCacheDir" to context.externalCacheDir, + "externalFilesDir" to context.getExternalFilesDir(null), + "codeCacheDir" to context.codeCacheDir, + "noBackupFilesDir" to context.noBackupFilesDir, + ).apply { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + put("dataDir", context.dataDir) + } + }.mapValues { it.value?.path }.toMutableMap() + dirs["externalCacheDirs"] = context.externalCacheDirs.joinToString { it.path } + dirs["externalFilesDirs"] = context.getExternalFilesDirs(null).joinToString { it?.path ?: "null" } + + // used by flutter plugin `path_provider` + dirs.putAll( + hashMapOf( + "flutter / cacheDir" to PathUtils.getCacheDirectory(context), + "flutter / dataDir" to PathUtils.getDataDirectory(context), + "flutter / filesDir" to PathUtils.getFilesDir(context), + ) + ) + + result.success(dirs) + } + + private fun getCodecs(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + fun getFields(info: MediaCodecInfo): FieldMap { + val fields: FieldMap = hashMapOf( + "name" to info.name, + "isEncoder" to info.isEncoder, + "supportedTypes" to info.supportedTypes.joinToString(", "), + ) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + if (info.canonicalName != info.name) fields["canonicalName"] = info.canonicalName + if (info.isAlias) fields["isAlias"] to info.isAlias + if (info.isHardwareAccelerated) fields["isHardwareAccelerated"] to info.isHardwareAccelerated + if (info.isSoftwareOnly) fields["isSoftwareOnly"] to info.isSoftwareOnly + if (info.isVendor) fields["isVendor"] to info.isVendor + } + return fields + } + + val codecs = MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos.map(::getFields).toList() + result.success(codecs) + } + + private fun getEnv(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(System.getenv()) + } + + private fun getBitmapFactoryInfo(call: MethodCall, result: MethodChannel.Result) { + val uri = call.argument<String>("uri")?.toUri() + if (uri == null) { + result.error("getBitmapDecoderInfo-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, String>() + try { + StorageUtils.openInputStream(context, uri)?.use { input -> + val options = BitmapFactory.Options().apply { + inJustDecodeBounds = true + } + BitmapFactory.decodeStream(input, null, options) + options.outMimeType?.let { metadataMap["MimeType"] = it } + options.outWidth.takeIf { it >= 0 }?.let { metadataMap["Width"] = it.toString() } + options.outHeight.takeIf { it >= 0 }?.let { metadataMap["Height"] = it.toString() } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + options.outColorSpace?.let { metadataMap["ColorSpace"] = it.toString() } + options.outConfig?.let { metadataMap["Config"] = it.toString() } + } + } + } catch (_: IOException) { + // ignore + } + result.success(metadataMap) + } + + private fun getContentResolverMetadata(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + if (mimeType == null || uri == null) { + result.error("getContentResolverMetadata-args", "missing arguments", null) + return + } + + var contentUri: Uri = uri + if (StorageUtils.isMediaStoreContentUri(uri)) { + uri.tryParseId()?.let { id -> + contentUri = when { + isImage(mimeType) -> ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) + isVideo(mimeType) -> ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id) + else -> uri + } + contentUri = StorageUtils.getOriginalUri(context, contentUri) + } + } + + // prefer image/video content URI, fallback to original URI (possibly a file content URI) + val metadataMap = getContentResolverMetadataForUri(contentUri) ?: getContentResolverMetadataForUri(uri) + if (metadataMap != null) { + result.success(metadataMap) + } else { + result.error("getContentResolverMetadata-null", "failed to get cursor for contentUri=$contentUri", null) + } + } + + private fun getContentResolverMetadataForUri(contentUri: Uri): FieldMap? { + val cursor = context.contentResolver.query(contentUri, null, null, null, null) + if (cursor != null && cursor.moveToFirst()) { + val metadataMap = HashMap<String, Any?>() + val columnCount = cursor.columnCount + val columnNames = cursor.columnNames + for (i in 0 until columnCount) { + val key = columnNames[i] + try { + metadataMap[key] = when (cursor.getType(i)) { + Cursor.FIELD_TYPE_NULL -> null + Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(i) + Cursor.FIELD_TYPE_FLOAT -> cursor.getFloat(i) + Cursor.FIELD_TYPE_STRING -> cursor.getString(i) + Cursor.FIELD_TYPE_BLOB -> cursor.getBlob(i) + else -> null + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get value for key=$key", e) + } + } + cursor.close() + return metadataMap + } + return null + } + + private fun getExifInterfaceMetadata(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + if (mimeType == null || uri == null) { + result.error("getExifInterfaceMetadata-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, String?>() + if (canReadWithExifInterface(mimeType, strict = false)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val exif = ExifInterface(input) + for (tag in ExifInterfaceHelper.allTags.keys.filter { exif.hasAttribute(it) }) { + metadataMap[tag] = exif.getAttribute(tag) + } + } + } catch (e: Exception) { + // ExifInterface initialization can fail with a RuntimeException + // caused by an internal MediaMetadataRetriever failure + result.error("getExifInterfaceMetadata-failure", "failed to get exif for uri=$uri", e.message) + return + } + } + result.success(metadataMap) + } + + private fun getMediaMetadataRetrieverMetadata(call: MethodCall, result: MethodChannel.Result) { + val uri = call.argument<String>("uri")?.toUri() + if (uri == null) { + result.error("getMediaMetadataRetrieverMetadata-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, String>() + val retriever = StorageUtils.openMetadataRetriever(context, uri) + if (retriever != null) { + try { + for ((code, name) in MediaMetadataRetrieverHelper.allKeys) { + retriever.extractMetadata(code)?.let { metadataMap[name] = it } + } + } catch (_: Exception) { + // ignore + } finally { + // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs + retriever.release() + } + } + result.success(metadataMap) + } + + private fun getMetadataExtractorSummary(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + if (mimeType == null || uri == null) { + result.error("getMetadataExtractorSummary-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, String>() + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + metadataMap["mimeType"] = metadata.getDirectoriesOfType(FileTypeDirectory::class.java).joinToString { dir -> + if (dir.containsTag(FileTypeDirectory.TAG_DETECTED_FILE_MIME_TYPE)) { + dir.getString(FileTypeDirectory.TAG_DETECTED_FILE_MIME_TYPE) + } else "" + } + metadataMap["typeName"] = metadata.getDirectoriesOfType(FileTypeDirectory::class.java).joinToString { dir -> + if (dir.containsTag(FileTypeDirectory.TAG_DETECTED_FILE_TYPE_NAME)) { + dir.getString(FileTypeDirectory.TAG_DETECTED_FILE_TYPE_NAME) + } else "" + } + for (dir in metadata.directories) { + val dirName = dir.name ?: "" + var index = 0 + while (metadataMap.containsKey("$dirName ($index)")) index++ + var value = "${dir.tagCount} tags" + dir.parent?.let { value += ", parent: ${it.name}" } + metadataMap["$dirName ($index)"] = value + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get metadata by metadata-extractor for uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to get metadata by metadata-extractor for uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to get metadata by metadata-extractor for uri=$uri", e) + } + } + result.success(metadataMap) + } + + private fun getMp4ParserDump(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + if (mimeType == null || uri == null) { + result.error("getMp4ParserDump-args", "missing arguments", null) + return + } + + val sb = StringBuilder() + if (mimeType == MimeTypes.MP4 || MimeTypes.isIsoBMFFImage(mimeType)) { + try { + // we can skip uninteresting boxes with a seekable data source + val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri") + pfd.use { + FileInputStream(it.fileDescriptor).use { stream -> + stream.channel.use { channel -> + IsoFile(channel, Mp4ParserHelper.metadataBoxParser()).use { isoFile -> + isoFile.dumpBoxes(sb) + } + } + } + } + } catch (e: Exception) { + result.error("getMp4ParserDump-exception", e.message, e.stackTraceToString()) + return + } + } + result.success(sb.toString()) + } + + private fun getPixyMetadata(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + if (mimeType == null || uri == null) { + result.error("getPixyMetadata-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, String>() + if (canReadWithPixyMeta(mimeType)) { + try { + StorageUtils.openInputStream(context, uri)?.use { input -> + metadataMap.putAll(PixyMetaHelper.describe(input)) + } + } catch (e: Exception) { + result.error("getPixyMetadata-exception", e.message, e.stackTraceToString()) + return + } + } + result.success(metadataMap) + } + + private fun getTiffStructure(call: MethodCall, result: MethodChannel.Result) { + val uri = call.argument<String>("uri")?.toUri() + if (uri == null) { + result.error("getTiffStructure-args", "missing arguments", null) + return + } + + try { + val metadataMap = HashMap<String, FieldMap>() + var fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd() + if (fd == null) { + result.error("getTiffStructure-fd", "failed to get file descriptor", null) + return + } + var options = TiffFetcher.buildOptions().apply { + inJustDecodeBounds = true + } + TiffBitmapFactory.decodeFileDescriptor(fd, options) + metadataMap["0"] = tiffOptionsToMap(options) + val dirCount = options.outDirectoryCount + for (page in 1 until dirCount) { + fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd() + if (fd == null) { + result.error("getTiffStructure-fd", "failed to get file descriptor", null) + return + } + options = TiffFetcher.buildOptions().apply { + inJustDecodeBounds = true + inDirectoryNumber = page + } + TiffBitmapFactory.decodeFileDescriptor(fd, options) + metadataMap["$page"] = tiffOptionsToMap(options) + } + result.success(metadataMap) + } catch (e: Exception) { + result.error("getTiffStructure-read", "failed to read tiff", e.message) + } + } + + private fun tiffOptionsToMap(options: TiffBitmapFactory.Options): FieldMap = hashMapOf( + "Author" to options.outAuthor, + "BitsPerSample" to options.outBitsPerSample.toString(), + "CompressionScheme" to options.outCompressionScheme?.toString(), + "Copyright" to options.outCopyright, + "CurDirectoryNumber" to options.outCurDirectoryNumber.toString(), + "Datetime" to options.outDatetime, + "DirectoryCount" to options.outDirectoryCount.toString(), + "FillOrder" to options.outFillOrder?.toString(), + "Height" to options.outHeight.toString(), + "HostComputer" to options.outHostComputer, + "ImageDescription" to options.outImageDescription, + "ImageOrientation" to options.outImageOrientation?.toString(), + "NumberOfStrips" to options.outNumberOfStrips.toString(), + "Photometric" to options.outPhotometric?.toString(), + "PlanarConfig" to options.outPlanarConfig?.toString(), + "ResolutionUnit" to options.outResolutionUnit?.toString(), + "RowPerStrip" to options.outRowPerStrip.toString(), + "SamplePerPixel" to options.outSamplePerPixel.toString(), + "Software" to options.outSoftware, + "StripSize" to options.outStripSize.toString(), + "TileHeight" to options.outTileHeight.toString(), + "TileWidth" to options.outTileWidth.toString(), + "Width" to options.outWidth.toString(), + "XResolution" to options.outXResolution.toString(), + "YResolution" to options.outYResolution.toString(), + ) + + companion object { + private val LOG_TAG = LogUtils.createTag<DebugHandler>() + const val CHANNEL = "deckers.thibault/aves/debug" + } + + class TestException internal constructor() : RuntimeException("oops") +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DeviceHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DeviceHandler.kt new file mode 100644 index 0000000..f03a33d --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DeviceHandler.kt @@ -0,0 +1,174 @@ +package deckers.thibault.aves.channel.calls + +import android.annotation.SuppressLint +import android.app.LocaleConfig +import android.app.LocaleManager +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.res.Resources +import android.location.Geocoder +import android.os.Build +import android.os.LocaleList +import android.provider.MediaStore +import android.provider.Settings +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.net.toUri +import androidx.core.text.util.LocalePreferences +import com.google.android.material.color.DynamicColors +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.MemoryUtils +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import java.util.Locale + +class DeviceHandler(private val context: Context) : MethodCallHandler { + private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "canManageMedia" -> safe(call, result, ::canManageMedia) + "getCapabilities" -> defaultScope.launch { safe(call, result, ::getCapabilities) } + "getLocales" -> safe(call, result, ::getLocales) + "setLocaleConfig" -> safe(call, result, ::setLocaleConfig) + "getFirstDayOfWeek" -> safe(call, result, ::getFirstDayOfWeek) + "getPerformanceClass" -> safe(call, result, ::getPerformanceClass) + "getWidgetCornerRadiusPx" -> safe(call, result, ::getWidgetCornerRadiusPx) + "isLocked" -> safe(call, result, ::isLocked) + "isSystemFilePickerEnabled" -> safe(call, result, ::isSystemFilePickerEnabled) + "requestMediaManagePermission" -> safe(call, result, ::requestMediaManagePermission) + "getAvailableHeapSize" -> safe(call, result, ::getAvailableHeapSize) + "requestGarbageCollection" -> safe(call, result, ::requestGarbageCollection) + else -> result.notImplemented() + } + } + + private fun canManageMedia(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) MediaStore.canManageMedia(context) else false) + } + + private fun getCapabilities(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + val sdkInt = Build.VERSION.SDK_INT + result.success( + hashMapOf( + "canPinShortcut" to ShortcutManagerCompat.isRequestPinShortcutSupported(context), + "canRenderFlagEmojis" to (sdkInt >= Build.VERSION_CODES.M), + "canRenderSubdivisionFlagEmojis" to (sdkInt >= Build.VERSION_CODES.O), + "canRequestManageMedia" to (sdkInt >= Build.VERSION_CODES.S), + "canSetLockScreenWallpaper" to (sdkInt >= Build.VERSION_CODES.N), + "hasGeocoder" to Geocoder.isPresent(), + "isDynamicColorAvailable" to DynamicColors.isDynamicColorAvailable(), + "showPinShortcutFeedback" to (sdkInt >= Build.VERSION_CODES.O), + "supportEdgeToEdgeUIMode" to (sdkInt >= Build.VERSION_CODES.Q), + "supportPictureInPicture" to supportPictureInPicture(), + ) + ) + } + + private fun supportPictureInPicture(): Boolean { + // minimum version for `PictureInPictureParams.Builder#setAutoEnterEnabled` + val supportPipOnLeave = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S + return supportPipOnLeave && context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE) + } + + private fun getLocales(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + fun toMap(locale: Locale): FieldMap = hashMapOf( + "language" to locale.language, + "country" to locale.country, + "script" to locale.script, + ) + + val locales = ArrayList<FieldMap>() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + // when called from a window-less service, locales from `context.resources` + // do not reflect the current system settings, so we use `Resources.getSystem()` instead + val list = Resources.getSystem().configuration.locales + for (i in 0 until list.size()) { + locales.add(toMap(list.get(i))) + } + } else { + locales.add(toMap(Locale.getDefault())) + } + result.success(locales) + } + + private fun setLocaleConfig(call: MethodCall, result: MethodChannel.Result) { + val locales = call.argument<List<String>>("locales") + if (locales.isNullOrEmpty()) { + result.error("setLocaleConfig-args", "missing arguments", null) + return + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + @SuppressLint("WrongConstant") + val lm = context.getSystemService(Context.LOCALE_SERVICE) as? LocaleManager + lm?.overrideLocaleConfig = LocaleConfig(LocaleList.forLanguageTags(locales.joinToString(","))) + } + + result.success(true) + } + + private fun getFirstDayOfWeek(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(LocalePreferences.getFirstDayOfWeek()) + } + + private fun getPerformanceClass(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val performanceClass = Build.VERSION.MEDIA_PERFORMANCE_CLASS + if (performanceClass > 0) { + result.success(performanceClass) + return + } + } + result.success(Build.VERSION.SDK_INT) + } + + private fun getWidgetCornerRadiusPx(@Suppress("unused_parameter") methodCall: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + result.success(context.resources.getDimension(android.R.dimen.system_app_widget_background_radius)) + } else { + result.success(null) + } + } + + private fun isLocked(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager + val isLocked = keyguardManager.isKeyguardLocked + result.success(isLocked) + } + + private fun isSystemFilePickerEnabled(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + val enabled = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).resolveActivity(context.packageManager) != null + result.success(enabled) + } + + private fun requestMediaManagePermission(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { + result.error("requestMediaManagePermission-unsupported", "media management permission is not available before Android 12", null) + return + } + + val intent = Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA, "package:${context.packageName}".toUri()) + context.startActivity(intent) + result.success(true) + } + + private fun getAvailableHeapSize(@Suppress("unused_parameter") methodCall: MethodCall, result: MethodChannel.Result) { + result.success(MemoryUtils.getAvailableHeapSize()) + } + + private fun requestGarbageCollection(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + Runtime.getRuntime().gc() + result.success(true) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/device" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/EmbeddedDataHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/EmbeddedDataHandler.kt new file mode 100644 index 0000000..30d4001 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/EmbeddedDataHandler.kt @@ -0,0 +1,361 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import android.util.Log +import androidx.core.content.FileProvider +import androidx.core.net.toUri +import androidx.exifinterface.media.ExifInterface +import com.adobe.internal.xmp.XMPException +import com.adobe.internal.xmp.XMPUtils +import com.bumptech.glide.load.resource.bitmap.TransformationUtils +import com.drew.metadata.xmp.XmpDirectory +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend +import deckers.thibault.aves.metadata.Metadata +import deckers.thibault.aves.metadata.MultiPage +import deckers.thibault.aves.metadata.metadataextractor.Helper +import deckers.thibault.aves.metadata.xmp.GoogleDeviceContainer +import deckers.thibault.aves.metadata.xmp.GoogleXMP +import deckers.thibault.aves.metadata.xmp.XMP.getSafeStructField +import deckers.thibault.aves.metadata.xmp.XMPPropName +import deckers.thibault.aves.model.EntryFields +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.provider.ImageProvider +import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.FileUtils.transferFrom +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.canReadWithExifInterface +import deckers.thibault.aves.utils.MimeTypes.canReadWithMetadataExtractor +import deckers.thibault.aves.utils.MimeTypes.extensionFor +import deckers.thibault.aves.utils.MimeTypes.isImage +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.StorageUtils +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import java.io.InputStream + +class EmbeddedDataHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "getExifThumbnails" -> ioScope.launch { safeSuspend(call, result, ::getExifThumbnails) } + "extractGoogleDeviceItem" -> ioScope.launch { safe(call, result, ::extractGoogleDeviceItem) } + "extractJpegMpfItem" -> ioScope.launch { safe(call, result, ::extractJpegMpfItem) } + "extractMotionPhotoImage" -> ioScope.launch { safe(call, result, ::extractMotionPhotoImage) } + "extractMotionPhotoVideo" -> ioScope.launch { safe(call, result, ::extractMotionPhotoVideo) } + "extractVideoEmbeddedPicture" -> ioScope.launch { safe(call, result, ::extractVideoEmbeddedPicture) } + "extractXmpDataProp" -> ioScope.launch { safe(call, result, ::extractXmpDataProp) } + else -> result.notImplemented() + } + } + + private suspend fun getExifThumbnails(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + if (mimeType == null || uri == null) { + result.error("getExifThumbnails-args", "missing arguments", null) + return + } + + val thumbnails = ArrayList<ByteArray>() + if (canReadWithExifInterface(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val exif = ExifInterface(input) + val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) + exif.thumbnailBitmap?.let { bitmap -> + TransformationUtils.rotateImageExif(BitmapUtils.getBitmapPool(context), bitmap, orientation)?.let { + // do not recycle bitmaps fetched from `ExifInterface` as their lifecycle is unknown + BitmapUtils.getBytes(it, recycle = false, decoded = true, mimeType = null)?.let { bytes -> thumbnails.add(bytes) } + } + } + } + } catch (_: Exception) { + // ExifInterface initialization can fail with a RuntimeException + // caused by an internal MediaMetadataRetriever failure + } + } + result.success(thumbnails) + } + + private fun extractGoogleDeviceItem(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val displayName = call.argument<String>("displayName") + val dataUri = call.argument<String>("dataUri") + if (mimeType == null || uri == null || sizeBytes == null || dataUri == null) { + result.error("extractGoogleDeviceItem-args", "missing arguments", null) + return + } + + var container: GoogleDeviceContainer? = null + + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + // data can be large and stored in "Extended XMP", + // which is returned as a second XMP directory + val xmpDirs = metadata.getDirectoriesOfType(XmpDirectory::class.java) + try { + container = xmpDirs.firstNotNullOfOrNull { GoogleXMP.getDeviceContainer(it.xmpMeta) } + } catch (e: XMPException) { + result.error("extractGoogleDeviceItem-xmp", "failed to read XMP directory for uri=$uri dataUri=$dataUri", e.message) + return + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to extract file from XMP", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to extract file from XMP", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to extract file from XMP", e) + } + } + + container?.let { + it.findOffsets(context, uri, mimeType, sizeBytes) + + val index = it.itemIndex(dataUri) + val itemStartOffset = it.itemStartOffset(index) + val itemLength = it.itemLength(index) + val itemMimeType = it.itemMimeType(index) + if (itemStartOffset != null && itemLength != null && itemMimeType != null) { + StorageUtils.openInputStream(context, uri)?.let { input -> + input.skip(itemStartOffset) + copyEmbeddedBytes(result, itemMimeType, displayName, input, itemLength) + return + } + } + } + + result.error("extractGoogleDeviceItem-empty", "failed to extract item from Google Device XMP at uri=$uri dataUri=$dataUri", null) + } + + private fun extractJpegMpfItem(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val displayName = call.argument<String>("displayName") + val id = call.argument<Int>("id") + if (mimeType == null || uri == null || sizeBytes == null || id == null) { + result.error("extractJpegMpfItem-args", "missing arguments", null) + return + } + + val pageIndex = id - 1 + val mpEntries = MultiPage.getJpegMpfEntries(context, uri, sizeBytes) + if (mpEntries != null && pageIndex < mpEntries.size) { + val mpEntry = mpEntries[pageIndex] + mpEntry.mimeType?.let { embedMimeType -> + var dataOffset = mpEntry.dataOffset + if (dataOffset > 0) { + val baseOffset = MultiPage.getJpegMpfBaseOffset(context, uri, sizeBytes) + if (baseOffset != null) { + dataOffset += baseOffset + } + } + StorageUtils.openInputStream(context, uri)?.let { input -> + input.skip(dataOffset) + copyEmbeddedBytes(result, embedMimeType, displayName, input, mpEntry.size) + } + return + } + } + + result.error("extractJpegMpfItem-empty", "failed to extract file index=$id from MPF at uri=$uri", null) + } + + private fun extractMotionPhotoImage(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val displayName = call.argument<String>("displayName") + if (mimeType == null || uri == null || sizeBytes == null) { + result.error("extractMotionPhotoImage-args", "missing arguments", null) + return + } + + MultiPage.getTrailerVideoSize(context, uri, mimeType, sizeBytes)?.let { videoSizeBytes -> + val imageSizeBytes = sizeBytes - videoSizeBytes + StorageUtils.openInputStream(context, uri)?.let { input -> + copyEmbeddedBytes(result, mimeType, displayName, input, imageSizeBytes) + } + return + } + + result.error("extractMotionPhotoImage-empty", "failed to extract image from motion photo at uri=$uri", null) + } + + private fun extractMotionPhotoVideo(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val displayName = call.argument<String>("displayName") + if (mimeType == null || uri == null || sizeBytes == null) { + result.error("extractMotionPhotoVideo-args", "missing arguments", null) + return + } + + MultiPage.getMotionPhotoVideoSizing(context, uri, mimeType, sizeBytes)?.let { (videoOffset, videoSize) -> + StorageUtils.openInputStream(context, uri)?.let { input -> + input.skip(videoOffset) + copyEmbeddedBytes(result, MimeTypes.MP4, displayName, input, videoSize) + } + return + } + + result.error("extractMotionPhotoVideo-empty", "failed to extract video from motion photo at uri=$uri", null) + } + + private fun extractVideoEmbeddedPicture(call: MethodCall, result: MethodChannel.Result) { + val uri = call.argument<String>("uri")?.toUri() + val displayName = call.argument<String>("displayName") + if (uri == null) { + result.error("extractVideoEmbeddedPicture-args", "missing arguments", null) + return + } + + val retriever = StorageUtils.openMetadataRetriever(context, uri) + if (retriever != null) { + try { + retriever.embeddedPicture?.let { bytes -> + var embedMimeType: String? = null + bytes.inputStream().use { input -> + Helper.readMimeType(input)?.let { embedMimeType = it } + } + embedMimeType?.let { mime -> + copyEmbeddedBytes(result, mime, displayName, bytes.inputStream(), bytes.size.toLong()) + return + } + } + } catch (e: Exception) { + result.error("extractVideoEmbeddedPicture-fetch", "failed to fetch picture for uri=$uri", e.message) + } finally { + // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs + retriever.release() + } + } + result.error("extractVideoEmbeddedPicture-empty", "failed to extract picture for uri=$uri", null) + } + + private fun extractXmpDataProp(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val displayName = call.argument<String>("displayName") + val dataProp = call.argument<List<Any>>("propPath") + val embedMimeType = call.argument<String>("propMimeType") + if (mimeType == null || uri == null || dataProp == null || embedMimeType == null) { + result.error("extractXmpDataProp-args", "missing arguments", null) + return + } + + val props = dataProp.mapNotNull { + when (it) { + is List<*> -> XMPPropName(it.first() as String, it.last() as String) + is Int -> it + else -> null + } + } + + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + // data can be large and stored in "Extended XMP", + // which is returned as a second XMP directory + val xmpDirs = metadata.getDirectoriesOfType(XmpDirectory::class.java) + try { + val embedBytes: ByteArray = if (props.size == 1) { + val prop = props.first() as XMPPropName + xmpDirs.firstNotNullOf { it.xmpMeta.getPropertyBase64(prop.nsUri, prop.toString()) } + } else { + xmpDirs.firstNotNullOf { it.xmpMeta.getSafeStructField(props) }.let { + XMPUtils.decodeBase64(it.value) + } + } + + copyEmbeddedBytes(result, embedMimeType, displayName, embedBytes.inputStream(), embedBytes.size.toLong()) + return + } catch (e: XMPException) { + result.error("extractXmpDataProp-xmp", "failed to read XMP directory for uri=$uri prop=$dataProp", e.message) + return + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to extract file from XMP", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to extract file from XMP", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to extract file from XMP", e) + } + } + result.error("extractXmpDataProp-empty", "failed to extract file from XMP uri=$uri prop=$dataProp", null) + } + + private fun copyEmbeddedBytes( + result: MethodChannel.Result, + mimeType: String, + displayName: String?, + embeddedByteStream: InputStream, + embeddedByteLength: Long, + ) { + val extension = extensionFor(mimeType, defaultExtension = null) + val targetFile = StorageUtils.createTempFile(context, extension).apply { + transferFrom(embeddedByteStream, embeddedByteLength) + } + + val authority = "${context.applicationContext.packageName}.file_provider" + val uri = if (displayName != null) { + // add extension to ease type identification when sharing this content + val displayNameWithExtension = if (displayName.endsWith(extension, ignoreCase = true)) { + displayName + } else { + "$displayName$extension" + } + FileProvider.getUriForFile(context, authority, targetFile, displayNameWithExtension) + } else { + FileProvider.getUriForFile(context, authority, targetFile) + } + val resultFields: FieldMap = hashMapOf( + EntryFields.URI to uri.toString(), + EntryFields.MIME_TYPE to mimeType, + ) + if (isImage(mimeType) || isVideo(mimeType)) { + val provider = getProvider(context, uri) + if (provider == null) { + result.error("copyEmbeddedBytes-provider", "failed to find provider for uri=$uri", null) + return + } + + ioScope.launch { + provider.fetchSingle(context, uri, mimeType, false, object : ImageProvider.ImageOpCallback { + override fun onSuccess(fields: FieldMap) { + resultFields.putAll(fields) + result.success(resultFields) + } + + override fun onFailure(throwable: Throwable) = result.error("copyEmbeddedBytes-failure", "failed to get entry for uri=$uri mime=$mimeType", throwable.message) + }) + } + } else { + result.success(resultFields) + } + } + + companion object { + private val LOG_TAG = LogUtils.createTag<EmbeddedDataHandler>() + const val CHANNEL = "deckers.thibault/aves/embedded" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GeocodingHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GeocodingHandler.kt new file mode 100644 index 0000000..d8379b5 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GeocodingHandler.kt @@ -0,0 +1,83 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import android.location.Address +import android.location.Geocoder +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.utils.getFromLocationCompat +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import java.util.Locale + +// as of 2021/03/10, geocoding packages exist but: +// - `geocoder` is unmaintained +// - `geocoding` method does not return `addressLine` (v2.0.0) +class GeocodingHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private var geocoder: Geocoder? = null + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "getAddress" -> ioScope.launch { safe(call, result, ::getAddress) } + else -> result.notImplemented() + } + } + + private fun getAddress(call: MethodCall, result: MethodChannel.Result) { + val latitude = call.argument<Number>("latitude")?.toDouble() + val longitude = call.argument<Number>("longitude")?.toDouble() + val localeLanguageTag = call.argument<String>("localeLanguageTag") + val maxResults = call.argument<Int>("maxResults") ?: 1 + if (latitude == null || longitude == null) { + result.error("getAddress-args", "missing arguments", null) + return + } + + if (!Geocoder.isPresent()) { + result.error("getAddress-unavailable", "Geocoder is unavailable", null) + return + } + + geocoder = geocoder ?: if (localeLanguageTag != null) { + Geocoder(context, Locale.forLanguageTag(localeLanguageTag)) + } else { + Geocoder(context) + } + + fun processAddresses(addresses: List<Address>) { + if (addresses.isEmpty()) { + result.error("getAddress-empty", "failed to find any address for latitude=$latitude, longitude=$longitude", null) + } else { + val addressMapList: ArrayList<Map<String, String?>> = ArrayList(addresses.map { address -> + hashMapOf( + "addressLine" to (0..address.maxAddressLineIndex).joinToString(", ") { i -> address.getAddressLine(i) }, + "adminArea" to address.adminArea, + "countryCode" to address.countryCode, + "countryName" to address.countryName, + "featureName" to address.featureName, + "locality" to address.locality, + "postalCode" to address.postalCode, + "subAdminArea" to address.subAdminArea, + "subLocality" to address.subLocality, + "subThoroughfare" to address.subThoroughfare, + "thoroughfare" to address.thoroughfare, + ) + }) + result.success(addressMapList) + } + } + + geocoder!!.getFromLocationCompat( + latitude, longitude, maxResults, ::processAddresses, + ) { code, message, details -> result.error(code, message, details) } + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/geocoding" + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GlobalSearchHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GlobalSearchHandler.kt new file mode 100644 index 0000000..b3704db --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GlobalSearchHandler.kt @@ -0,0 +1,42 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import androidx.core.content.edit +import deckers.thibault.aves.SearchSuggestionsProvider +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +class GlobalSearchHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "registerCallback" -> ioScope.launch { safe(call, result, ::registerCallback) } + else -> result.notImplemented() + } + } + + private fun registerCallback(call: MethodCall, result: MethodChannel.Result) { + val callbackHandle = call.argument<Number>("callbackHandle")?.toLong() + if (callbackHandle == null) { + result.error("registerCallback-args", "missing arguments", null) + return + } + + val preferences = context.getSharedPreferences(SearchSuggestionsProvider.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE) + preferences.edit { + putLong(SearchSuggestionsProvider.CALLBACK_HANDLE_KEY, callbackHandle) + } + result.success(true) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/global_search" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/HomeWidgetHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/HomeWidgetHandler.kt new file mode 100644 index 0000000..eb6e8e8 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/HomeWidgetHandler.kt @@ -0,0 +1,32 @@ +package deckers.thibault.aves.channel.calls + +import android.appwidget.AppWidgetManager +import android.content.Context +import deckers.thibault.aves.HomeWidgetProvider +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +class HomeWidgetHandler(private val context: Context) : MethodChannel.MethodCallHandler { + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "update" -> Coresult.safe(call, result, ::update) + else -> result.notImplemented() + } + } + + private fun update(call: MethodCall, result: MethodChannel.Result) { + val widgetId = call.argument<Int>("widgetId") + if (widgetId == null) { + result.error("update-args", "missing arguments", null) + return + } + + val appWidgetManager = AppWidgetManager.getInstance(context) + HomeWidgetProvider().onUpdate(context, appWidgetManager, intArrayOf(widgetId)) + result.success(null) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/widget_update" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaEditHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaEditHandler.kt new file mode 100644 index 0000000..4f48d73 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaEditHandler.kt @@ -0,0 +1,77 @@ +package deckers.thibault.aves.channel.calls + +import android.content.ContextWrapper +import android.util.Log +import androidx.core.net.toUri +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.NameConflictStrategy +import deckers.thibault.aves.model.provider.ImageProvider.ImageOpCallback +import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.StorageUtils.ensureTrailingSeparator +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +class MediaEditHandler(private val contextWrapper: ContextWrapper) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "cancelFileOp" -> safe(call, result, ::cancelFileOp) + "captureFrame" -> ioScope.launch { safeSuspend(call, result, ::captureFrame) } + else -> result.notImplemented() + } + } + + private fun cancelFileOp(call: MethodCall, result: MethodChannel.Result) { + val opId = call.argument<String>("opId") + if (opId == null) { + result.error("cancelFileOp-args", "missing arguments", null) + return + } + + Log.i(LOG_TAG, "cancelling file op $opId") + cancelledOps.add(opId) + + result.success(null) + } + + private suspend fun captureFrame(call: MethodCall, result: MethodChannel.Result) { + val uri = call.argument<String>("uri")?.toUri() + val desiredName = call.argument<String>("desiredName") + val exifFields = call.argument<FieldMap>("exif") ?: HashMap() + val bytes = call.argument<ByteArray>("bytes") + var destinationDir = call.argument<String>("destinationPath") + val nameConflictStrategy = NameConflictStrategy.get(call.argument<String>("nameConflictStrategy")) + if (uri == null || desiredName == null || bytes == null || destinationDir == null || nameConflictStrategy == null) { + result.error("captureFrame-args", "missing arguments", null) + return + } + + val provider = getProvider(contextWrapper, uri) + if (provider == null) { + result.error("captureFrame-provider", "failed to find provider for uri=$uri", null) + return + } + + destinationDir = ensureTrailingSeparator(destinationDir) + provider.captureFrame(contextWrapper, desiredName, exifFields, bytes, destinationDir, nameConflictStrategy, object : ImageOpCallback { + override fun onSuccess(fields: FieldMap) = result.success(fields) + override fun onFailure(throwable: Throwable) = result.error("captureFrame-failure", "failed to capture frame for uri=$uri", throwable.message) + }) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<MediaEditHandler>() + const val CHANNEL = "deckers.thibault/aves/media_edit" + + val cancelledOps = HashSet<String>() + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaFetchObjectHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaFetchObjectHandler.kt new file mode 100644 index 0000000..ead151e --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaFetchObjectHandler.kt @@ -0,0 +1,68 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import android.os.Handler +import android.os.Looper +import androidx.core.net.toUri +import com.bumptech.glide.Glide +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.provider.ImageProvider.ImageOpCallback +import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +class MediaFetchObjectHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "getEntry" -> ioScope.launch { safe(call, result, ::getEntry) } + "clearImageDiskCache" -> ioScope.launch { safe(call, result, ::clearImageDiskCache) } + "clearImageMemoryCache" -> ioScope.launch { safe(call, result, ::clearImageMemoryCache) } + else -> result.notImplemented() + } + } + + private fun getEntry(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") // MIME type is optional + val uri = call.argument<String>("uri")?.toUri() + val allowUnsized = call.argument<Boolean>("allowUnsized") ?: false + if (uri == null) { + result.error("getEntry-args", "missing arguments", null) + return + } + + val provider = getProvider(context, uri) + if (provider == null) { + result.error("getEntry-provider", "failed to find provider for uri=$uri mimeType=$mimeType", null) + return + } + + provider.fetchSingle(context, uri, mimeType, allowUnsized, object : ImageOpCallback { + override fun onSuccess(fields: FieldMap) = result.success(fields) + override fun onFailure(throwable: Throwable) = result.error("getEntry-failure", "failed to get entry for uri=$uri mimeType=$mimeType", throwable.message) + }) + } + + private fun clearImageDiskCache(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + Glide.get(context).clearDiskCache() + result.success(null) + } + + private fun clearImageMemoryCache(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + Handler(Looper.getMainLooper()).post { + Glide.get(context).clearMemory() + } + result.success(null) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/media_fetch_object" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaSessionHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaSessionHandler.kt new file mode 100644 index 0000000..6a4023e --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaSessionHandler.kt @@ -0,0 +1,169 @@ +package deckers.thibault.aves.channel.calls + +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.media.AudioManager +import android.media.session.PlaybackState +import android.support.v4.media.MediaMetadataCompat +import android.support.v4.media.session.MediaSessionCompat +import android.support.v4.media.session.PlaybackStateCompat +import androidx.core.net.toUri +import androidx.media.session.MediaButtonReceiver +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend +import deckers.thibault.aves.channel.streams.platformtodart.MediaCommandStreamHandler +import deckers.thibault.aves.utils.FlutterUtils +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +class MediaSessionHandler(private val context: Context, private val mediaCommandHandler: MediaCommandStreamHandler) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + private var session: MediaSessionCompat? = null + private var wasPlaying = false + private var isNoisyAudioReceiverRegistered = false + private val noisyAudioReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) { + mediaCommandHandler.callback.onStop() + } + } + } + + fun dispose() { + unregisterNoisyAudioReceiver() + } + + private fun registerNoisyAudioReceiver() { + context.registerReceiver(noisyAudioReceiver, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) + isNoisyAudioReceiverRegistered = true + } + + private fun unregisterNoisyAudioReceiver() { + if (isNoisyAudioReceiverRegistered) { + context.unregisterReceiver(noisyAudioReceiver) + isNoisyAudioReceiverRegistered = false + } + } + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "update" -> ioScope.launch { safeSuspend(call, result, ::updateSession) } + "release" -> ioScope.launch { safe(call, result, ::releaseSession) } + else -> result.notImplemented() + } + } + + private suspend fun updateSession(call: MethodCall, result: MethodChannel.Result) { + val uri = call.argument<String>("uri")?.toUri() + val title = call.argument<String>("title") ?: uri?.toString() + val durationMillis = call.argument<Number>("durationMillis")?.toLong() + val stateString = call.argument<String>("state") + val positionMillis = call.argument<Number>("positionMillis")?.toLong() + val playbackSpeed = call.argument<Number>("playbackSpeed")?.toFloat() + val canSkipToNext = call.argument<Boolean>("canSkipToNext") + val canSkipToPrevious = call.argument<Boolean>("canSkipToPrevious") + + if (uri == null || title == null || durationMillis == null || stateString == null || positionMillis == null || playbackSpeed == null || canSkipToNext == null || canSkipToPrevious == null) { + result.error( + "updateSession-args", "missing arguments: uri=$uri, title=$title, durationMillis=$durationMillis" + + ", stateString=$stateString, positionMillis=$positionMillis, playbackSpeed=$playbackSpeed, canSkipToNext=$canSkipToNext, canSkipToPrevious=$canSkipToPrevious", null + ) + return + } + + val state = when (stateString) { + STATE_STOPPED -> PlaybackStateCompat.STATE_STOPPED + STATE_PAUSED -> PlaybackStateCompat.STATE_PAUSED + STATE_PLAYING -> PlaybackStateCompat.STATE_PLAYING + else -> { + result.error("updateSession-state", "unknown state=$stateString", null) + return + } + } + + var actions = PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SEEK_TO + actions = if (state == PlaybackState.STATE_PLAYING) { + actions or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_STOP + } else { + actions or PlaybackStateCompat.ACTION_PLAY + } + if (canSkipToNext) { + actions = actions or PlaybackStateCompat.ACTION_SKIP_TO_NEXT + } + if (canSkipToPrevious) { + actions = actions or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS + } + + val playbackState = PlaybackStateCompat.Builder() + .setState( + state, + positionMillis, + playbackSpeed, + System.currentTimeMillis() + ) + .setActions(actions) + .build() + + FlutterUtils.runOnUiThread { + try { + if (session == null) { + val mbrIntent = MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_PLAY_PAUSE) + val mbrName = ComponentName(context, MediaButtonReceiver::class.java) + session = MediaSessionCompat(context, "aves", mbrName, mbrIntent).apply { + setCallback(mediaCommandHandler.callback) + } + } + session!!.apply { + val metadata = MediaMetadataCompat.Builder() + .putString(MediaMetadataCompat.METADATA_KEY_TITLE, title) + .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, title) + .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, durationMillis) + .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, uri.toString()) + .build() + setMetadata(metadata) + setPlaybackState(playbackState) + if (!isActive) { + isActive = true + } + } + + val isPlaying = state == PlaybackStateCompat.STATE_PLAYING + if (!wasPlaying && isPlaying) { + registerNoisyAudioReceiver() + } else if (wasPlaying && !isPlaying) { + unregisterNoisyAudioReceiver() + } + wasPlaying = isPlaying + + result.success(null) + } catch (e: Exception) { + result.error("updateSession-exception", e.message, e.stackTraceToString()) + } + } + } + + private fun releaseSession(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + session?.let { + it.release() + session = null + } + result.success(null) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/media_session" + + const val STATE_STOPPED = "stopped" + const val STATE_PAUSED = "paused" + const val STATE_PLAYING = "playing" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaStoreHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaStoreHandler.kt new file mode 100644 index 0000000..64b440b --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaStoreHandler.kt @@ -0,0 +1,85 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import android.media.MediaScannerConnection +import android.net.Uri +import android.os.Build +import android.provider.MediaStore +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.model.provider.MediaStoreImageProvider +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +class MediaStoreHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "checkObsoleteContentIds" -> ioScope.launch { safe(call, result, ::checkObsoleteContentIds) } + "checkObsoletePaths" -> ioScope.launch { safe(call, result, ::checkObsoletePaths) } + "getChangedUris" -> ioScope.launch { safe(call, result, ::getChangedUris) } + "getGeneration" -> ioScope.launch { safe(call, result, ::getGeneration) } + "scanFile" -> ioScope.launch { safe(call, result, ::scanFile) } + else -> result.notImplemented() + } + } + + private fun checkObsoleteContentIds(call: MethodCall, result: MethodChannel.Result) { + val knownContentIds = call.argument<List<Number?>>("knownContentIds")?.map { it?.toLong() } + if (knownContentIds == null) { + result.error("checkObsoleteContentIds-args", "missing arguments", null) + return + } + result.success(MediaStoreImageProvider().checkObsoleteContentIds(context, knownContentIds)) + } + + private fun checkObsoletePaths(call: MethodCall, result: MethodChannel.Result) { + val knownPathById = call.argument<Map<Number?, String?>>("knownPathById")?.mapKeys { it.key?.toLong() } + if (knownPathById == null) { + result.error("checkObsoletePaths-args", "missing arguments", null) + return + } + result.success(MediaStoreImageProvider().checkObsoletePaths(context, knownPathById)) + } + + private fun getChangedUris(call: MethodCall, result: MethodChannel.Result) { + val sinceGeneration = call.argument<Int>("sinceGeneration") + if (sinceGeneration == null) { + result.error("getChangedUris-args", "missing arguments", null) + return + } + val uris = MediaStoreImageProvider().getChangedUris(context, sinceGeneration) + result.success(uris) + } + + private fun getGeneration(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + val generation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + try { + MediaStore.getGeneration(context, MediaStore.VOLUME_EXTERNAL_PRIMARY) + } catch (e: Exception) { + // may yield `IllegalArgumentException: Volume external_primary not found` + val volumes = MediaStore.getExternalVolumeNames(context).joinToString(", ") + result.error("getGeneration-primary", e.message + " (available volumes are [$volumes])", e) + return + } + } else { + null + } + result.success(generation) + } + + private fun scanFile(call: MethodCall, result: MethodChannel.Result) { + val path = call.argument<String>("path") + val mimeType = call.argument<String>("mimeType") + MediaScannerConnection.scanFile(context, arrayOf(path), arrayOf(mimeType)) { _, uri: Uri? -> result.success(uri?.toString()) } + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/media_store" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataEditHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataEditHandler.kt new file mode 100644 index 0000000..470fc20 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataEditHandler.kt @@ -0,0 +1,206 @@ +package deckers.thibault.aves.channel.calls + +import android.content.ContextWrapper +import androidx.core.net.toUri +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.metadata.Mp4TooLargeException +import deckers.thibault.aves.model.ExifOrientationOp +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.provider.ImageProvider.ImageOpCallback +import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import java.io.FileNotFoundException + +class MetadataEditHandler(private val contextWrapper: ContextWrapper) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "rotate" -> ioScope.launch { safe(call, result, ::rotate) } + "flip" -> ioScope.launch { safe(call, result, ::flip) } + "editDate" -> ioScope.launch { safe(call, result, ::editDate) } + "editMetadata" -> ioScope.launch { safe(call, result, ::editMetadata) } + "removeTrailerVideo" -> ioScope.launch { safe(call, result, ::removeTrailerVideo) } + "removeTypes" -> ioScope.launch { safe(call, result, ::removeTypes) } + else -> result.notImplemented() + } + } + + private fun rotate(call: MethodCall, result: MethodChannel.Result) { + val clockwise = call.argument<Boolean>("clockwise") + if (clockwise == null) { + result.error("rotate-args", "missing arguments", null) + return + } + + val op = if (clockwise) ExifOrientationOp.ROTATE_CW else ExifOrientationOp.ROTATE_CCW + editOrientation(call, result, op) + } + + private fun flip(call: MethodCall, result: MethodChannel.Result) { + editOrientation(call, result, ExifOrientationOp.FLIP) + } + + private fun editOrientation(call: MethodCall, result: MethodChannel.Result, op: ExifOrientationOp) { + val entryMap = call.argument<FieldMap>("entry") + if (entryMap == null) { + result.error("editOrientation-args", "missing arguments", null) + return + } + + val uri = (entryMap["uri"] as String?)?.toUri() + val path = entryMap["path"] as String? + val mimeType = entryMap["mimeType"] as String? + if (uri == null || path == null || mimeType == null) { + result.error("editOrientation-args", "failed because entry fields are missing", null) + return + } + + val provider = getProvider(contextWrapper, uri) + if (provider == null) { + result.error("editOrientation-provider", "failed to find provider for uri=$uri", null) + return + } + + val callback = MetadataOpCallback("editOrientation", entryMap, result) + provider.editOrientation(contextWrapper, path, uri, mimeType, op, callback) + } + + private fun editDate(call: MethodCall, result: MethodChannel.Result) { + val dateMillis = call.argument<Number>("dateMillis")?.toLong() + val shiftSeconds = call.argument<Number>("shiftSeconds")?.toLong() + val fields = call.argument<List<String>>("fields") + val entryMap = call.argument<FieldMap>("entry") + if (entryMap == null || fields == null) { + result.error("editDate-args", "missing arguments", null) + return + } + + val uri = (entryMap["uri"] as String?)?.toUri() + val path = entryMap["path"] as String? + val mimeType = entryMap["mimeType"] as String? + if (uri == null || path == null || mimeType == null) { + result.error("editDate-args", "failed because entry fields are missing", null) + return + } + + val provider = getProvider(contextWrapper, uri) + if (provider == null) { + result.error("editDate-provider", "failed to find provider for uri=$uri", null) + return + } + + val callback = MetadataOpCallback("editDate", entryMap, result) + provider.editDate(contextWrapper, path, uri, mimeType, dateMillis, shiftSeconds, fields, callback) + } + + private fun editMetadata(call: MethodCall, result: MethodChannel.Result) { + val metadata = call.argument<FieldMap>("metadata") + val entryMap = call.argument<FieldMap>("entry") + val autoCorrectTrailerOffset = call.argument<Boolean>("autoCorrectTrailerOffset") + if (entryMap == null || metadata == null || autoCorrectTrailerOffset == null) { + result.error("editMetadata-args", "missing arguments", null) + return + } + + val uri = (entryMap["uri"] as String?)?.toUri() + val path = entryMap["path"] as String? + val mimeType = entryMap["mimeType"] as String? + if (uri == null || path == null || mimeType == null) { + result.error("editMetadata-args", "failed because entry fields are missing", null) + return + } + + val provider = getProvider(contextWrapper, uri) + if (provider == null) { + result.error("editMetadata-provider", "failed to find provider for uri=$uri", null) + return + } + + val callback = MetadataOpCallback("editMetadata", entryMap, result) + provider.editMetadata(contextWrapper, path, uri, mimeType, metadata, autoCorrectTrailerOffset, callback) + } + + private fun removeTrailerVideo(call: MethodCall, result: MethodChannel.Result) { + val entryMap = call.argument<FieldMap>("entry") + if (entryMap == null) { + result.error("removeTrailerVideo-args", "missing arguments", null) + return + } + + val uri = (entryMap["uri"] as String?)?.toUri() + val path = entryMap["path"] as String? + val mimeType = entryMap["mimeType"] as String? + if (uri == null || path == null || mimeType == null) { + result.error("removeTrailerVideo-args", "failed because entry fields are missing", null) + return + } + + val provider = getProvider(contextWrapper, uri) + if (provider == null) { + result.error("removeTrailerVideo-provider", "failed to find provider for uri=$uri", null) + return + } + + val callback = MetadataOpCallback("removeTrailerVideo", entryMap, result) + provider.removeTrailerVideo(contextWrapper, path, uri, mimeType, callback) + } + + private fun removeTypes(call: MethodCall, result: MethodChannel.Result) { + val types = call.argument<List<String>>("types") + val entryMap = call.argument<FieldMap>("entry") + if (entryMap == null || types == null) { + result.error("removeTypes-args", "missing arguments", null) + return + } + + val uri = (entryMap["uri"] as String?)?.toUri() + val path = entryMap["path"] as String? + val mimeType = entryMap["mimeType"] as String? + if (uri == null || path == null || mimeType == null) { + result.error("removeTypes-args", "failed because entry fields are missing", null) + return + } + + val provider = getProvider(contextWrapper, uri) + if (provider == null) { + result.error("removeTypes-provider", "failed to find provider for uri=$uri", null) + return + } + + val callback = MetadataOpCallback("removeTypes", entryMap, result) + provider.removeMetadataTypes(contextWrapper, path, uri, mimeType, types.toSet(), callback) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/metadata_edit" + } +} + +private class MetadataOpCallback( + private val errorCodeBase: String, + private val entryMap: FieldMap, + private val result: MethodChannel.Result, +) : ImageOpCallback { + override fun onSuccess(fields: FieldMap) = result.success(fields) + override fun onFailure(throwable: Throwable) { + val errorCode = if (throwable is Mp4TooLargeException) { + if (throwable.type == "moov") { + "$errorCodeBase-mp4largemoov" + } else { + "$errorCodeBase-mp4largeother" + } + } else if (throwable is FileNotFoundException) { + "$errorCodeBase-filenotfound" + } else { + "$errorCodeBase-failure" + } + result.error(errorCode, "failed for entry=$entryMap", throwable) + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataFetchHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataFetchHandler.kt new file mode 100644 index 0000000..e049c3d --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataFetchHandler.kt @@ -0,0 +1,1521 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import android.media.MediaFormat +import android.media.MediaMetadataRetriever +import android.net.Uri +import android.os.Build +import android.util.Log +import androidx.core.net.toUri +import com.adobe.internal.xmp.XMPException +import com.adobe.internal.xmp.XMPMeta +import com.adobe.internal.xmp.XMPMetaFactory +import com.adobe.internal.xmp.options.SerializeOptions +import com.adobe.internal.xmp.properties.XMPPropertyInfo +import com.drew.lang.KeyValuePair +import com.drew.lang.Rational +import com.drew.metadata.Tag +import com.drew.metadata.avi.AviDirectory +import com.drew.metadata.exif.ExifDirectoryBase +import com.drew.metadata.exif.ExifIFD0Directory +import com.drew.metadata.exif.ExifSubIFDDirectory +import com.drew.metadata.exif.GpsDirectory +import com.drew.metadata.file.FileTypeDirectory +import com.drew.metadata.gif.GifAnimationDirectory +import com.drew.metadata.iptc.IptcDirectory +import com.drew.metadata.mov.metadata.QuickTimeMetadataDirectory +import com.drew.metadata.mp4.media.Mp4UuidBoxDirectory +import com.drew.metadata.png.PngDirectory +import com.drew.metadata.webp.WebpDirectory +import com.drew.metadata.xmp.XmpDirectory +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.metadata.ExifGeoTiffTags +import deckers.thibault.aves.metadata.ExifInterfaceHelper +import deckers.thibault.aves.metadata.ExifInterfaceHelper.describeAll +import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeDateMillis +import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeDouble +import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeInt +import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeRational +import deckers.thibault.aves.metadata.ExifTags +import deckers.thibault.aves.metadata.GSpherical +import deckers.thibault.aves.metadata.GeoTiffKeys +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeDateMillis +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeDescription +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeInt +import deckers.thibault.aves.metadata.Metadata +import deckers.thibault.aves.metadata.Metadata.DIR_DNG +import deckers.thibault.aves.metadata.Metadata.DIR_EXIF_GEOTIFF +import deckers.thibault.aves.metadata.Metadata.DIR_PNG_TEXTUAL_DATA +import deckers.thibault.aves.metadata.Metadata.getRotationDegreesForExifCode +import deckers.thibault.aves.metadata.Metadata.isFlippedForExifCode +import deckers.thibault.aves.metadata.Mp4ParserHelper +import deckers.thibault.aves.metadata.MultiPage +import deckers.thibault.aves.metadata.PixyMetaHelper +import deckers.thibault.aves.metadata.QuickTimeMetadata +import deckers.thibault.aves.metadata.metadataextractor.Helper +import deckers.thibault.aves.metadata.metadataextractor.Helper.PNG_ITXT_DIR_NAME +import deckers.thibault.aves.metadata.metadataextractor.Helper.PNG_LAST_MODIFICATION_TIME_FORMAT +import deckers.thibault.aves.metadata.metadataextractor.Helper.PNG_TIME_DIR_NAME +import deckers.thibault.aves.metadata.metadataextractor.Helper.containsGeoTiffTags +import deckers.thibault.aves.metadata.metadataextractor.Helper.extractGeoKeys +import deckers.thibault.aves.metadata.metadataextractor.Helper.extractPngProfile +import deckers.thibault.aves.metadata.metadataextractor.Helper.getDateDigitizedMillis +import deckers.thibault.aves.metadata.metadataextractor.Helper.getDateModifiedMillis +import deckers.thibault.aves.metadata.metadataextractor.Helper.getDateOriginalMillis +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeBoolean +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeDateMillis +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeInt +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeRational +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeString +import deckers.thibault.aves.metadata.metadataextractor.Helper.isPngTextDir +import deckers.thibault.aves.metadata.metadataextractor.PngActlDirectory +import deckers.thibault.aves.metadata.metadataextractor.SafeXmpReader +import deckers.thibault.aves.metadata.metadataextractor.mpf.MpEntry +import deckers.thibault.aves.metadata.metadataextractor.mpf.MpEntryDirectory +import deckers.thibault.aves.metadata.xmp.GoogleXMP +import deckers.thibault.aves.metadata.xmp.XMP +import deckers.thibault.aves.metadata.xmp.XMP.doesPropExist +import deckers.thibault.aves.metadata.xmp.XMP.getPropArrayItemValues +import deckers.thibault.aves.metadata.xmp.XMP.getSafeDateMillis +import deckers.thibault.aves.metadata.xmp.XMP.getSafeInt +import deckers.thibault.aves.metadata.xmp.XMP.getSafeLocalizedText +import deckers.thibault.aves.metadata.xmp.XMP.hasHdrGainMap +import deckers.thibault.aves.metadata.xmp.XMP.isMotionPhoto +import deckers.thibault.aves.metadata.xmp.XMP.isPanorama +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.ContextUtils.queryContentPropValue +import deckers.thibault.aves.utils.HashUtils +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.TIFF_EXTENSION_PATTERN +import deckers.thibault.aves.utils.MimeTypes.canReadWithExifInterface +import deckers.thibault.aves.utils.MimeTypes.canReadWithMetadataExtractor +import deckers.thibault.aves.utils.MimeTypes.isIsoBMFFImage +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.StorageUtils +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import org.json.JSONObject +import org.mp4parser.boxes.threegpp.ts26244.LocationInformationBox +import org.mp4parser.tools.Path +import java.nio.charset.StandardCharsets +import java.text.DecimalFormat +import java.text.ParseException +import java.util.Locale +import kotlin.math.roundToInt +import kotlin.math.roundToLong +import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface + +class MetadataFetchHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "getAllMetadata" -> ioScope.launch { safe(call, result, ::getAllMetadata) } + "getCatalogMetadata" -> ioScope.launch { safe(call, result, ::getCatalogMetadata) } + "getOverlayMetadata" -> ioScope.launch { safe(call, result, ::getOverlayMetadata) } + "getGeoTiffInfo" -> ioScope.launch { safe(call, result, ::getGeoTiffInfo) } + "getMultiPageInfo" -> ioScope.launch { safe(call, result, ::getMultiPageInfo) } + "getPanoramaInfo" -> ioScope.launch { safe(call, result, ::getPanoramaInfo) } + "getIptc" -> ioScope.launch { safe(call, result, ::getIptc) } + "getXmp" -> ioScope.launch { safe(call, result, ::getXmp) } + "hasContentResolverProp" -> ioScope.launch { safe(call, result, ::hasContentProp) } + "getContentResolverProp" -> ioScope.launch { safe(call, result, ::getContentPropValue) } + "getDate" -> ioScope.launch { safe(call, result, ::getDate) } + "getFields" -> ioScope.launch { safe(call, result, ::getFields) } + else -> result.notImplemented() + } + } + + private fun getAllMetadata(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + if (mimeType == null || uri == null) { + result.error("getAllMetadata-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, MutableMap<String, String>>() + var foundExif = false + var foundXmp = false + var foundMp4Uuid = false + + fun processXmp(xmpMeta: XMPMeta, dirMap: MutableMap<String, String>, allowMultiple: Boolean = false) { + if (foundXmp && !allowMultiple) return + foundXmp = true + try { + for (prop in xmpMeta) { + if (prop is XMPPropertyInfo) { + val path = prop.path + if (path?.isNotEmpty() == true) { + val value = if (XMP.isDataPath(path)) VALUE_SKIPPED_DATA else prop.value + if (value?.isNotEmpty() == true) { + dirMap[path] = value + } + } + } + } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to read XMP directory for uri=$uri", e) + } + // remove this stat as it is not actual XMP data + dirMap.remove(XmpDirectory().getTagName(XmpDirectory.TAG_XMP_VALUE_COUNT)) + if (dirMap.isNotEmpty()) { + // add schema prefixes for namespace resolution + val prefixes = XMPMetaFactory.getSchemaRegistry().prefixes + dirMap["schemaRegistryPrefixes"] = JSONObject(prefixes).toString() + } + } + + val mp4UuidDirCount = HashMap<String, Int>() + fun processMp4Uuid(dir: Mp4UuidBoxDirectory) { + var thisDirName: String + when (val uuid = dir.getString(Mp4UuidBoxDirectory.TAG_UUID)) { + GSpherical.SPHERICAL_VIDEO_V1_UUID -> { + val bytes = dir.getByteArray(Mp4UuidBoxDirectory.TAG_USER_DATA) + thisDirName = "Spherical Video" + metadataMap[thisDirName] = HashMap(GSpherical(bytes).describe()) + } + + QuickTimeMetadata.PROF_UUID -> { + // redundant with info derived on the Dart side + } + + QuickTimeMetadata.USMT_UUID -> { + val bytes = dir.getByteArray(Mp4UuidBoxDirectory.TAG_USER_DATA) + val blocks = QuickTimeMetadata.parseUuidUsmt(bytes) + if (blocks.isNotEmpty()) { + thisDirName = "QuickTime User Media" + val usmt = metadataMap[thisDirName] ?: HashMap() + metadataMap[thisDirName] = usmt + + blocks.forEach { + var key = it.type + var value = it.value + val language = it.language + + var i = 0 + while (usmt.containsKey(key)) { + key = it.type + " (${++i})" + } + if (language != "und") { + value += " ($language)" + } + usmt[key] = value + } + } + } + + else -> { + val uuidPart = uuid.substringBefore('-') + thisDirName = "${dir.name} $uuidPart" + + val count = mp4UuidDirCount[uuidPart] ?: 0 + mp4UuidDirCount[uuidPart] = count + 1 + if (count > 0) { + thisDirName += " ($count)" + } + + val dirMap = metadataMap[thisDirName] ?: HashMap() + metadataMap[thisDirName] = dirMap + + dirMap.putAll(dir.tags.map { Pair(it.tagName, it.description) }) + } + } + } + + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + foundExif = metadata.directories.any { it is ExifDirectoryBase && it.tagCount > 0 } + foundMp4Uuid = metadata.directories.any { it is Mp4UuidBoxDirectory && it.tagCount > 0 } + + val dirByName = metadata.directories.filter { + (it.tagCount > 0 || it.errorCount > 0 || it is MpEntryDirectory) + && it !is FileTypeDirectory + && it !is AviDirectory + }.groupBy { dir -> dir.name } + + for (dirEntry in dirByName) { + val baseDirName = dirEntry.key + + // exclude directories known to be redundant with info derived on the Dart side + // they are excluded by name instead of runtime type because excluding `Mp4Directory` + // would also exclude derived directories, such as `Mp4UuidBoxDirectory` + if (allMetadataRedundantDirNames.contains(baseDirName)) continue + + val sameNameDirs = dirEntry.value + val sameNameDirCount = sameNameDirs.size + for (dirIndex in 0 until sameNameDirCount) { + val dir = sameNameDirs[dirIndex] + + // directory name + var thisDirName = baseDirName + if (sameNameDirCount > 1 && !allMetadataMergeableDirNames.contains(baseDirName)) { + // optional count for multiple directories of the same type + thisDirName = "$thisDirName[${dirIndex + 1}]" + } + // optional parent to distinguish child directories of the same type + dir.parent?.name?.let { thisDirName = "$it/$thisDirName" } + + var dirMap = metadataMap[thisDirName] ?: HashMap() + if (dir !is Mp4UuidBoxDirectory) { + metadataMap[thisDirName] = dirMap + + // tags + val tags = dir.tags + when { + dir is ExifDirectoryBase -> { + when { + dir.containsGeoTiffTags() -> { + // split GeoTIFF tags in their own directory + val geoTiffDirMap = metadataMap[DIR_EXIF_GEOTIFF] ?: HashMap() + metadataMap[DIR_EXIF_GEOTIFF] = geoTiffDirMap + val byGeoTiff = tags.groupBy { ExifTags.isGeoTiffTag(it.tagType) } + byGeoTiff[true]?.flatMap { tag -> + when (tag.tagType) { + ExifGeoTiffTags.TAG_GEO_KEY_DIRECTORY -> { + val geoTiffTags = (dir as ExifIFD0Directory).extractGeoKeys(dir.getIntArray(tag.tagType)) + geoTiffTags.map { geoTag -> + val name = GeoTiffKeys.getTagName(geoTag.key) ?: "0x${geoTag.key.toString(16)}" + val value = geoTag.value + val description = if (value is DoubleArray) value.joinToString(" ") { doubleFormat.format(it) } else "$value" + Pair(name, description) + } + } + // skip `Geo double/ascii params`, as their content is split and presented through various GeoTIFF keys + ExifGeoTiffTags.TAG_GEO_DOUBLE_PARAMS, + ExifGeoTiffTags.TAG_GEO_ASCII_PARAMS -> ArrayList() + + else -> listOf(exifTagMapper(tag)) + } + }?.let { geoTiffDirMap.putAll(it) } + byGeoTiff[false]?.map { exifTagMapper(it) }?.let { dirMap.putAll(it) } + } + + mimeType == MimeTypes.DNG || mimeType == MimeTypes.DNG_ADOBE -> { + // split DNG tags in their own directory + val dngDirMap = metadataMap[DIR_DNG] ?: HashMap() + metadataMap[DIR_DNG] = dngDirMap + val byDng = tags.groupBy { ExifTags.isDngTag(it.tagType) } + byDng[true]?.map { exifTagMapper(it) }?.let { dngDirMap.putAll(it) } + byDng[false]?.map { exifTagMapper(it) }?.let { dirMap.putAll(it) } + } + + else -> dirMap.putAll(tags.map { exifTagMapper(it) }) + } + } + + dir.isPngTextDir() -> { + metadataMap.remove(thisDirName) + dirMap = metadataMap[DIR_PNG_TEXTUAL_DATA] ?: HashMap() + metadataMap[DIR_PNG_TEXTUAL_DATA] = dirMap + + for (tag in tags) { + val tagType = tag.tagType + if (tagType == PngDirectory.TAG_TEXTUAL_DATA) { + val pairs = dir.getObject(tagType) as List<*> + val textPairs = pairs.map { pair -> + val kv = pair as KeyValuePair + val key = kv.key + // `PNG-iTXt` uses UTF-8, contrary to `PNG-tEXt` and `PNG-zTXt` using Latin-1 / ISO-8859-1 + val charset = if (baseDirName == PNG_ITXT_DIR_NAME) { + StandardCharsets.UTF_8 + } else { + kv.value.charset + } + val valueString = String(kv.value.bytes, charset) + val dirs = extractPngProfile(key, valueString) + if (dirs?.any() == true) { + dirs.forEach { profileDir -> + val profileDirName = "${dir.name}/${profileDir.name}" + val profileDirMap = metadataMap[profileDirName] ?: HashMap() + metadataMap[profileDirName] = profileDirMap + val profileTags = profileDir.tags + if (profileDir is ExifDirectoryBase) { + profileDirMap.putAll(profileTags.map { exifTagMapper(it) }) + } else { + profileDirMap.putAll(profileTags.map { Pair(it.tagName, it.description) }) + } + } + null + } else { + Pair(key, valueString) + } + } + dirMap.putAll(textPairs.filterNotNull()) + } else { + dirMap[tag.tagName] = tag.description + } + } + } + + dir is MpEntryDirectory -> { + dirMap.putAll(dir.describe()) + } + + else -> dirMap.putAll(tags.map { Pair(it.tagName, it.description) }) + } + } + + if (!isLargeMp4(mimeType, sizeBytes)) { + if (dir is Mp4UuidBoxDirectory) { + processMp4Uuid(dir) + } + + if (dir is XmpDirectory) { + processXmp(dir.xmpMeta, dirMap, allowMultiple = true) + } + } + + // include errors, if any + dir.errors.forEachIndexed { i, error -> + dirMap["Error[$i]"] = error + } + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + + if (!foundExif && canReadWithExifInterface(mimeType)) { + // fallback to read EXIF via ExifInterface + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val exif = ExifInterface(input) + val allTags = describeAll(exif).toMutableMap() + if (foundXmp) { + // do not overwrite XMP parsed by metadata-extractor + // with raw XMP found by ExifInterface + allTags.remove(Metadata.DIR_XMP) + } else { + val xmpTags = allTags[Metadata.DIR_XMP] + if (xmpTags != null) { + val xmpRaw = xmpTags[ExifInterface.TAG_XMP] + if (xmpRaw != null) { + val metadata = com.drew.metadata.Metadata() + val xmpBytes = xmpRaw.toByteArray(Charsets.UTF_8) + SafeXmpReader().extract(xmpBytes, 0, xmpBytes.size, metadata, null) + metadata.getFirstDirectoryOfType(XmpDirectory::class.java)?.let { xmpDir -> + val dirMap = HashMap<String, String>() + processXmp(xmpDir.xmpMeta, dirMap, allowMultiple = true) + allTags[Metadata.DIR_XMP] = dirMap + } + } + } + } + metadataMap.putAll(allTags.mapValues { it.value.toMutableMap() }) + } + } catch (e: Exception) { + // ExifInterface initialization can fail with a RuntimeException + // caused by an internal MediaMetadataRetriever failure + Log.w(LOG_TAG, "failed to get metadata by ExifInterface for uri=$uri", e) + } + } + + fun fallbackProcessXmp(xmpMeta: XMPMeta) { + val thisDirName = XmpDirectory().name + val dirMap = metadataMap[thisDirName] ?: HashMap() + processXmp(xmpMeta, dirMap) + if (dirMap.isNotEmpty()) { + metadataMap[thisDirName] = dirMap + } + } + + XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::fallbackProcessXmp) + // `metadata-extractor` may fail to get UUID boxes for some MP4 files, + // so we always check with `mp4parser`, even for smaller files + XMP.checkMp4(context, mimeType, uri) { dirs -> + for (dir in dirs.filterIsInstance<XmpDirectory>()) { + fallbackProcessXmp(dir.xmpMeta) + } + if (!foundMp4Uuid) { + for (dir in dirs.filterIsInstance<Mp4UuidBoxDirectory>()) { + processMp4Uuid(dir) + } + } + } + + if (isVideo(mimeType)) { + // `metadata-extractor` do not extract custom tags in user data box + Mp4ParserHelper.getUserDataBox(context, mimeType, uri)?.let { box -> + metadataMap[Metadata.DIR_MP4_USER_DATA] = Mp4ParserHelper.extractBoxFields(box) + } + + // this is used as fallback when the video metadata cannot be found on the Dart side + // and to identify whether there is an accessible cover image + // do not include HEIC here + val mediaDir = getAllMetadataByMediaMetadataRetriever(uri) + if (mediaDir.isNotEmpty()) { + metadataMap[Metadata.DIR_MEDIA] = mediaDir + if (mediaDir.containsKey(KEY_HAS_EMBEDDED_PICTURE)) { + metadataMap[Metadata.DIR_COVER_ART] = hashMapOf( + // dummy entry value + "Image" to "data", + ) + } + } + // Android's `MediaExtractor` and `MediaPlayer` cannot be used for details + // about embedded images as they do not list them as separate tracks + // and only identify at most one + } else if (isIsoBMFFImage(mimeType)) { + Mp4ParserHelper.getSamsungSefd(context, uri)?.let { (_, bytes) -> + metadataMap[Mp4ParserHelper.SAMSUNG_MAKERNOTE_BOX_TYPE] = hashMapOf( + "Size" to bytes.size.toString(), + ) + } + } + + if (metadataMap.isNotEmpty()) { + result.success(metadataMap) + } else { + result.error("getAllMetadata-failure", "failed to get metadata for mimeType=$mimeType uri=$uri", null) + } + } + + private fun getAllMetadataByMediaMetadataRetriever(uri: Uri): MutableMap<String, String> { + val dirMap = HashMap<String, String>() + val retriever = StorageUtils.openMetadataRetriever(context, uri) ?: return dirMap + try { + for ((code, name) in MediaMetadataRetrieverHelper.allKeys) { + retriever.getSafeDescription(code) { dirMap[name] = it } + } + if (retriever.embeddedPicture != null) { + // additional key for the Dart side to know whether to add a `Cover` section + dirMap[KEY_HAS_EMBEDDED_PICTURE] = "yes" + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get video metadata by MediaMetadataRetriever for uri=$uri", e) + } finally { + // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs + retriever.release() + } + return dirMap + } + + // set `KEY_DATE_MILLIS` from these fields (by precedence): + // - Exif / DATETIME_ORIGINAL + // - Exif / DATETIME + // - XMP / xmp:CreateDate + // - XMP / photoshop:DateCreated + // - PNG / TIME / LAST_MODIFICATION_TIME + // - Video / METADATA_KEY_DATE + // set `KEY_XMP_TITLE` from these fields (by precedence): + // - XMP / dc:title + // - IPTC / object-name + // set `KEY_XMP_SUBJECTS` from these fields (by precedence): + // - XMP / dc:subject + // - IPTC / keywords + // set `KEY_RATING` from these fields (by precedence): + // - XMP / xmp:Rating + // - XMP / MicrosoftPhoto:Rating + private fun getCatalogMetadata(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val path = call.argument<String>("path") + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + if (mimeType == null || uri == null) { + result.error("getCatalogMetadata-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, Any>() + getCatalogMetadataByMetadataExtractor(mimeType, uri, path, sizeBytes, metadataMap) + + if (isVideo(mimeType) || isIsoBMFFImage(mimeType)) { + getMultimediaCatalogMetadataByMediaMetadataRetriever(mimeType, uri, metadataMap) + + // fallback to MP4 `loci` box for location + if (!metadataMap.contains(KEY_LATITUDE) || !metadataMap.contains(KEY_LONGITUDE)) { + try { + Mp4ParserHelper.getUserDataBox(context, mimeType, uri)?.let { userDataBox -> + Path.getPath<LocationInformationBox>(userDataBox, LocationInformationBox.TYPE)?.let { locationBox -> + if (!locationBox.isParsed) { + locationBox.parseDetails() + } + metadataMap[KEY_LATITUDE] = locationBox.latitude + metadataMap[KEY_LONGITUDE] = locationBox.longitude + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get Location Information box by MP4 parser for mimeType=$mimeType uri=$uri", e) + } + } + } + + if (isIsoBMFFImage(mimeType)) { + val flags = (metadataMap[KEY_FLAGS] ?: 0) as Int + if ((flags and MASK_IS_MOTION_PHOTO == 0) && MultiPage.isIsoBMFFImageSefdMotionPhoto(context, uri)) { + metadataMap[KEY_FLAGS] = flags or MASK_IS_MULTIPAGE or MASK_IS_MOTION_PHOTO + } + } + + // report success even when empty + result.success(metadataMap) + } + + private fun getCatalogMetadataByMetadataExtractor( + mimeType: String, + uri: Uri, + path: String?, + sizeBytes: Long?, + metadataMap: HashMap<String, Any>, + ) { + var flags = (metadataMap[KEY_FLAGS] ?: 0) as Int + var foundExif = false + var foundXmp = false + var foundMp4Uuid = false + + fun processXmp(xmpMeta: XMPMeta, allowMultiple: Boolean = false) { + if (foundXmp && !allowMultiple) return + foundXmp = true + try { + if (xmpMeta.doesPropExist(XMP.DC_SUBJECT_PROP_NAME)) { + val values = xmpMeta.getPropArrayItemValues(XMP.DC_SUBJECT_PROP_NAME) + metadataMap[KEY_XMP_SUBJECTS] = values.joinToString(XMP_SUBJECTS_SEPARATOR) + } + xmpMeta.getSafeLocalizedText(XMP.DC_TITLE_PROP_NAME, acceptBlank = false) { metadataMap[KEY_XMP_TITLE] = it } + if (!metadataMap.containsKey(KEY_DATE_MILLIS)) { + xmpMeta.getSafeDateMillis(XMP.XMP_CREATE_DATE_PROP_NAME) { metadataMap[KEY_DATE_MILLIS] = it } + if (!metadataMap.containsKey(KEY_DATE_MILLIS)) { + xmpMeta.getSafeDateMillis(XMP.PS_DATE_CREATED_PROP_NAME) { metadataMap[KEY_DATE_MILLIS] = it } + } + } + + xmpMeta.getSafeInt(XMP.XMP_RATING_PROP_NAME) { metadataMap[KEY_RATING] = it } + if (!metadataMap.containsKey(KEY_RATING)) { + xmpMeta.getSafeInt(XMP.MS_RATING_PROP_NAME) { percentRating -> + // values of 1,25,50,75,99% correspond to 1,2,3,4,5 stars + val standardRating = (percentRating / 25f).roundToInt() + 1 + metadataMap[KEY_RATING] = standardRating + } + } + + // identification of panorama (aka photo sphere) + if (xmpMeta.isPanorama()) { + flags = flags or MASK_IS_360 + } + + // identification of motion photo + if (xmpMeta.isMotionPhoto()) { + flags = flags or MASK_IS_MULTIPAGE or MASK_IS_MOTION_PHOTO + } + + // identification of embedded gain map + if (xmpMeta.hasHdrGainMap()) { + flags = flags or MASK_IS_HDR + } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to read XMP directory for uri=$uri", e) + } + } + + fun processMp4Uuid(dir: Mp4UuidBoxDirectory) { + // identification of spherical video (aka 360° video) + if (dir.getString(Mp4UuidBoxDirectory.TAG_UUID) == GSpherical.SPHERICAL_VIDEO_V1_UUID) { + flags = flags or MASK_IS_360 + } + } + + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + foundExif = metadata.directories.any { it is ExifDirectoryBase && it.tagCount > 0 } + foundMp4Uuid = metadata.directories.any { it is Mp4UuidBoxDirectory && it.tagCount > 0 } + + // File type + for (dir in metadata.getDirectoriesOfType(FileTypeDirectory::class.java)) { + // * `metadata-extractor` sometimes detects the wrong MIME type (e.g. `pef` file as `tiff`, `mpeg` as `dvd`, `avif` as `mov`) + // * the content resolver / media store sometimes reports the wrong MIME type (e.g. `png` file as `jpeg`, `tiff` as `srw`) + // * `context.getContentResolver().getType()` sometimes returns an incorrect value + // * `MediaMetadataRetriever.setDataSource()` sometimes fails with `status = 0x80000000` + // * file extension is unreliable + // In the end, `metadata-extractor` is the most reliable, except for `tiff`/`dvd`/`mov`/`zip` (false positives, false negatives), + // in which case we trust the file extension + // cf https://github.com/drewnoakes/metadata-extractor/issues/296 + if (path?.matches(TIFF_EXTENSION_PATTERN) == true) { + metadataMap[KEY_MIME_TYPE] = MimeTypes.TIFF + } else { + dir.getSafeString(FileTypeDirectory.TAG_DETECTED_FILE_MIME_TYPE) { + if (it != MimeTypes.TIFF && it != MimeTypes.DVD && it != MimeTypes.MOV && it != MimeTypes.ZIP) { + metadataMap[KEY_MIME_TYPE] = it + } + } + } + } + + // EXIF + for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) { + dir.getDateOriginalMillis { metadataMap[KEY_DATE_MILLIS] = it } + if (!metadataMap.containsKey(KEY_DATE_MILLIS)) { + // fetch date modified from SubIFD directory first, as the sub-second tag is here + dir.getDateModifiedMillis { metadataMap[KEY_DATE_MILLIS] = it } + } + } + for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) { + if (!metadataMap.containsKey(KEY_DATE_MILLIS)) { + // fallback to fetch date modified from IFD0 directory, without the sub-second tag + // in case there was no SubIFD directory + dir.getSafeDateMillis(ExifIFD0Directory.TAG_DATETIME, null)?.let { metadataMap[KEY_DATE_MILLIS] = it } + } + dir.getSafeInt(ExifDirectoryBase.TAG_ORIENTATION) { + val orientation = it + if (isFlippedForExifCode(orientation)) { + flags = flags or MASK_IS_FLIPPED + } + metadataMap[KEY_ROTATION_DEGREES] = getRotationDegreesForExifCode(orientation) + } + } + + // GPS + for (dir in metadata.getDirectoriesOfType(GpsDirectory::class.java)) { + val geoLocation = dir.geoLocation + if (geoLocation != null) { + metadataMap[KEY_LATITUDE] = geoLocation.latitude + metadataMap[KEY_LONGITUDE] = geoLocation.longitude + } + } + + // JPEG Multi-Picture Format + if (metadata.getDirectoriesOfType(MpEntryDirectory::class.java).count { !it.entry.isThumbnail } > 1) { + flags = flags or MASK_IS_MULTIPAGE + + if (hasAppleHdrGainMap(uri, sizeBytes)) { + flags = flags or MASK_IS_HDR + } + } + + // XMP + if (!isLargeMp4(mimeType, sizeBytes)) { + metadata.getDirectoriesOfType(XmpDirectory::class.java).map { it.xmpMeta }.forEach { + processXmp(it, allowMultiple = true) + } + + // XMP fallback to IPTC + if (!metadataMap.containsKey(KEY_XMP_TITLE) || !metadataMap.containsKey(KEY_XMP_SUBJECTS)) { + for (dir in metadata.getDirectoriesOfType(IptcDirectory::class.java)) { + if (!metadataMap.containsKey(KEY_XMP_TITLE)) { + dir.getSafeString(IptcDirectory.TAG_OBJECT_NAME, acceptBlank = false) { metadataMap[KEY_XMP_TITLE] = it } + } + if (!metadataMap.containsKey(KEY_XMP_SUBJECTS)) { + dir.keywords?.let { metadataMap[KEY_XMP_SUBJECTS] = it.joinToString(XMP_SUBJECTS_SEPARATOR) } + } + } + } + } + + if (!metadataMap.containsKey(KEY_LATITUDE) || !metadataMap.containsKey(KEY_LONGITUDE)) { + for (dir in metadata.getDirectoriesOfType(QuickTimeMetadataDirectory::class.java)) { + dir.getSafeString(QuickTimeMetadataDirectory.TAG_LOCATION_ISO6709) { locationString -> + val matcher = Metadata.VIDEO_LOCATION_PATTERN.matcher(locationString) + if (matcher.find() && matcher.groupCount() >= 2) { + val latitude = matcher.group(1)?.toDoubleOrNull() + val longitude = matcher.group(2)?.toDoubleOrNull() + if (latitude != null && longitude != null) { + metadataMap[KEY_LATITUDE] = latitude + metadataMap[KEY_LONGITUDE] = longitude + } + } + } + } + } + + when (mimeType) { + MimeTypes.PNG -> { + // date fallback to PNG time chunk + if (!metadataMap.containsKey(KEY_DATE_MILLIS)) { + for (dir in metadata.getDirectoriesOfType(PngDirectory::class.java).filter { it.name == PNG_TIME_DIR_NAME }) { + dir.getSafeString(PngDirectory.TAG_LAST_MODIFICATION_TIME) { + try { + PNG_LAST_MODIFICATION_TIME_FORMAT.parse(it)?.let { date -> + metadataMap[KEY_DATE_MILLIS] = date.time + } + } catch (e: ParseException) { + Log.w(LOG_TAG, "failed to parse PNG date=$it for uri=$uri", e) + } + } + } + } + + // identification of animated PNG + if (metadata.containsDirectoryOfType(PngActlDirectory::class.java)) { + flags = flags or MASK_IS_ANIMATED + } + } + + MimeTypes.GIF -> { + // identification of animated GIF + if (metadata.containsDirectoryOfType(GifAnimationDirectory::class.java)) { + flags = flags or MASK_IS_ANIMATED + } + } + + MimeTypes.WEBP -> { + // identification of animated WEBP + for (dir in metadata.getDirectoriesOfType(WebpDirectory::class.java)) { + dir.getSafeBoolean(WebpDirectory.TAG_IS_ANIMATION) { + if (it) flags = flags or MASK_IS_ANIMATED + } + } + } + + MimeTypes.TIFF -> { + // identification of GeoTIFF + for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) { + if (dir.containsGeoTiffTags()) { + flags = flags or MASK_IS_GEOTIFF + } + } + } + } + + metadata.getDirectoriesOfType(Mp4UuidBoxDirectory::class.java).forEach(::processMp4Uuid) + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + + if (!foundExif && canReadWithExifInterface(mimeType)) { + // fallback to read EXIF via ExifInterface + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val exif = ExifInterface(input) + exif.getSafeDateMillis(ExifInterface.TAG_DATETIME_ORIGINAL, ExifInterface.TAG_SUBSEC_TIME_ORIGINAL) { metadataMap[KEY_DATE_MILLIS] = it } + if (!metadataMap.containsKey(KEY_DATE_MILLIS)) { + exif.getSafeDateMillis(ExifInterface.TAG_DATETIME, ExifInterface.TAG_SUBSEC_TIME) { metadataMap[KEY_DATE_MILLIS] = it } + } + exif.getSafeInt(ExifInterface.TAG_ORIENTATION, acceptZero = false) { + if (exif.isFlipped) flags = flags or MASK_IS_FLIPPED + metadataMap[KEY_ROTATION_DEGREES] = exif.rotationDegrees + } + val latLong = exif.latLong + if (latLong?.size == 2) { + metadataMap[KEY_LATITUDE] = latLong[0] + metadataMap[KEY_LONGITUDE] = latLong[1] + } + } + } catch (e: Exception) { + // ExifInterface initialization can fail with a RuntimeException + // caused by an internal MediaMetadataRetriever failure + Log.w(LOG_TAG, "failed to get metadata by ExifInterface for mimeType=$mimeType uri=$uri", e) + } + } + + XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::processXmp) + // `metadata-extractor` may fail to get UUID boxes for some MP4 files, + // so we always check with `mp4parser`, even for smaller files + XMP.checkMp4(context, mimeType, uri) { dirs -> + for (dir in dirs.filterIsInstance<XmpDirectory>()) { + processXmp(dir.xmpMeta) + } + if (!foundMp4Uuid) { + for (dir in dirs.filterIsInstance<Mp4UuidBoxDirectory>()) { + processMp4Uuid(dir) + } + } + } + + if (mimeType == MimeTypes.TIFF && MultiPage.isMultiPageTiff(context, uri)) flags = flags or MASK_IS_MULTIPAGE + + metadataMap[KEY_FLAGS] = flags + } + + private fun hasAppleHdrGainMap(uri: Uri, sizeBytes: Long?): Boolean { + val mpEntries = MultiPage.getJpegMpfEntries(context, uri, sizeBytes) ?: return false + mpEntries.filter { it.type == MpEntry.TYPE_UNDEFINED }.forEachIndexed { mpIndex, mpEntry -> + var dataOffset = mpEntry.dataOffset + if (dataOffset > 0) { + val baseOffset = MultiPage.getJpegMpfBaseOffset(context, uri, sizeBytes) + if (baseOffset != null) { + dataOffset += baseOffset + } + } + StorageUtils.openInputStream(context, uri)?.let { input -> + input.skip(dataOffset) + try { + val pageMetadata = Helper.safeRead(input, sizeBytes) + if (pageMetadata.getDirectoriesOfType(XmpDirectory::class.java).any { it.xmpMeta.hasHdrGainMap() }) { + return true + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for uri=$uri mpIndex=$mpIndex mpEntry=$mpEntry", e) + } + } + } + return false + } + + private fun getMultimediaCatalogMetadataByMediaMetadataRetriever( + mimeType: String, + uri: Uri, + metadataMap: HashMap<String, Any>, + ) { + val retriever = StorageUtils.openMetadataRetriever(context, uri) ?: return + + var flags = (metadataMap[KEY_FLAGS] ?: 0) as Int + try { + retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION) { metadataMap[KEY_ROTATION_DEGREES] = it } + if (!metadataMap.containsKey(KEY_DATE_MILLIS)) { + retriever.getSafeDateMillis(MediaMetadataRetriever.METADATA_KEY_DATE) { metadataMap[KEY_DATE_MILLIS] = it } + } + + if (!metadataMap.containsKey(KEY_LATITUDE) || !metadataMap.containsKey(KEY_LONGITUDE)) { + val locationString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION) + if (locationString != null) { + val matcher = Metadata.VIDEO_LOCATION_PATTERN.matcher(locationString) + if (matcher.find() && matcher.groupCount() >= 2) { + val latitude = matcher.group(1)?.toDoubleOrNull() + val longitude = matcher.group(2)?.toDoubleOrNull() + if (latitude != null && longitude != null) { + metadataMap[KEY_LATITUDE] = latitude + metadataMap[KEY_LONGITUDE] = longitude + } + } + } + } + + if (isIsoBMFFImage(mimeType)) { + retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS) { + if (it > 1) flags = flags or MASK_IS_MULTIPAGE + } + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_COLOR_TRANSFER) { + if (it == MediaFormat.COLOR_TRANSFER_ST2084 || it == MediaFormat.COLOR_TRANSFER_HLG) { + flags = flags or MASK_IS_HDR + } + } + } + + metadataMap[KEY_FLAGS] = flags + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get catalog metadata by MediaMetadataRetriever for uri=$uri", e) + } finally { + // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs + retriever.release() + } + } + + private fun getOverlayMetadata(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val fields = call.argument<List<String>>("fields") + if (mimeType == null || uri == null || fields == null) { + result.error("getOverlayMetadata-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, Any>() + if (fields.isEmpty() || isVideo(mimeType)) { + result.success(metadataMap) + return + } + + val saveExposureTime = fun(value: Rational) { + // `TAG_EXPOSURE_TIME` as a string is sometimes a ratio, sometimes a decimal + // so we explicitly request it as a rational (e.g. 1/100, 1/14, 71428571/1000000000, 4000/1000, 2000000000/500000000) + // and process it to make sure the numerator is `1` when the ratio value is less than 1 + val num = value.numerator + val denom = value.denominator + metadataMap[KEY_EXPOSURE_TIME] = when { + num >= denom -> "${value.toSimpleString(true)}″" + num != 1L && num != 0L -> Rational(1, (denom / num.toDouble()).roundToLong()).toString() + else -> value.toString() + } + } + + var foundExif = false + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) { + foundExif = true + if (fields.contains(KEY_APERTURE)) { + dir.getSafeRational(ExifDirectoryBase.TAG_FNUMBER) { metadataMap[KEY_APERTURE] = it.numerator.toDouble() / it.denominator } + } + if (fields.contains(KEY_DESCRIPTION)) { + getDescriptionByMetadataExtractor(metadata)?.let { metadataMap[KEY_DESCRIPTION] = it } + } + if (fields.contains(KEY_EXPOSURE_TIME)) { + dir.getSafeRational(ExifDirectoryBase.TAG_EXPOSURE_TIME, saveExposureTime) + } + if (fields.contains(KEY_FOCAL_LENGTH)) { + dir.getSafeRational(ExifDirectoryBase.TAG_FOCAL_LENGTH) { metadataMap[KEY_FOCAL_LENGTH] = it.numerator.toDouble() / it.denominator } + } + if (fields.contains(KEY_ISO)) { + dir.getSafeInt(ExifDirectoryBase.TAG_ISO_EQUIVALENT) { metadataMap[KEY_ISO] = it } + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + + if (!foundExif && canReadWithExifInterface(mimeType)) { + // fallback to read EXIF via ExifInterface + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val exif = ExifInterface(input) + if (fields.contains(KEY_APERTURE)) { + exif.getSafeDouble(ExifInterface.TAG_F_NUMBER) { metadataMap[KEY_APERTURE] = it } + } + if (fields.contains(KEY_EXPOSURE_TIME)) { + exif.getSafeRational(ExifInterface.TAG_EXPOSURE_TIME, saveExposureTime) + } + if (fields.contains(KEY_FOCAL_LENGTH)) { + exif.getSafeDouble(ExifInterface.TAG_FOCAL_LENGTH) { metadataMap[KEY_FOCAL_LENGTH] = it } + } + if (fields.contains(KEY_ISO)) { + exif.getSafeInt(ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY) { metadataMap[KEY_ISO] = it } + } + } + } catch (e: Exception) { + // ExifInterface initialization can fail with a RuntimeException + // caused by an internal MediaMetadataRetriever failure + Log.w(LOG_TAG, "failed to get metadata by ExifInterface for mimeType=$mimeType uri=$uri", e) + } + } + + result.success(metadataMap) + } + + // returns description from these fields (by precedence): + // - XMP / dc:description + // - IPTC / caption-abstract + // - Exif / UserComment + // - Exif / ImageDescription + private fun getDescriptionByMetadataExtractor(metadata: com.drew.metadata.Metadata): String? { + var description: String? = null + for (dir in metadata.getDirectoriesOfType(XmpDirectory::class.java)) { + val xmpMeta = dir.xmpMeta + try { + if (xmpMeta.doesPropExist(XMP.DC_DESCRIPTION_PROP_NAME)) { + xmpMeta.getSafeLocalizedText(XMP.DC_DESCRIPTION_PROP_NAME, acceptBlank = false) { description = it } + } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to read XMP directory", e) + } + } + if (description == null) { + for (dir in metadata.getDirectoriesOfType(IptcDirectory::class.java)) { + dir.getSafeString(IptcDirectory.TAG_CAPTION, acceptBlank = false) { description = it } + } + } + if (description == null) { + for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) { + // user comment field specifies encoding, unlike other string fields + if (dir.containsTag(ExifSubIFDDirectory.TAG_USER_COMMENT)) { + val string = dir.getDescription(ExifSubIFDDirectory.TAG_USER_COMMENT) + if (string.isNotBlank()) { + description = string + } + } + } + } + if (description == null) { + for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) { + dir.getSafeString(ExifIFD0Directory.TAG_IMAGE_DESCRIPTION, acceptBlank = false) { description = it } + } + } + return description + } + + private fun getGeoTiffInfo(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + if (mimeType == null || uri == null) { + result.error("getGeoTiffInfo-args", "missing arguments", null) + return + } + + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + val fields = HashMap<Int, Any?>() + for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) { + if (dir.containsGeoTiffTags()) { + fields.putAll(dir.tags.map { it.tagType }.filter { ExifTags.isGeoTiffTag(it) }.map { + val value = when (it) { + ExifGeoTiffTags.TAG_GEO_ASCII_PARAMS -> dir.getString(it) + else -> dir.getObject(it) + } + Pair(it, value) + }) + val geoKeyDirectory = dir.getIntArray(ExifGeoTiffTags.TAG_GEO_KEY_DIRECTORY) + fields.putAll((dir as ExifIFD0Directory).extractGeoKeys(geoKeyDirectory)) + } + } + result.success(fields) + return + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + result.error("getGeoTiffInfo-empty", "failed to get info for mimeType=$mimeType uri=$uri", null) + } + + private fun getMultiPageInfo(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val isMotionPhoto = call.argument<Boolean>("isMotionPhoto") + if (mimeType == null || uri == null || sizeBytes == null || isMotionPhoto == null) { + result.error("getMultiPageInfo-args", "missing arguments", null) + return + } + + val pages: ArrayList<FieldMap>? = if (isMotionPhoto) { + MultiPage.getMotionPhotoPages(context, uri, mimeType, sizeBytes) + } else { + when (mimeType) { + MimeTypes.HEIC, MimeTypes.HEIF -> MultiPage.getHeicTracks(context, uri) + MimeTypes.JPEG -> MultiPage.getJpegMpfPages(context, uri, sizeBytes) + MimeTypes.TIFF -> MultiPage.getTiffPages(context, uri) + else -> null + } + } + if (pages?.isEmpty() == true) { + result.error("getMultiPageInfo-empty", "failed to get pages for mimeType=$mimeType uri=$uri", null) + } else { + result.success(pages) + } + } + + private fun getPanoramaInfo(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + if (mimeType == null || uri == null) { + result.error("getPanoramaInfo-args", "missing arguments", null) + return + } + + val fields: FieldMap = hashMapOf() + var foundXmp = false + + fun processXmp(xmpMeta: XMPMeta, allowMultiple: Boolean = false) { + if (foundXmp && !allowMultiple) return + foundXmp = true + fields.putAll(GoogleXMP.getPanoramaInfo(xmpMeta)) + } + + if (canReadWithMetadataExtractor(mimeType) && !isLargeMp4(mimeType, sizeBytes)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + metadata.getDirectoriesOfType(XmpDirectory::class.java).map { it.xmpMeta }.forEach { + processXmp(it, allowMultiple = true) + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + + XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::processXmp) + // `metadata-extractor` may fail to get UUID boxes for some MP4 files, + // so we always check with `mp4parser`, even for smaller files + XMP.checkMp4(context, mimeType, uri) { dirs -> + for (dir in dirs.filterIsInstance<XmpDirectory>()) { + processXmp(dir.xmpMeta) + } + } + + if (fields.isEmpty()) { + result.error("getPanoramaInfo-empty", "failed to get info for mimeType=$mimeType uri=$uri", null) + } else { + fields["projectionType"] = fields["projectionType"] ?: GoogleXMP.GPANO_PROJECTION_TYPE_DEFAULT + result.success(fields) + } + } + + private fun getIptc(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + if (mimeType == null || uri == null) { + result.error("getIptc-args", "missing arguments", null) + return + } + + if (MimeTypes.canReadWithPixyMeta(mimeType)) { + try { + StorageUtils.openInputStream(context, uri)?.use { input -> + val iptcDataList = PixyMetaHelper.getIptc(input) + result.success(iptcDataList) + return + } + } catch (e: Exception) { + result.error("getIptc-exception", "failed to read IPTC for mimeType=$mimeType uri=$uri", e.message) + return + } + } + + result.success(null) + } + + // returns XMP components + // returns an empty list if there is no XMP + private fun getXmp(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + if (mimeType == null || uri == null) { + result.error("getXmp-args", "missing arguments", null) + return + } + + val xmpStrings = mutableListOf<String>() + var foundXmp = false + + fun processXmp(xmpMeta: XMPMeta, allowMultiple: Boolean = false) { + if (foundXmp && !allowMultiple) return + foundXmp = true + try { + xmpStrings.add(XMPMetaFactory.serializeToString(xmpMeta, xmpSerializeOptions)) + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to read XMP directory for uri=$uri", e) + } + } + + if (canReadWithMetadataExtractor(mimeType) && !isLargeMp4(mimeType, sizeBytes)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + metadata.getDirectoriesOfType(XmpDirectory::class.java).map { it.xmpMeta }.forEach { + processXmp(it, allowMultiple = true) + } + } + } catch (e: Exception) { + result.error("getXmp-exception", "failed to read XMP for mimeType=$mimeType uri=$uri", e.message) + return + } catch (e: NoClassDefFoundError) { + result.error("getXmp-noclass", "failed to read XMP for mimeType=$mimeType uri=$uri", e.message) + return + } catch (e: AssertionError) { + result.error("getXmp-assert", "failed to read XMP for mimeType=$mimeType uri=$uri", e.message) + return + } + } + + XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::processXmp) + // `metadata-extractor` may fail to get UUID boxes for some MP4 files, + // so we always check with `mp4parser`, even for smaller files + XMP.checkMp4(context, mimeType, uri) { dirs -> + for (dir in dirs.filterIsInstance<XmpDirectory>()) { + processXmp(dir.xmpMeta) + } + } + + result.success(xmpStrings) + } + + private fun hasContentProp(call: MethodCall, result: MethodChannel.Result) { + val prop = call.argument<String>("prop") + if (prop == null) { + result.error("hasContentProp-args", "missing arguments", null) + return + } + + result.success( + when (prop) { + "owner_package_name" -> Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q + else -> { + result.error("hasContentProp-unknown", "unknown property=$prop", null) + return + } + } + ) + } + + private fun getContentPropValue(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val prop = call.argument<String>("prop") + if (mimeType == null || uri == null || prop == null) { + result.error("getContentPropValue-args", "missing arguments", null) + return + } + + try { + val value = context.queryContentPropValue(uri, mimeType, prop) + result.success(value?.toString()) + } catch (e: Exception) { + result.error("getContentPropValue-query", "failed to query prop for uri=$uri", e.message) + } + } + + private fun getDate(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val field = call.argument<String>("field") + if (mimeType == null || uri == null || field == null) { + result.error("getDate-args", "missing arguments", null) + return + } + + var dateMillis: Long? = null + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + val tag = when (field) { + ExifInterface.TAG_DATETIME -> ExifIFD0Directory.TAG_DATETIME + ExifInterface.TAG_DATETIME_DIGITIZED -> ExifSubIFDDirectory.TAG_DATETIME_DIGITIZED + ExifInterface.TAG_DATETIME_ORIGINAL -> ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL + ExifInterface.TAG_GPS_DATESTAMP -> GpsDirectory.TAG_DATE_STAMP + else -> { + result.error("getDate-field", "unsupported ExifInterface field=$field", null) + return + } + } + + when (tag) { + ExifIFD0Directory.TAG_DATETIME -> { + for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) { + dir.getDateModifiedMillis { dateMillis = it } + } + if (dateMillis == null) { + for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) { + dir.getSafeDateMillis(ExifIFD0Directory.TAG_DATETIME, null)?.let { dateMillis = it } + } + } + } + + ExifSubIFDDirectory.TAG_DATETIME_DIGITIZED -> { + for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) { + dir.getDateDigitizedMillis { dateMillis = it } + } + } + + ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL -> { + for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) { + dir.getDateOriginalMillis { dateMillis = it } + } + } + + GpsDirectory.TAG_DATE_STAMP -> { + for (dir in metadata.getDirectoriesOfType(GpsDirectory::class.java)) { + dir.gpsDate?.let { dateMillis = it.time } + } + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + + result.success(dateMillis) + } + + private fun getFields(call: MethodCall, result: MethodChannel.Result) { + val mimeType = call.argument<String>("mimeType") + val uri = call.argument<String>("uri")?.toUri() + val sizeBytes = call.argument<Number>("sizeBytes")?.toLong() + val fields = call.argument<List<String>>("fields") + if (mimeType == null || uri == null || fields == null) { + result.error("getFields-args", "missing arguments", null) + return + } + + val metadataMap = HashMap<String, Any?>() + + val hashFields = fields.filter { it.startsWith(HASH_FIELD_PREFIX) }.toSet() + metadataMap.putAll(getHashFields(uri, mimeType, sizeBytes, hashFields)) + + val exifFields = fields.filterNot { hashFields.contains(it) }.toSet() + metadataMap.putAll(getExifFields(uri, mimeType, sizeBytes, exifFields)) + + result.success(metadataMap) + } + + private fun getHashFields(uri: Uri, mimeType: String, sizeBytes: Long?, fields: Set<String>): FieldMap { + val metadataMap = HashMap<String, Any?>() + fields.forEach { field -> + val function = field.substringAfter(HASH_FIELD_PREFIX).lowercase(Locale.ROOT) + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + metadataMap[field] = HashUtils.getHash(input, function) + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get hash for mimeType=$mimeType uri=$uri function=$function", e) + } + } + return metadataMap + } + + private fun getExifFields(uri: Uri, mimeType: String, sizeBytes: Long?, fields: Set<String>): FieldMap { + val metadataMap = HashMap<String, Any?>() + if (fields.isEmpty() || isVideo(mimeType)) { + return metadataMap + } + + var foundExif = false + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + for (dir in metadata.getDirectoriesOfType(ExifDirectoryBase::class.java)) { + foundExif = true + val allTags = ExifInterfaceHelper.allTags + fields.forEach { tag -> + allTags[tag]?.let { mapper -> + val tagType = mapper.type + dir.getDescription(tagType)?.let { value -> metadataMap[tag] = value } + } + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + + if (!foundExif && canReadWithExifInterface(mimeType)) { + // fallback to read EXIF via ExifInterface + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val exif = ExifInterface(input) + fields.forEach { tag -> + if (exif.hasAttribute(tag)) { + val value = exif.getAttribute(tag) + if (value != null) { + metadataMap[tag] = value + } + } + } + } + } catch (e: Exception) { + // ExifInterface initialization can fail with a RuntimeException + // caused by an internal MediaMetadataRetriever failure + Log.w(LOG_TAG, "failed to get metadata by ExifInterface for mimeType=$mimeType uri=$uri", e) + } + } + + return metadataMap + } + + companion object { + private val LOG_TAG = LogUtils.createTag<MetadataFetchHandler>() + const val CHANNEL = "deckers.thibault/aves/metadata_fetch" + + private val doubleFormat = DecimalFormat("0.###") + + private val allMetadataRedundantDirNames = setOf( + "MP4", + "MP4 Metadata", + "MP4 Sound", + "MP4 Video", + "QuickTime", + "QuickTime Sound", + "QuickTime Video", + ) + private val allMetadataMergeableDirNames = setOf( + "Exif SubIFD", + "GIF Control", + "GIF Image", + "HEIF", + "ICC Profile", + "IPTC", + "WebP", + "XMP", + ) + + private val xmpSerializeOptions = SerializeOptions().apply { + omitPacketWrapper = true // e.g. <?xpacket begin="..." id="W5M0MpCehiHzreSzNTczkc9d"?>...<?xpacket end="r"?> + omitXmpMetaElement = false // e.g. <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core Test.SNAPSHOT">...</x:xmpmeta> + } + + private fun isLargeMp4(mimeType: String, sizeBytes: Long?) = mimeType == MimeTypes.MP4 && Metadata.isDangerouslyLarge(sizeBytes) + + private fun exifTagMapper(it: Tag): Pair<String, String> { + val name = if (it.hasTagName()) { + it.tagName + } else { + ExifTags.getTagName(it.tagType) ?: it.tagName + } + return Pair(name, it.description) + } + + // catalog metadata + private const val KEY_MIME_TYPE = "mimeType" + private const val KEY_DATE_MILLIS = "dateMillis" + private const val KEY_FLAGS = "flags" + private const val KEY_ROTATION_DEGREES = "rotationDegrees" + private const val KEY_LATITUDE = "latitude" + private const val KEY_LONGITUDE = "longitude" + private const val KEY_XMP_SUBJECTS = "xmpSubjects" + private const val KEY_XMP_TITLE = "xmpTitle" + private const val KEY_RATING = "rating" + + private const val MASK_IS_ANIMATED = 1 shl 0 + private const val MASK_IS_FLIPPED = 1 shl 1 + private const val MASK_IS_GEOTIFF = 1 shl 2 + private const val MASK_IS_360 = 1 shl 3 + private const val MASK_IS_MULTIPAGE = 1 shl 4 + private const val MASK_IS_MOTION_PHOTO = 1 shl 5 + private const val MASK_IS_HDR = 1 shl 6 // for images: embedded HDR gainmap, for videos: HDR color transfer + private const val XMP_SUBJECTS_SEPARATOR = ";" + + // overlay metadata + private const val KEY_APERTURE = "aperture" + private const val KEY_DESCRIPTION = "description" + private const val KEY_EXPOSURE_TIME = "exposureTime" + private const val KEY_FOCAL_LENGTH = "focalLength" + private const val KEY_ISO = "iso" + + // additional media key + private const val KEY_HAS_EMBEDDED_PICTURE = "Has Embedded Picture" + + private const val HASH_FIELD_PREFIX = "hash" + private const val VALUE_SKIPPED_DATA = "[skipped]" + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/SecurityHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/SecurityHandler.kt new file mode 100644 index 0000000..1263ce7 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/SecurityHandler.kt @@ -0,0 +1,80 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import android.content.SharedPreferences +import androidx.core.content.edit +import androidx.security.crypto.EncryptedSharedPreferences +import androidx.security.crypto.MasterKey +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler + +class SecurityHandler(private val context: Context) : MethodCallHandler { + private var sharedPreferences: SharedPreferences? = null + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "writeValue" -> safe(call, result, ::writeValue) + "readValue" -> safe(call, result, ::readValue) + else -> result.notImplemented() + } + } + + private fun getStore(): SharedPreferences { + if (sharedPreferences == null) { + val mainKey = MasterKey.Builder(context) + .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) + .build() + sharedPreferences = EncryptedSharedPreferences.create( + context, + FILENAME, + mainKey, + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM + ) + } + return sharedPreferences!! + } + + private fun writeValue(call: MethodCall, result: MethodChannel.Result) { + val key = call.argument<String>("key") + val value = call.argument<Any?>("value") + if (key == null) { + result.error("writeValue-args", "missing arguments", null) + return + } + + val preferences = getStore() + preferences.edit { + when (value) { + is Boolean -> putBoolean(key, value) + is Float -> putFloat(key, value) + is Int -> putInt(key, value) + is Long -> putLong(key, value) + is String -> putString(key, value) + null -> remove(key) + else -> { + result.error("writeValue-type", "unsupported type for value=$value", null) + return + } + } + } + result.success(true) + } + + private fun readValue(call: MethodCall, result: MethodChannel.Result) { + val key = call.argument<String>("key") + if (key == null) { + result.error("readValue-args", "missing arguments", null) + return + } + + result.success(getStore().all[key]) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/security" + const val FILENAME = "secret_shared_prefs" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/StorageHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/StorageHandler.kt new file mode 100644 index 0000000..6c456fc --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/StorageHandler.kt @@ -0,0 +1,269 @@ +package deckers.thibault.aves.channel.calls + +import android.content.Context +import android.os.Build +import android.os.Environment +import android.os.storage.StorageManager +import androidx.core.os.EnvironmentCompat +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.PermissionManager +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.StorageUtils.getFolderSize +import deckers.thibault.aves.utils.StorageUtils.getPrimaryVolumePath +import deckers.thibault.aves.utils.StorageUtils.getVolumePaths +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import io.flutter.util.PathUtils +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import java.io.File + +class StorageHandler(private val context: Context) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "getDataUsage" -> ioScope.launch { safe(call, result, ::getDataUsage) } + "getStorageVolumes" -> ioScope.launch { safe(call, result, ::getStorageVolumes) } + "getCacheDirectory" -> ioScope.launch { safe(call, result, ::getCacheDirectory) } + "getUntrackedTrashPaths" -> ioScope.launch { safe(call, result, ::getUntrackedTrashPaths) } + "getUntrackedVaultPaths" -> ioScope.launch { safe(call, result, ::getUntrackedVaultPaths) } + "getVaultRoot" -> ioScope.launch { safe(call, result, ::getVaultRoot) } + "getFreeSpace" -> ioScope.launch { safe(call, result, ::getFreeSpace) } + "getGrantedDirectories" -> ioScope.launch { safe(call, result, ::getGrantedDirectories) } + "getInaccessibleDirectories" -> ioScope.launch { safe(call, result, ::getInaccessibleDirectories) } + "getRestrictedDirectories" -> ioScope.launch { safe(call, result, ::getRestrictedDirectories) } + "revokeDirectoryAccess" -> safe(call, result, ::revokeDirectoryAccess) + "deleteEmptyDirectories" -> ioScope.launch { safe(call, result, ::deleteEmptyDirectories) } + "deleteTempDirectory" -> ioScope.launch { safe(call, result, ::deleteTempDirectory) } + "deleteExternalCache" -> ioScope.launch { safe(call, result, ::deleteExternalCache) } + "canRequestMediaFileBulkAccess" -> safe(call, result, ::canRequestMediaFileBulkAccess) + "canInsertMedia" -> safe(call, result, ::canInsertMedia) + else -> result.notImplemented() + } + } + + private fun getDataUsage(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + var internalCache = getFolderSize(context.cacheDir) + internalCache += getFolderSize(context.codeCacheDir) + val externalCache = context.externalCacheDirs.sumOf(::getFolderSize) + val externalFilesDirs = context.getExternalFilesDirs(null) + + val dataDir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) context.dataDir else File(context.applicationInfo.dataDir) + + val database = getFolderSize(File(dataDir, "databases")) + val flutter = getFolderSize(File(PathUtils.getDataDirectory(context))) + val vaults = getFolderSize(File(StorageUtils.getVaultRoot(context))) + val trash = externalFilesDirs.mapNotNull { StorageUtils.trashDirFor(context, it.path) }.sumOf(::getFolderSize) + + val internalData = getFolderSize(dataDir) - internalCache + val externalData = externalFilesDirs.sumOf(::getFolderSize) + val miscData = internalData + externalData - (database + flutter + vaults + trash) + + result.success( + hashMapOf( + "database" to database, + "flutter" to flutter, + "vaults" to vaults, + "trash" to trash, + "miscData" to miscData, + "internalCache" to internalCache, + "externalCache" to externalCache, + ) + ) + } + + private fun getStorageVolumes(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + val volumes = ArrayList<Map<String, Any>>() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager + if (sm != null) { + for (volumePath in getVolumePaths(context)) { + try { + sm.getStorageVolume(File(volumePath))?.let { + volumes.add( + hashMapOf( + "path" to volumePath, + "description" to it.getDescription(context), + "isPrimary" to it.isPrimary, + "isRemovable" to it.isRemovable, + "state" to it.state, + ) + ) + } + } catch (_: Exception) { + // ignore + } + } + } + } else { + val primaryVolumePath = getPrimaryVolumePath(context) + for (volumePath in getVolumePaths(context)) { + val volumeFile = File(volumePath) + try { + val isPrimary = volumePath == primaryVolumePath + val isRemovable = Environment.isExternalStorageRemovable(volumeFile) + volumes.add( + hashMapOf( + "path" to volumePath, + "isPrimary" to isPrimary, + "isRemovable" to isRemovable, + "state" to EnvironmentCompat.getStorageState(volumeFile) + ) + ) + } catch (_: Exception) { + // ignore + } + } + } + result.success(volumes) + } + + private fun getCacheDirectory(call: MethodCall, result: MethodChannel.Result) { + val external = call.argument<Boolean>("external") + if (external == null) { + result.error("getCacheDirectory-args", "missing arguments", null) + return + } + + val dir = (if (external) context.externalCacheDir else context.cacheDir) + if (dir == null) { + result.error("getCacheDirectory-null", "context cache dir is null", null) + return + } + + result.success(dir.path) + } + + + private fun getUntrackedTrashPaths(call: MethodCall, result: MethodChannel.Result) { + val knownPaths = call.argument<List<String>>("knownPaths") + if (knownPaths == null) { + result.error("getUntrackedTrashPaths-args", "missing arguments", null) + return + } + + val trashDirs = context.getExternalFilesDirs(null).filterNotNull().mapNotNull { StorageUtils.trashDirFor(context, it.path) } + val trashItemPaths = trashDirs.flatMap { dir -> dir.listFiles()?.filterNotNull()?.mapNotNull { file -> file.path } ?: listOf() } + val untrackedPaths = trashItemPaths.filterNot(knownPaths::contains).toList() + + result.success(untrackedPaths) + } + + private fun getUntrackedVaultPaths(call: MethodCall, result: MethodChannel.Result) { + val vault = call.argument<String>("vault") + val knownPaths = call.argument<List<String>>("knownPaths") + if (vault == null || knownPaths == null) { + result.error("getUntrackedVaultPaths-args", "missing arguments", null) + return + } + + val vaultDir = File(StorageUtils.getVaultRoot(context), vault) + val vaultItemPaths = vaultDir.listFiles()?.mapNotNull { file -> file?.path } ?: listOf() + val untrackedPaths = vaultItemPaths.filterNot(knownPaths::contains).toList() + + result.success(untrackedPaths) + } + + private fun getVaultRoot(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(StorageUtils.getVaultRoot(context)) + } + + private fun getFreeSpace(call: MethodCall, result: MethodChannel.Result) { + val path = call.argument<String>("path") + if (path == null) { + result.error("getFreeSpace-args", "missing arguments", null) + return + } + + // `StorageStatsManager` `getFreeBytes()` is only available from API 26, + // and non-primary volume UUIDs cannot be used with it + val file = File(path) + try { + result.success(file.freeSpace) + } catch (e: SecurityException) { + result.error("getFreeSpace-security", "failed because of missing access", e.message) + } + } + + private fun getGrantedDirectories(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(ArrayList(PermissionManager.getGrantedDirs(context))) + } + + private fun getInaccessibleDirectories(call: MethodCall, result: MethodChannel.Result) { + val dirPaths = call.argument<List<String>>("dirPaths") + if (dirPaths == null) { + result.error("getInaccessibleDirectories-args", "missing arguments", null) + return + } + + result.success(PermissionManager.getInaccessibleDirectories(context, dirPaths)) + } + + private fun getRestrictedDirectories(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(PermissionManager.getRestrictedDirectories(context)) + } + + private fun revokeDirectoryAccess(call: MethodCall, result: MethodChannel.Result) { + val path = call.argument<String>("path") + if (path == null) { + result.error("revokeDirectoryAccess-args", "missing arguments", null) + return + } + + val success = PermissionManager.revokeDirectoryAccess(context, path) + result.success(success) + } + + private fun deleteEmptyDirectories(call: MethodCall, result: MethodChannel.Result) { + val dirPaths = call.argument<List<String>>("dirPaths") + if (dirPaths == null) { + result.error("deleteEmptyDirectories-args", "missing arguments", null) + return + } + + var deleted = 0 + dirPaths.forEach { + try { + val dir = File(it) + if (dir.isDirectory && dir.listFiles()?.isEmpty() == true && dir.delete()) { + deleted++ + } + } catch (_: SecurityException) { + // ignore + } + } + result.success(deleted) + } + + private fun deleteTempDirectory(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(StorageUtils.deleteTempDirectory(context)) + } + + private fun deleteExternalCache(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + context.externalCacheDirs.filter { it.exists() }.forEach { it.deleteRecursively() } + result.success(true) + } + + private fun canRequestMediaFileBulkAccess(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) + } + + private fun canInsertMedia(call: MethodCall, result: MethodChannel.Result) { + val directories = call.argument<List<FieldMap>>("directories") + if (directories == null) { + result.error("canInsertMedia-args", "missing arguments", null) + return + } + + result.success(PermissionManager.canInsertByMediaStore(directories)) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/storage" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/WallpaperHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/WallpaperHandler.kt new file mode 100644 index 0000000..5b91a63 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/WallpaperHandler.kt @@ -0,0 +1,58 @@ +package deckers.thibault.aves.channel.calls + +import android.app.WallpaperManager +import android.app.WallpaperManager.FLAG_LOCK +import android.app.WallpaperManager.FLAG_SYSTEM +import android.content.ContextWrapper +import android.os.Build +import deckers.thibault.aves.channel.calls.Coresult.Companion.safe +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +class WallpaperHandler(private val contextWrapper: ContextWrapper) : MethodCallHandler { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "setWallpaper" -> ioScope.launch { safe(call, result, ::setWallpaper) } + else -> result.notImplemented() + } + } + + private fun setWallpaper(call: MethodCall, result: MethodChannel.Result) { + val bytes = call.argument<ByteArray>("bytes") + val home = call.argument<Boolean>("home") + val lock = call.argument<Boolean>("lock") + if (bytes == null || home == null || lock == null) { + result.error("setWallpaper-args", "missing arguments", null) + return + } + + val manager = WallpaperManager.getInstance(contextWrapper) + val supported = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || manager.isWallpaperSupported + val allowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.N || manager.isSetWallpaperAllowed + if (!supported || !allowed) { + result.error("setWallpaper-unsupported", "failed because setting wallpaper is not allowed", null) + return + } + + bytes.inputStream().use { input -> + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + val flags = (if (home) FLAG_SYSTEM else 0) or (if (lock) FLAG_LOCK else 0) + manager.setStream(input, null, true, flags) + } else { + manager.setStream(input) + } + } + result.success(true) + } + + companion object { + const val CHANNEL = "deckers.thibault/aves/wallpaper" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ActivityWindowHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ActivityWindowHandler.kt new file mode 100644 index 0000000..85201c6 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ActivityWindowHandler.kt @@ -0,0 +1,203 @@ +package deckers.thibault.aves.channel.calls.window + +import android.app.Activity +import android.content.ClipData +import android.content.Context +import android.content.pm.ActivityInfo +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Matrix +import android.graphics.Matrix.ScaleToFit +import android.graphics.Point +import android.graphics.RectF +import android.os.Build +import android.util.Log +import android.view.View +import android.view.WindowManager +import androidx.core.graphics.createBitmap +import androidx.core.net.toUri +import deckers.thibault.aves.channel.calls.AppAdapterHandler.Companion.getShareableUri +import deckers.thibault.aves.utils.ContextUtils.devicePixelRatio +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.getDisplayCompat +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import java.nio.ByteBuffer +import kotlin.math.roundToInt + +class ActivityWindowHandler(private val activity: Activity) : WindowHandler(activity) { + override fun isActivity(call: MethodCall, result: MethodChannel.Result) { + result.success(true) + } + + private fun setWindowFlag(call: MethodCall, result: MethodChannel.Result, flag: Int) { + val on = call.argument<Boolean>("on") + if (on == null) { + result.error("keepOn-args", "missing arguments", null) + return + } + + val window = activity.window + val old = (window.attributes.flags and flag) != 0 + if (old != on) { + if (on) { + window.addFlags(flag) + } else { + window.clearFlags(flag) + } + } + result.success(null) + } + + override fun keepScreenOn(call: MethodCall, result: MethodChannel.Result) { + setWindowFlag(call, result, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + + override fun secureScreen(call: MethodCall, result: MethodChannel.Result) { + setWindowFlag(call, result, WindowManager.LayoutParams.FLAG_SECURE) + } + + override fun isInMultiWindowMode(call: MethodCall, result: MethodChannel.Result) { + val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) activity.isInMultiWindowMode else false + result.success(enabled) + } + + override fun isInPictureInPictureMode(call: MethodCall, result: MethodChannel.Result) { + val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) activity.isInPictureInPictureMode else false + result.success(enabled) + } + + // display orientation in degrees + override fun getOrientation(call: MethodCall, result: MethodChannel.Result) { + val displayRotation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + activity.display.rotation + } else { + val windowService = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager + @Suppress("deprecation") + windowService.defaultDisplay.rotation + } + result.success(displayRotation * 90) + } + + override fun requestOrientation(call: MethodCall, result: MethodChannel.Result) { + val orientation = call.argument<Int>("orientation") + if (orientation == null) { + result.error("requestOrientation-args", "missing arguments", null) + return + } + activity.requestedOrientation = orientation + result.success(true) + } + + override fun isCutoutAware(call: MethodCall, result: MethodChannel.Result) { + result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) + } + + override fun getCutoutInsets(call: MethodCall, result: MethodChannel.Result) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + result.error("getCutoutInsets-sdk", "unsupported SDK version=${Build.VERSION.SDK_INT}", null) + return + } + + val cutout = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + activity.getDisplayCompat()?.cutout + } else { + activity.window.decorView.rootWindowInsets.displayCutout + } + + val density = activity.devicePixelRatio() + result.success( + hashMapOf( + "left" to (cutout?.safeInsetLeft ?: 0) / density, + "top" to (cutout?.safeInsetTop ?: 0) / density, + "right" to (cutout?.safeInsetRight ?: 0) / density, + "bottom" to (cutout?.safeInsetBottom ?: 0) / density, + ) + ) + } + + override fun supportsWideGamut(call: MethodCall, result: MethodChannel.Result) { + result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && activity.resources.configuration.isScreenWideColorGamut) + } + + override fun supportsHdr(call: MethodCall, result: MethodChannel.Result) { + result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && activity.resources.configuration.isScreenHdr) + } + + override fun setColorMode(call: MethodCall, result: MethodChannel.Result) { + val wideColorGamut = call.argument<Boolean>("wideColorGamut") + val hdr = call.argument<Boolean>("hdr") + if (wideColorGamut == null || hdr == null) { + result.error("setColorMode-args", "missing arguments", null) + return + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + activity.window.colorMode = if (hdr) { + ActivityInfo.COLOR_MODE_HDR + } else if (wideColorGamut) { + ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT + } else { + ActivityInfo.COLOR_MODE_DEFAULT + } + } + result.success(null) + } + + override fun startGlobalDrag(call: MethodCall, result: MethodChannel.Result) { + val uri = call.argument<String>("uri")?.toUri() + val label = call.argument<String>("label") + val shadowWidthDip = call.argument<Number>("shadowWidthDip")?.toFloat() + val shadowHeightDip = call.argument<Number>("shadowHeightDip")?.toFloat() + val shadowBytes = call.argument<ByteArray>("shadowBytes") + + if (uri == null || shadowWidthDip == null || shadowHeightDip == null || shadowBytes == null) { + result.error("startGlobalDrag-args", "missing arguments", null) + return + } + + val clip = ClipData.newUri(activity.contentResolver, label, getShareableUri(activity, uri)) + + val density = activity.devicePixelRatio() + val widthPx = (shadowWidthDip * density).roundToInt() + val heightPx = (shadowHeightDip * density).roundToInt() + + val shadowBuilder: View.DragShadowBuilder = try { + val bitmap = createBitmap(widthPx, heightPx, Bitmap.Config.ARGB_8888).also { + it.copyPixelsFromBuffer(ByteBuffer.wrap(shadowBytes)) + } + + val scaleToFit = Matrix() + val src = RectF(0f, 0f, bitmap.getWidth().toFloat(), bitmap.getHeight().toFloat()) + val dst = RectF(0f, 0f, heightPx.toFloat(), heightPx.toFloat()) + scaleToFit.setRectToRect(src, dst, ScaleToFit.CENTER) + + object : View.DragShadowBuilder() { + override fun onProvideShadowMetrics(outShadowSize: Point, outShadowTouchPoint: Point) { + outShadowSize.set(widthPx, heightPx) + outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2) + } + + override fun onDrawShadow(canvas: Canvas) { + canvas.drawBitmap(bitmap, scaleToFit, null) + } + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to draw widget", e) + View.DragShadowBuilder() + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + activity.window.decorView.startDragAndDrop( + clip, + shadowBuilder, + null, + View.DRAG_FLAG_GLOBAL or View.DRAG_FLAG_GLOBAL_URI_READ + ) + } + } + + companion object { + private val LOG_TAG = LogUtils.createTag<ActivityWindowHandler>() + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ServiceWindowHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ServiceWindowHandler.kt new file mode 100644 index 0000000..a82bb41 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ServiceWindowHandler.kt @@ -0,0 +1,59 @@ +package deckers.thibault.aves.channel.calls.window + +import android.app.Service +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +class ServiceWindowHandler(service: Service) : WindowHandler(service) { + override fun isActivity(call: MethodCall, result: MethodChannel.Result) { + result.success(false) + } + + override fun keepScreenOn(call: MethodCall, result: MethodChannel.Result) { + result.success(null) + } + + override fun secureScreen(call: MethodCall, result: MethodChannel.Result) { + result.success(null) + } + + override fun isInMultiWindowMode(call: MethodCall, result: MethodChannel.Result) { + result.success(false) + } + + override fun isInPictureInPictureMode(call: MethodCall, result: MethodChannel.Result) { + result.success(false) + } + + override fun getOrientation(call: MethodCall, result: MethodChannel.Result) { + result.success(0) + } + + override fun requestOrientation(call: MethodCall, result: MethodChannel.Result) { + result.success(false) + } + + override fun isCutoutAware(call: MethodCall, result: MethodChannel.Result) { + result.success(false) + } + + override fun getCutoutInsets(call: MethodCall, result: MethodChannel.Result) { + result.success(HashMap<String, Any>()) + } + + override fun supportsWideGamut(call: MethodCall, result: MethodChannel.Result) { + result.success(false) + } + + override fun supportsHdr(call: MethodCall, result: MethodChannel.Result) { + result.success(false) + } + + override fun setColorMode(call: MethodCall, result: MethodChannel.Result) { + result.success(null) + } + + override fun startGlobalDrag(call: MethodCall, result: MethodChannel.Result) { + result.success(null) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/WindowHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/WindowHandler.kt new file mode 100644 index 0000000..9b7bba8 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/WindowHandler.kt @@ -0,0 +1,72 @@ +package deckers.thibault.aves.channel.calls.window + +import android.content.ContextWrapper +import android.provider.Settings +import android.util.Log +import deckers.thibault.aves.channel.calls.Coresult +import deckers.thibault.aves.utils.LogUtils +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +abstract class WindowHandler(private val contextWrapper: ContextWrapper) : MethodChannel.MethodCallHandler { + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "isActivity" -> Coresult.safe(call, result, ::isActivity) + "keepScreenOn" -> Coresult.safe(call, result, ::keepScreenOn) + "secureScreen" -> Coresult.safe(call, result, ::secureScreen) + "isInMultiWindowMode" -> Coresult.safe(call, result, ::isInMultiWindowMode) + "isInPictureInPictureMode" -> Coresult.safe(call, result, ::isInPictureInPictureMode) + "isRotationLocked" -> Coresult.safe(call, result, ::isRotationLocked) + "getOrientation" -> Coresult.safe(call, result, ::getOrientation) + "requestOrientation" -> Coresult.safe(call, result, ::requestOrientation) + "isCutoutAware" -> Coresult.safe(call, result, ::isCutoutAware) + "getCutoutInsets" -> Coresult.safe(call, result, ::getCutoutInsets) + "supportsWideGamut" -> Coresult.safe(call, result, ::supportsWideGamut) + "supportsHdr" -> Coresult.safe(call, result, ::supportsHdr) + "setColorMode" -> Coresult.safe(call, result, ::setColorMode) + "startGlobalDrag" -> Coresult.safe(call, result, ::startGlobalDrag) + else -> result.notImplemented() + } + } + + abstract fun isActivity(call: MethodCall, result: MethodChannel.Result) + + abstract fun keepScreenOn(call: MethodCall, result: MethodChannel.Result) + + abstract fun secureScreen(call: MethodCall, result: MethodChannel.Result) + + abstract fun isInMultiWindowMode(call: MethodCall, result: MethodChannel.Result) + + abstract fun isInPictureInPictureMode(call: MethodCall, result: MethodChannel.Result) + + private fun isRotationLocked(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) { + var locked = false + try { + locked = Settings.System.getInt(contextWrapper.contentResolver, Settings.System.ACCELEROMETER_ROTATION) == 0 + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get settings with error=${e.message}", null) + } + result.success(locked) + } + + abstract fun getOrientation(call: MethodCall, result: MethodChannel.Result) + + abstract fun requestOrientation(call: MethodCall, result: MethodChannel.Result) + + abstract fun isCutoutAware(call: MethodCall, result: MethodChannel.Result) + + abstract fun getCutoutInsets(call: MethodCall, result: MethodChannel.Result) + + abstract fun supportsWideGamut(call: MethodCall, result: MethodChannel.Result) + + abstract fun supportsHdr(call: MethodCall, result: MethodChannel.Result) + + abstract fun setColorMode(call: MethodCall, result: MethodChannel.Result) + + abstract fun startGlobalDrag(call: MethodCall, result: MethodChannel.Result) + + companion object { + private val LOG_TAG = LogUtils.createTag<WindowHandler>() + const val CHANNEL = "deckers.thibault/aves/window" + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/BaseStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/BaseStreamHandler.kt new file mode 100644 index 0000000..7735b6d --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/BaseStreamHandler.kt @@ -0,0 +1,108 @@ +package deckers.thibault.aves.channel.streams + +import android.os.Handler +import android.os.Looper +import android.util.Log +import deckers.thibault.aves.utils.MemoryUtils +import io.flutter.plugin.common.EventChannel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import java.io.InputStream + +abstract class BaseStreamHandler : EventChannel.StreamHandler { + val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + // cannot use `lateinit` because we cannot guarantee + // its initialization in `onListen` at the right time + // e.g. when resuming the app after the activity got destroyed + private var eventSink: EventChannel.EventSink? = null + private var handler: Handler? = null + + override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink) { + this.eventSink = eventSink + handler = Handler(Looper.getMainLooper()) + onCall(arguments) + } + + override fun onCancel(arguments: Any?) { + // nothing + } + + open fun success(event: Any?) { + handler?.post { + try { + eventSink?.success(event) + } catch (e: Exception) { + Log.w(logTag, "failed to use event sink", e) + } + } + } + + open fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) { + handler?.post { + try { + eventSink?.error(errorCode, errorMessage, errorDetails) + } catch (e: Exception) { + Log.w(logTag, "failed to use event sink", e) + } + } + } + + open fun endOfStream() { + handler?.post { + try { + eventSink?.endOfStream() + } catch (e: Exception) { + Log.w(logTag, "failed to use event sink", e) + } + } + } + + fun streamBytes(inputStream: InputStream): Boolean { + val buffer = ByteArray(BUFFER_SIZE) + var len: Int + while (inputStream.read(buffer).also { len = it } != -1) { + // cannot decode image on Flutter side when using `buffer` directly + if (MemoryUtils.canAllocate(len)) { + success(buffer.copyOf(len)) + } else { + error("streamBytes-memory", "not enough memory to allocate $len bytes", null) + return false + } + } + return true + } + + fun safe(function: () -> Unit, closeStream: Boolean = true) { + try { + function() + } catch (e: Exception) { + error("safe-exception", e.message, e.stackTraceToString()) + } + if (closeStream) { + endOfStream() + } + } + + suspend fun safeSuspend(function: suspend () -> Unit, closeStream: Boolean = true) { + try { + function() + } catch (e: Exception) { + error("safeSuspend-exception", e.message, e.stackTraceToString()) + } + if (closeStream) { + endOfStream() + } + } + + abstract val logTag: String + + open fun onCall(args: Any?) { + // nothing by default + } + + companion object { + const val BUFFER_SIZE = 1 shl 18 // 256kB + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ActivityResultStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ActivityResultStreamHandler.kt new file mode 100644 index 0000000..39d4d53 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ActivityResultStreamHandler.kt @@ -0,0 +1,278 @@ +package deckers.thibault.aves.channel.streams.darttoplatform + +import android.app.Activity +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.util.Log +import androidx.core.net.toUri +import deckers.thibault.aves.MainActivity +import deckers.thibault.aves.PendingStorageAccessResultHandler +import deckers.thibault.aves.channel.calls.AppAdapterHandler +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.PermissionManager +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.StorageUtils.ensureTrailingSeparator +import kotlinx.coroutines.launch + +// starting activity to get a result (e.g. storage access via native dialog) +// breaks the regular `MethodChannel` so we use a stream channel instead +class ActivityResultStreamHandler(private val activity: Activity, arguments: Any?) : BaseStreamHandler() { + private var op: String? = null + private lateinit var args: Map<*, *> + + init { + if (arguments is Map<*, *>) { + op = arguments["op"] as String? + args = arguments + } + } + + override val logTag = LOG_TAG + + override fun onCall(args: Any?) { + // do not automatically close stream when launching activity, + // as it will be closed when getting that activity result + val closeStream = false + when (op) { + "requestDirectoryAccess" -> ioScope.launch { safe(::requestDirectoryAccess, closeStream) } + "requestMediaFileAccess" -> ioScope.launch { safe(::requestMediaFileAccess, closeStream) } + "createFile" -> ioScope.launch { safe(::createFile, closeStream) } + "openFile" -> ioScope.launch { safe(::openFile, closeStream) } + "copyFile" -> ioScope.launch { safe(::copyFile, closeStream) } + "edit" -> safe(::edit, closeStream) + "pickCollectionFilters" -> safe(::pickCollectionFilters, closeStream) + else -> endOfStream() + } + } + + override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) { + super.error(errorCode, errorMessage, errorDetails) + endOfStream() + } + + private fun requestDirectoryAccess() { + val path = args["path"] as String? + if (path == null) { + error("requestDirectoryAccess-args", "missing arguments", null) + return + } + + PermissionManager.requestDirectoryAccess(activity, ensureTrailingSeparator(path), { + success(true) + endOfStream() + }, { + success(false) + endOfStream() + }) + } + + private fun requestMediaFileAccess() { + val uris = (args["uris"] as List<*>?)?.mapNotNull { if (it is String) it.toUri() else null } + val mimeTypes = (args["mimeTypes"] as List<*>?)?.mapNotNull { it as? String } + if (uris.isNullOrEmpty() || mimeTypes == null || mimeTypes.size != uris.size) { + error("requestMediaFileAccess-args", "missing arguments", null) + return + } + + if (uris.any { !StorageUtils.isMediaStoreContentUri(it) }) { + error("requestMediaFileAccess-nonmediastore", "request is only valid for Media Store content URIs, uris=$uris", null) + return + } + + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + error("requestMediaFileAccess-unsupported", "media file bulk access is not allowed before Android 11", null) + return + } + + try { + val granted = PermissionManager.requestMediaFileAccess(activity, uris, mimeTypes) + success(granted) + endOfStream() + } catch (e: Exception) { + error("requestMediaFileAccess-request", "failed to request access to ${uris.size} uris=$uris", e.message) + } + } + + private fun safeStartActivityForStorageAccessResult(intent: Intent, requestCode: Int, onGranted: (uri: Uri) -> Unit, onDenied: () -> Unit) { + if (intent.resolveActivity(activity.packageManager) != null) { + MainActivity.pendingStorageAccessResultHandlers[requestCode] = PendingStorageAccessResultHandler(null, onGranted, onDenied) + if (!safeStartActivityForResult(intent, requestCode)) { + MainActivity.notifyError("failed to start activity for intent=$intent extras=${intent.extras}") + onDenied() + } + } else { + MainActivity.notifyError("failed to resolve activity for intent=$intent extras=${intent.extras}") + onDenied() + } + } + + private fun createFile() { + val name = args["name"] as String? + val mimeType = args["mimeType"] as String? + val bytes = args["bytes"] as ByteArray? + if (name == null || mimeType == null || bytes == null) { + error("createFile-args", "missing arguments", null) + return + } + + fun onGranted(uri: Uri) { + ioScope.launch { + try { + // truncate is necessary when overwriting a longer file + activity.contentResolver.openOutputStream(uri, "wt")?.use { output -> + output.write(bytes) + } + success(true) + endOfStream() + } catch (e: Exception) { + error("createFile-write", "failed to write file at uri=$uri", e.message) + } + } + } + + fun onDenied() { + success(null) + endOfStream() + } + + val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = mimeType + putExtra(Intent.EXTRA_TITLE, name) + } + safeStartActivityForStorageAccessResult(intent, MainActivity.CREATE_FILE_REQUEST, ::onGranted, ::onDenied) + } + + private fun openFile() { + val mimeType = args["mimeType"] as String? // optional + + fun onGranted(uri: Uri) { + ioScope.launch { + try { + activity.contentResolver.openInputStream(uri)?.use(::streamBytes) + endOfStream() + } catch (e: Exception) { + error("openFile-read", "failed to read file at uri=$uri", e.message) + } + } + } + + fun onDenied() { + success(ByteArray(0)) + endOfStream() + } + + val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + setTypeAndNormalize(mimeType ?: MimeTypes.ANY) + } + safeStartActivityForStorageAccessResult(intent, MainActivity.OPEN_FILE_REQUEST, ::onGranted, ::onDenied) + } + + private fun copyFile() { + val name = args["name"] as String? + val mimeType = args["mimeType"] as String? + val sourceUri = (args["sourceUri"] as String?)?.toUri() + if (name == null || mimeType == null || sourceUri == null) { + error("copyFile-args", "missing arguments", null) + return + } + + fun onGranted(uri: Uri) { + ioScope.launch { + try { + StorageUtils.openInputStream(activity, sourceUri)?.use { input -> + // truncate is necessary when overwriting a longer file + activity.contentResolver.openOutputStream(uri, "wt")?.use { output -> + val buffer = ByteArray(BUFFER_SIZE) + var len: Int + while (input.read(buffer).also { len = it } != -1) { + output.write(buffer, 0, len) + } + } + } + success(true) + endOfStream() + } catch (e: Exception) { + error("copyFile-write", "failed to copy file from sourceUri=$sourceUri to uri=$uri", e.message) + } + } + } + + fun onDenied() { + success(null) + endOfStream() + } + + val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = mimeType + putExtra(Intent.EXTRA_TITLE, name) + } + safeStartActivityForStorageAccessResult(intent, MainActivity.CREATE_FILE_REQUEST, ::onGranted, ::onDenied) + } + + private fun edit() { + val uri = args["uri"] as String? + val mimeType = args["mimeType"] as String? // optional + if (uri == null) { + error("edit-args", "missing arguments", null) + return + } + + val intent = Intent(Intent.ACTION_EDIT) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + .setDataAndType(AppAdapterHandler.getShareableUri(activity, uri.toUri()), mimeType) + + if (intent.resolveActivity(activity.packageManager) == null) { + error("edit-resolve", "cannot resolve activity for this intent for uri=$uri mimeType=$mimeType", null) + return + } + + MainActivity.pendingEditIntentHandler = { fields -> + success(fields) + endOfStream() + } + if (!safeStartActivityForResult(intent, MainActivity.EDIT_REQUEST)) { + error("edit-start", "cannot start activity for this intent for uri=$uri mimeType=$mimeType", null) + } + } + + private fun pickCollectionFilters() { + val initialFilters = (args["initialFilters"] as? List<*>)?.mapNotNull { it as? String } ?: listOf() + val intent = Intent(MainActivity.INTENT_ACTION_PICK_COLLECTION_FILTERS, null, activity, MainActivity::class.java) + .putExtra(MainActivity.EXTRA_KEY_FILTERS_ARRAY, initialFilters.toTypedArray()) + .putExtra(MainActivity.EXTRA_KEY_FILTERS_STRING, initialFilters.joinToString(MainActivity.EXTRA_STRING_ARRAY_SEPARATOR)) + MainActivity.pendingCollectionFilterPickHandler = { filters -> + success(filters) + endOfStream() + } + activity.startActivityForResult(intent, MainActivity.PICK_COLLECTION_FILTERS_REQUEST) + } + + private fun safeStartActivityForResult(intent: Intent, requestCode: Int): Boolean { + return try { + activity.startActivityForResult(intent, requestCode) + true + } catch (_: SecurityException) { + if (intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0) { + // in some environments, providing the write flag yields a `SecurityException`: + // "UID XXXX does not have permission to content://XXXX" + // so we retry without it + Log.i(LOG_TAG, "retry intent=$intent without FLAG_GRANT_WRITE_URI_PERMISSION") + intent.flags = intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION.inv() + safeStartActivityForResult(intent, requestCode) + } else { + false + } + } + } + + companion object { + private val LOG_TAG = LogUtils.createTag<ActivityResultStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/activity_result_stream" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageByteStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageByteStreamHandler.kt new file mode 100644 index 0000000..8633f0c --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageByteStreamHandler.kt @@ -0,0 +1,277 @@ +package deckers.thibault.aves.channel.streams.darttoplatform + +import android.content.Context +import android.graphics.Rect +import android.net.Uri +import androidx.core.net.toUri +import com.bumptech.glide.Glide +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.decoding.RegionFetcher +import deckers.thibault.aves.decoding.SvgRegionFetcher +import deckers.thibault.aves.decoding.ThumbnailFetcher +import deckers.thibault.aves.decoding.TiffRegionFetcher +import deckers.thibault.aves.glide.AvesAppGlideModule +import deckers.thibault.aves.model.EntryFields +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.BitmapUtils.applyExifOrientation +import deckers.thibault.aves.utils.ContextUtils.devicePixelRatio +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.handleEncodedBytesInFlutter +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.MimeTypes.needRotationAfterGlide +import deckers.thibault.aves.utils.StorageUtils +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.ByteArrayInputStream +import java.io.InputStream +import java.util.Date +import kotlin.math.roundToInt + +class ImageByteStreamHandler(private val context: Context, private val arguments: Any?) : BaseStreamHandler(), ByteSink { + private var op: String? = null + private var decoded: Boolean = false + private val regionFetcher = RegionFetcher(context) + private val density = context.devicePixelRatio() + + init { + if (arguments is Map<*, *>) { + op = arguments["op"] as String? + decoded = arguments["decoded"] as Boolean + } + } + + override val logTag = LOG_TAG + + override fun onCall(args: Any?) { + when (op) { + "getFullImage" -> ioScope.launch { safeSuspend(::streamFullImage) } + "getRegion" -> ioScope.launch { safeSuspend(::streamRegion) } + "getThumbnail" -> ioScope.launch { safeSuspend(::streamThumbnail) } + else -> endOfStream() + } + } + + // Supported image formats: + // - Flutter (as of v1.20): JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP, and WBMP + // - Android: https://developer.android.com/guide/topics/media/media-formats#image-formats + // - Glide: https://github.com/bumptech/glide/blob/master/library/src/main/java/com/bumptech/glide/load/ImageHeaderParser.java + private suspend fun streamFullImage() { + if (arguments !is Map<*, *>) { + return + } + + val uri = (arguments["uri"] as String?)?.toUri() + val pageId = arguments["pageId"] as Int? + val mimeType = arguments["mimeType"] as String? + val sizeBytes = (arguments["sizeBytes"] as Number?)?.toLong() + val rotationDegrees = arguments["rotationDegrees"] as Int + val isFlipped = arguments["isFlipped"] as Boolean + + if (mimeType == null || uri == null) { + error("streamImage-args", "missing arguments", null) + return + } + + if (!decoded && handleEncodedBytesInFlutter(mimeType)) { + // the image can be decoded by Flutter codecs, + // and there is no need for processing on the platform side + // so we stream it without decoding it + streamOriginalBytesWithTrailer(uri, mimeType) + } else if (isVideo(mimeType)) { + streamVideoByGlide( + uri = uri, + mimeType = mimeType, + sizeBytes = sizeBytes, + decoded = decoded, + ) + } else { + // even if the image could be decoded by Flutter codecs, + // it needs to be processed on the platform side + // so we decode, process, optionally reencode, then stream it + streamImageByGlide( + uri = uri, + pageId = pageId, + mimeType = mimeType, + sizeBytes = sizeBytes, + rotationDegrees = rotationDegrees, + isFlipped = isFlipped, + decoded = decoded, + ) + } + } + + private fun streamOriginalBytesWithTrailer(uri: Uri, mimeType: String) { + try { + val sent = StorageUtils.openInputStream(context, uri)?.use(::streamBytes) + if (sent ?: false) { + success(BitmapUtils.FORMAT_BYTE_ENCODED_AS_BYTES) + } + } catch (e: Exception) { + error("streamImage-image-read-exception", "failed to get image for mimeType=$mimeType uri=$uri", e.stackTraceToString()) + } + } + + private suspend fun streamImageByGlide( + uri: Uri, + pageId: Int?, + mimeType: String, + sizeBytes: Long?, + rotationDegrees: Int, + isFlipped: Boolean, + decoded: Boolean, + ) { + val target = Glide.with(context) + .asBitmap() + .apply(AvesAppGlideModule.uncachedFullImageOptions) + .load(AvesAppGlideModule.getModel(context, uri, mimeType, pageId, sizeBytes)) + .submit() + try { + var bitmap = withContext(Dispatchers.IO) { target.get() } + if (needRotationAfterGlide(mimeType, pageId)) { + bitmap = applyExifOrientation(context, bitmap, rotationDegrees, isFlipped) + } + if (bitmap != null) { + // do not recycle bitmaps fetched from Glide as their lifecycle is unknown + val bytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = decoded, mimeType) + streamBytes(ByteArrayInputStream(bytes)) + } else { + error("streamImage-image-decode-null", "failed to get image for mimeType=$mimeType uri=$uri", null) + } + } catch (e: Exception) { + error("streamImage-image-decode-exception", "failed to get image for mimeType=$mimeType uri=$uri", e.stackTraceToString()) + } finally { + Glide.with(context).clear(target) + } + } + + private suspend fun streamVideoByGlide(uri: Uri, mimeType: String, sizeBytes: Long?, decoded: Boolean) { + val target = Glide.with(context) + .asBitmap() + .apply(AvesAppGlideModule.uncachedFullImageOptions) + .load(AvesAppGlideModule.getModel(context, uri, mimeType, null, sizeBytes)) + .submit() + try { + val bitmap = withContext(Dispatchers.IO) { target.get() } + if (bitmap != null) { + // do not recycle bitmaps fetched from Glide as their lifecycle is unknown + val bytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = decoded, mimeType) + streamBytes(ByteArrayInputStream(bytes)) + } else { + error("streamImage-video-null", "failed to get image for mimeType=$mimeType uri=$uri", null) + } + } catch (e: Exception) { + error("streamImage-video-exception", "failed to get image for mimeType=$mimeType uri=$uri", e.stackTraceToString()) + } finally { + Glide.with(context).clear(target) + } + } + + private suspend fun streamRegion() { + if (arguments !is Map<*, *>) { + return + } + + val uri = (arguments["uri"] as String?)?.toUri() + val pageId = arguments["pageId"] as Int? + val mimeType = arguments["mimeType"] as String? + val sizeBytes = (arguments["sizeBytes"] as Number?)?.toLong() + val sampleSize = arguments["sampleSize"] as Int? + val x = arguments["regionX"] as Int? + val y = arguments["regionY"] as Int? + val width = arguments["regionWidth"] as Int? + val height = arguments["regionHeight"] as Int? + val imageWidth = arguments["imageWidth"] as Int? + val imageHeight = arguments["imageHeight"] as Int? + + if (uri == null || mimeType == null || sampleSize == null || x == null || y == null || width == null || height == null || imageWidth == null || imageHeight == null) { + error("getRegion-args", "missing arguments", null) + return + } + + val regionRect = Rect(x, y, x + width, y + height) + when (mimeType) { + MimeTypes.SVG -> SvgRegionFetcher(context).fetch( + uri = uri, + decoded = decoded, + sizeBytes = sizeBytes, + scale = sampleSize, + regionRect = regionRect, + imageWidth = imageWidth, + imageHeight = imageHeight, + result = this, + ) + + MimeTypes.TIFF -> TiffRegionFetcher(context).fetch( + uri = uri, + page = pageId ?: 0, + decoded = decoded, + sampleSize = sampleSize, + regionRect = regionRect, + result = this, + ) + + else -> regionFetcher.fetch( + uri = uri, + pageId = pageId, + decoded = decoded, + mimeType = mimeType, + sampleSize = sampleSize, + regionRect = regionRect, + imageWidth = imageWidth, + imageHeight = imageHeight, + result = this, + ) + } + } + + private suspend fun streamThumbnail() { + if (arguments !is Map<*, *>) { + return + } + + val uri = arguments[EntryFields.URI] as String? + val pageId = arguments["pageId"] as Int? + val mimeType = arguments[EntryFields.MIME_TYPE] as String? + val dateModifiedMillis = (arguments[EntryFields.DATE_MODIFIED_MILLIS] as Number?)?.toLong() + val rotationDegrees = arguments[EntryFields.ROTATION_DEGREES] as Int? + val isFlipped = arguments[EntryFields.IS_FLIPPED] as Boolean? + val widthDip = (arguments["widthDip"] as Number?)?.toDouble() + val heightDip = (arguments["heightDip"] as Number?)?.toDouble() + val defaultSizeDip = (arguments["defaultSizeDip"] as Number?)?.toDouble() + val quality = arguments["quality"] as Int? + + if (uri == null || mimeType == null || rotationDegrees == null || isFlipped == null || widthDip == null || heightDip == null || defaultSizeDip == null || quality == null) { + error("getThumbnail-args", "missing arguments", null) + return + } + + // convert DIP to physical pixels here, instead of using `devicePixelRatio` in Flutter + ThumbnailFetcher( + context = context, + uri = uri, + pageId = pageId, + decoded = decoded, + mimeType = mimeType, + dateModifiedMillis = dateModifiedMillis ?: (Date().time), + rotationDegrees = rotationDegrees, + isFlipped = isFlipped, + width = (widthDip * density).roundToInt(), + height = (heightDip * density).roundToInt(), + defaultSize = (defaultSizeDip * density).roundToInt(), + quality = quality, + result = this, + ).fetch() + } + + companion object { + private val LOG_TAG = LogUtils.createTag<ImageByteStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/media_byte_stream" + } +} + +interface ByteSink { + fun streamBytes(inputStream: InputStream): Boolean + fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageOpStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageOpStreamHandler.kt new file mode 100644 index 0000000..a8b3543 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageOpStreamHandler.kt @@ -0,0 +1,221 @@ +package deckers.thibault.aves.channel.streams.darttoplatform + +import android.app.Activity +import android.util.Log +import androidx.core.net.toUri +import deckers.thibault.aves.channel.calls.MediaEditHandler.Companion.cancelledOps +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.model.AvesEntry +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.NameConflictStrategy +import deckers.thibault.aves.model.provider.ImageProvider.ImageOpCallback +import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider +import deckers.thibault.aves.model.provider.MediaStoreImageProvider +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.StorageUtils.ensureTrailingSeparator +import kotlinx.coroutines.launch + +class ImageOpStreamHandler(private val activity: Activity, private val arguments: Any?) : BaseStreamHandler() { + private var op: String? = null + private var opId: String? = null + private val entryMapList = ArrayList<FieldMap>() + + init { + if (arguments is Map<*, *>) { + op = arguments["op"] as String? + opId = arguments["id"] as String? + @Suppress("unchecked_cast") + val rawEntries = arguments["entries"] as List<FieldMap>? + if (rawEntries != null) { + entryMapList.addAll(rawEntries) + } + } + } + + override val logTag = LOG_TAG + + override fun onCall(args: Any?) { + when (op) { + "delete" -> ioScope.launch { safe(::delete) } + "convert" -> ioScope.launch { safeSuspend(::convert) } + "move" -> ioScope.launch { safeSuspend(::move) } + "rename" -> ioScope.launch { safeSuspend(::rename) } + else -> endOfStream() + } + } + + override fun endOfStream() { + cancelledOps.remove(opId) + super.endOfStream() + } + + private fun isCancelledOp() = cancelledOps.contains(opId) + + private fun delete() { + val entries = entryMapList.map(::AvesEntry) + for (entry in entries) { + val mimeType = entry.mimeType + val trashed = entry.trashed + + val uri = entry.uri + val path = if (trashed) entry.trashPath else entry.path + + val result: FieldMap = hashMapOf( + "uri" to uri.toString(), + ) + if (isCancelledOp()) { + result["skipped"] = true + } else { + result["success"] = false + getProvider(activity, uri)?.let { provider -> + try { + provider.delete(activity, uri, path, mimeType) + result["success"] = true + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to delete entry with path=$path", e) + } + } + } + success(result) + } + endOfStream() + } + + private suspend fun convert() { + if (arguments !is Map<*, *> || entryMapList.isEmpty()) { + endOfStream() + return + } + + var destinationDir = arguments["destinationPath"] as String? + val mimeType = arguments["mimeType"] as String? + val quality = (arguments["quality"] as Number?)?.toInt() + val lengthUnit = arguments["lengthUnit"] as String? + val width = (arguments["width"] as Number?)?.toInt() + val height = (arguments["height"] as Number?)?.toInt() + val writeMetadata = arguments["writeMetadata"] as Boolean? + val nameConflictStrategy = NameConflictStrategy.get(arguments["nameConflictStrategy"] as String?) + if (destinationDir == null || mimeType == null || quality == null || lengthUnit == null || width == null || height == null || writeMetadata == null || nameConflictStrategy == null) { + error("convert-args", "missing arguments", null) + return + } + + // assume same provider for all entries + val firstEntry = entryMapList.first() + val provider = (firstEntry["uri"] as String?)?.toUri()?.let { getProvider(activity, it) } + if (provider == null) { + error("convert-provider", "failed to find provider for entry=$firstEntry", null) + return + } + + destinationDir = ensureTrailingSeparator(destinationDir) + val entries = entryMapList.map(::AvesEntry) + provider.convertMultiple( + activity = activity, + imageExportMimeType = mimeType, + targetDir = destinationDir, + entries = entries, + quality = quality, + lengthUnit = lengthUnit, + width = width, + height = height, + writeMetadata = writeMetadata, + nameConflictStrategy = nameConflictStrategy, + callback = object : ImageOpCallback { + override fun onSuccess(fields: FieldMap) = success(fields) + override fun onFailure(throwable: Throwable) = error("convert-failure", "failed to convert entries", throwable) + }, + ) + endOfStream() + } + + private suspend fun move() { + if (arguments !is Map<*, *>) { + endOfStream() + return + } + + val copy = arguments["copy"] as Boolean? + val nameConflictStrategy = NameConflictStrategy.get(arguments["nameConflictStrategy"] as String?) + val rawEntryMap = arguments["entriesByDestination"] as Map<*, *>? + if (copy == null || nameConflictStrategy == null || rawEntryMap == null || rawEntryMap.isEmpty()) { + error("move-args", "missing arguments", null) + return + } + + val entriesByTargetDir = HashMap<String, List<AvesEntry>>() + rawEntryMap.forEach { + var destinationDir = it.key as String + if (destinationDir != StorageUtils.TRASH_PATH_PLACEHOLDER) { + destinationDir = ensureTrailingSeparator(destinationDir) + } + @Suppress("unchecked_cast") + val rawEntries = it.value as List<FieldMap> + entriesByTargetDir[destinationDir] = rawEntries.map(::AvesEntry) + } + + // always use Media Store (as we move from or to it) + val provider = MediaStoreImageProvider() + + provider.moveMultiple( + activity = activity, + copy = copy, + nameConflictStrategy = nameConflictStrategy, + entriesByTargetDir = entriesByTargetDir, + isCancelledOp = ::isCancelledOp, + callback = object : ImageOpCallback { + override fun onSuccess(fields: FieldMap) = success(fields) + override fun onFailure(throwable: Throwable) = error("move-failure", "failed to move entries", throwable) + }, + ) + endOfStream() + } + + private suspend fun rename() { + if (arguments !is Map<*, *>) { + endOfStream() + return + } + + val rawEntryMap = arguments["entriesToNewName"] as Map<*, *>? + if (rawEntryMap == null || rawEntryMap.isEmpty()) { + error("rename-args", "missing arguments", null) + return + } + + val entriesToNewName = HashMap<AvesEntry, String>() + rawEntryMap.forEach { + @Suppress("unchecked_cast") + val rawEntry = it.key as FieldMap + val newName = it.value as String + entriesToNewName[AvesEntry(rawEntry)] = newName + } + + val byProvider = entriesToNewName.entries.groupBy { kv -> getProvider(activity, kv.key.uri) } + for ((provider, entryList) in byProvider) { + if (provider == null) { + error("rename-provider", "failed to find provider for entry=${entryList.firstOrNull()}", null) + return + } + + val entryMap = mapOf(*entryList.map { Pair(it.key, it.value) }.toTypedArray()) + provider.renameMultiple( + activity = activity, + entriesToNewName = entryMap, + isCancelledOp = ::isCancelledOp, + callback = object : ImageOpCallback { + override fun onSuccess(fields: FieldMap) = success(fields) + override fun onFailure(throwable: Throwable) = error("rename-failure", "failed to rename", throwable.message) + }, + ) + } + + endOfStream() + } + + companion object { + private val LOG_TAG = LogUtils.createTag<ImageOpStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/media_op_stream" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/MediaStoreStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/MediaStoreStreamHandler.kt new file mode 100644 index 0000000..da05c38 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/MediaStoreStreamHandler.kt @@ -0,0 +1,36 @@ +package deckers.thibault.aves.channel.streams.darttoplatform + +import android.content.Context +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.model.provider.MediaStoreImageProvider +import deckers.thibault.aves.utils.LogUtils +import kotlinx.coroutines.launch + +class MediaStoreStreamHandler(private val context: Context, arguments: Any?) : BaseStreamHandler() { + // knownEntries: map of contentId -> dateModifiedMillis + private var knownEntries: Map<Long?, Long?>? = null + private var directory: String? = null + + init { + if (arguments is Map<*, *>) { + knownEntries = (arguments["knownEntries"] as? Map<*, *>?)?.map { (it.key as Number?)?.toLong() to (it.value as Number?)?.toLong() }?.toMap() + directory = arguments["directory"] as String? + } + } + + override val logTag = LOG_TAG + + override fun onCall(args: Any?) { + ioScope.launch { safe(::fetchAll) } + } + + private fun fetchAll() { + MediaStoreImageProvider().fetchAll(context, knownEntries ?: emptyMap(), directory) { success(it) } + endOfStream() + } + + companion object { + private val LOG_TAG = LogUtils.createTag<MediaStoreStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/media_store_stream" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/AnalysisStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/AnalysisStreamHandler.kt new file mode 100644 index 0000000..92271f4 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/AnalysisStreamHandler.kt @@ -0,0 +1,15 @@ +package deckers.thibault.aves.channel.streams.platformtodart + +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.utils.LogUtils + +class AnalysisStreamHandler : BaseStreamHandler() { + fun notifyCompletion() = success(true) + + override val logTag = LOG_TAG + + companion object { + private val LOG_TAG = LogUtils.createTag<AnalysisStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/analysis_events" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/ErrorStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/ErrorStreamHandler.kt new file mode 100644 index 0000000..b71b642 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/ErrorStreamHandler.kt @@ -0,0 +1,15 @@ +package deckers.thibault.aves.channel.streams.platformtodart + +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.utils.LogUtils + +class ErrorStreamHandler : BaseStreamHandler() { + fun notifyError(error: String) = success(error) + + override val logTag = LOG_TAG + + companion object { + private val LOG_TAG = LogUtils.createTag<ErrorStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/error" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/IntentStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/IntentStreamHandler.kt new file mode 100644 index 0000000..badbe20 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/IntentStreamHandler.kt @@ -0,0 +1,15 @@ +package deckers.thibault.aves.channel.streams.platformtodart + +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.utils.LogUtils + +class IntentStreamHandler : BaseStreamHandler() { + fun notifyNewIntent(intentData: MutableMap<String, Any?>?) = success(intentData) + + override val logTag = LOG_TAG + + companion object { + private val LOG_TAG = LogUtils.createTag<IntentStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/new_intent_stream" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaCommandStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaCommandStreamHandler.kt new file mode 100644 index 0000000..d298464 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaCommandStreamHandler.kt @@ -0,0 +1,61 @@ +package deckers.thibault.aves.channel.streams.platformtodart + +import android.support.v4.media.session.MediaSessionCompat +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.utils.LogUtils + +class MediaCommandStreamHandler : BaseStreamHandler() { + val callback = object : MediaSessionCompat.Callback() { + override fun onPlay() { + super.onPlay() + success(hashMapOf(KEY_COMMAND to COMMAND_PLAY)) + } + + override fun onPause() { + super.onPause() + success(hashMapOf(KEY_COMMAND to COMMAND_PAUSE)) + } + + override fun onSkipToNext() { + super.onSkipToNext() + success(hashMapOf(KEY_COMMAND to COMMAND_SKIP_TO_NEXT)) + } + + override fun onSkipToPrevious() { + super.onSkipToPrevious() + success(hashMapOf(KEY_COMMAND to COMMAND_SKIP_TO_PREVIOUS)) + } + + override fun onStop() { + super.onStop() + success(hashMapOf(KEY_COMMAND to COMMAND_STOP)) + } + + override fun onSeekTo(pos: Long) { + super.onSeekTo(pos) + success( + hashMapOf( + KEY_COMMAND to COMMAND_SEEK, + KEY_POSITION to pos, + ) + ) + } + } + + override val logTag = LOG_TAG + + companion object { + private val LOG_TAG = LogUtils.createTag<MediaCommandStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/media_command" + + const val KEY_COMMAND = "command" + const val KEY_POSITION = "position" + + const val COMMAND_PLAY = "play" + const val COMMAND_PAUSE = "pause" + const val COMMAND_SKIP_TO_NEXT = "skip_to_next" + const val COMMAND_SKIP_TO_PREVIOUS = "skip_to_previous" + const val COMMAND_STOP = "stop" + const val COMMAND_SEEK = "seek" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaStoreChangeStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaStoreChangeStreamHandler.kt new file mode 100644 index 0000000..d666603 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaStoreChangeStreamHandler.kt @@ -0,0 +1,49 @@ +package deckers.thibault.aves.channel.streams.platformtodart + +import android.content.Context +import android.database.ContentObserver +import android.net.Uri +import android.provider.MediaStore +import android.util.Log +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.utils.LogUtils + +class MediaStoreChangeStreamHandler(private val context: Context) : BaseStreamHandler() { + private val contentObserver = object : ContentObserver(null) { + override fun onChange(selfChange: Boolean) { + this.onChange(selfChange, null) + } + + override fun onChange(selfChange: Boolean, uri: Uri?) { + // warning: querying the content resolver right after a change + // sometimes yields obsolete results + success(uri?.toString()) + } + } + + init { + Log.i(LOG_TAG, "start listening to Media Store") + try { + context.contentResolver.apply { + registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, contentObserver) + registerContentObserver(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, contentObserver) + } + } catch (e: SecurityException) { + // Trying to register an observer may yield a security exception with this message: + // "Failed to find provider media for user 0; expected to find a valid ContentProvider for this authority" + Log.w(LOG_TAG, "failed to register content observer", e) + } + } + + fun dispose() { + Log.i(LOG_TAG, "stop listening to Media Store") + context.contentResolver.unregisterContentObserver(contentObserver) + } + + override val logTag = LOG_TAG + + companion object { + private val LOG_TAG = LogUtils.createTag<MediaStoreChangeStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/media_store_change" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/SettingsChangeStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/SettingsChangeStreamHandler.kt new file mode 100644 index 0000000..c6f8ab2 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/SettingsChangeStreamHandler.kt @@ -0,0 +1,82 @@ +package deckers.thibault.aves.channel.streams.platformtodart + +import android.content.Context +import android.database.ContentObserver +import android.net.Uri +import android.provider.Settings +import android.util.Log +import android.view.ViewConfiguration +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.utils.LogUtils + +class SettingsChangeStreamHandler(private val context: Context) : BaseStreamHandler() { + private val contentObserver = object : ContentObserver(null) { + private var accelerometerRotation: Int = 0 + private var transitionAnimationScale: Float = 1f + private var longPressTimeoutMillis: Int = 0 + + init { + update() + } + + override fun onChange(selfChange: Boolean) { + this.onChange(selfChange, null) + } + + override fun onChange(selfChange: Boolean, uri: Uri?) { + if (update()) { + success( + hashMapOf( + Settings.System.ACCELEROMETER_ROTATION to accelerometerRotation, + Settings.Global.TRANSITION_ANIMATION_SCALE to transitionAnimationScale, + KEY_LONG_PRESS_TIMEOUT_MILLIS to longPressTimeoutMillis, + ) + ) + } + } + + private fun update(): Boolean { + var changed = false + try { + val newAccelerometerRotation = Settings.System.getInt(context.contentResolver, Settings.System.ACCELEROMETER_ROTATION) + if (accelerometerRotation != newAccelerometerRotation) { + accelerometerRotation = newAccelerometerRotation + changed = true + } + val newTransitionAnimationScale = Settings.Global.getFloat(context.contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE) + if (transitionAnimationScale != newTransitionAnimationScale) { + transitionAnimationScale = newTransitionAnimationScale + changed = true + } + val newLongPressTimeout = ViewConfiguration.getLongPressTimeout() + if (longPressTimeoutMillis != newLongPressTimeout) { + longPressTimeoutMillis = newLongPressTimeout + changed = true + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get settings with error=${e.message}", null) + } + return changed + } + } + + init { + Log.i(LOG_TAG, "start listening to system settings") + context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, contentObserver) + } + + fun dispose() { + Log.i(LOG_TAG, "stop listening to system settings") + context.contentResolver.unregisterContentObserver(contentObserver) + } + + override val logTag = LOG_TAG + + companion object { + private val LOG_TAG = LogUtils.createTag<SettingsChangeStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/settings_change" + + // cf `Settings.Secure.LONG_PRESS_TIMEOUT` + const val KEY_LONG_PRESS_TIMEOUT_MILLIS = "long_press_timeout" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/WindowChangeStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/WindowChangeStreamHandler.kt new file mode 100644 index 0000000..59d62f4 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/WindowChangeStreamHandler.kt @@ -0,0 +1,15 @@ +package deckers.thibault.aves.channel.streams.platformtodart + +import deckers.thibault.aves.channel.streams.BaseStreamHandler +import deckers.thibault.aves.utils.LogUtils + +class WindowChangeStreamHandler : BaseStreamHandler() { + fun notifyWindowModeChange() = success(null) + + override val logTag = LOG_TAG + + companion object { + private val LOG_TAG = LogUtils.createTag<ErrorStreamHandler>() + const val CHANNEL = "deckers.thibault/aves/window_change" + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/decoding/RegionFetcher.kt b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/RegionFetcher.kt new file mode 100644 index 0000000..5efbf5d --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/RegionFetcher.kt @@ -0,0 +1,227 @@ +package deckers.thibault.aves.decoding + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.BitmapRegionDecoder +import android.graphics.ColorSpace +import android.graphics.Rect +import android.net.Uri +import android.os.Build +import android.util.Log +import androidx.core.graphics.createBitmap +import com.bumptech.glide.Glide +import deckers.thibault.aves.channel.streams.darttoplatform.ByteSink +import deckers.thibault.aves.glide.AvesAppGlideModule +import deckers.thibault.aves.glide.MultiPageImage +import deckers.thibault.aves.utils.BitmapRegionDecoderCompat +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.BitmapUtils.describe +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MathUtils +import deckers.thibault.aves.utils.MemoryUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.StorageUtils +import java.io.ByteArrayInputStream +import java.nio.ByteBuffer +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock +import kotlin.math.max +import kotlin.math.roundToInt + +// As of Android 14 (API 34), `BitmapRegionDecoder` documentation states +// that "only the JPEG, PNG, WebP and HEIF formats are supported" +// but in practice it successfully decodes some others. +class RegionFetcher internal constructor( + private val context: Context, +) { + suspend fun fetch( + uri: Uri, + pageId: Int?, + decoded: Boolean, + mimeType: String, + sampleSize: Int, + regionRect: Rect, + imageWidth: Int, + imageHeight: Int, + requestKey: Pair<Uri, Int?> = Pair(uri, pageId), + result: ByteSink, + ) { + if (pageId != null && MultiPageImage.isSupported(mimeType)) { + // use export for requested page + val exportUri = exportUris.getOrPut(requestKey) { createTemporaryExport(uri, mimeType, pageId) } + fetch( + uri = exportUri, + pageId = null, + decoded = decoded, + mimeType = EXPORT_MIME_TYPE, + sampleSize = sampleSize, + regionRect = regionRect, + imageWidth = imageWidth, + imageHeight = imageHeight, + requestKey = requestKey, + result = result, + ) + return + } + + try { + val decoder = getOrCreateDecoder(context, uri, requestKey) + if (decoder == null) { + result.error("fetch-read-null", "failed to open file for mimeType=$mimeType uri=$uri regionRect=$regionRect", null) + return + } + + // with raw images, the known image size may not match the decoded image size + // so we scale the requested region accordingly + var effectiveRect = regionRect + var effectiveSampleSize = sampleSize + + if (imageWidth != decoder.width || imageHeight != decoder.height) { + val xf = decoder.width.toDouble() / imageWidth + val yf = decoder.height.toDouble() / imageHeight + effectiveRect = Rect( + (regionRect.left * xf).roundToInt(), + (regionRect.top * yf).roundToInt(), + (regionRect.right * xf).roundToInt(), + (regionRect.bottom * yf).roundToInt(), + ) + val factor = MathUtils.highestPowerOf2((1 / max(xf, yf)).roundToInt()) + if (factor > 1) { + effectiveSampleSize = max(1, effectiveSampleSize / factor) + } + } + + val options = BitmapFactory.Options().apply { + inSampleSize = effectiveSampleSize + // Specifying preferred config and color space avoids the need for conversion afterwards, + // but may prevent decoding (e.g. from RGBA_1010102 to ARGB_8888 on some devices). + inPreferredConfig = PREFERRED_CONFIG + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB) + } + } + + val pixelCount = effectiveRect.width() * effectiveRect.height() / effectiveSampleSize + val targetBitmapSizeBytes = BitmapUtils.getExpectedImageSize(pixelCount.toLong(), options.inPreferredConfig) + if (!MemoryUtils.canAllocate(targetBitmapSizeBytes)) { + // decoding a region that large would yield an OOM when creating the bitmap + result.error("fetch-large-region", "Region too large for uri=$uri regionRect=$regionRect", null) + return + } + + var bitmap = decoder.decodeRegion(effectiveRect, options) + if (bitmap == null) { + // retry without specifying config or color space, + // falling back to custom byte conversion afterwards + options.inPreferredConfig = null + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && options.inPreferredColorSpace != null) { + options.inPreferredColorSpace = null + } + bitmap = decoder.decodeRegion(effectiveRect, options) + } + + val bytes = BitmapUtils.getBytes(bitmap, recycle = true, decoded = decoded, mimeType) + if (bytes == null) { + result.error("fetch-null", "failed to decode region for uri=$uri regionRect=$regionRect", null) + } else { + result.streamBytes(ByteArrayInputStream(bytes)) + } + } catch (e: Exception) { + if (EXPORT_MIME_TYPE != mimeType) { + // retry with export on failure, + // as some formats are not fully supported by `BitmapRegionDecoder` + val exportUri = exportUris.getOrPut(requestKey) { createTemporaryExport(uri, mimeType, pageId) } + fetch( + uri = exportUri, + pageId = null, + decoded = decoded, + mimeType = EXPORT_MIME_TYPE, + sampleSize = sampleSize, + regionRect = regionRect, + imageWidth = imageWidth, + imageHeight = imageHeight, + requestKey = requestKey, + result = result, + ) + return + } + + result.error("fetch-read-exception", "failed to initialize region decoder for uri=$uri regionRect=$regionRect", e.message) + } + } + + private suspend fun createTemporaryExport(uri: Uri, mimeType: String, pageId: Int?): Uri { + val exportFormat = EXPORT_FORMAT + Log.d(LOG_TAG, "create export for uri=$uri mimeType=$mimeType pageId=$pageId exportFormat=$exportFormat") + val target = Glide.with(context) + .asBitmap() + .apply(AvesAppGlideModule.uncachedFullImageOptions) + .load(AvesAppGlideModule.getModel(context, uri, mimeType, pageId)) + .submit() + + try { + val bitmap = target.get() + val tempFile = StorageUtils.createTempFile(context).apply { + outputStream().use { output -> + val encodedExport = bitmap.compress(exportFormat, 100, output) + if (!encodedExport) { + Log.w(LOG_TAG, "failed export via encoded bytes for uri=$uri mimeType=$mimeType pageId=$pageId exportFormat=$exportFormat, with bitmap=${bitmap.describe()}") + + val decodedBytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = true, mimeType) + if (decodedBytes != null) { + val exportBitmap = createBitmap(bitmap.width, bitmap.height, PREFERRED_CONFIG) + exportBitmap.copyPixelsFromBuffer(ByteBuffer.wrap(decodedBytes)) + val decodedExport = exportBitmap.compress(exportFormat, 100, output) + if (!decodedExport) { + Log.w(LOG_TAG, "failed to compress exportBitmap=${bitmap.describe()}") + } + } + } + } + } + return Uri.fromFile(tempFile) + } finally { + Glide.with(context).clear(target) + } + } + + private data class DecoderRef( + val requestKey: Pair<Uri, Int?>, + val decoder: BitmapRegionDecoder, + ) + + companion object { + private val LOG_TAG = LogUtils.createTag<RegionFetcher>() + private val PREFERRED_CONFIG = Bitmap.Config.ARGB_8888 + private const val DECODER_POOL_SIZE = 3 + private const val EXPORT_MIME_TYPE = MimeTypes.JPEG + private val EXPORT_FORMAT = Bitmap.CompressFormat.JPEG + private val decoderPool = ArrayList<DecoderRef>() + private val exportUris = HashMap<Pair<Uri, Int?>, Uri>() + + private val poolLock = ReentrantLock() + + private fun getOrCreateDecoder(context: Context, uri: Uri, requestKey: Pair<Uri, Int?>): BitmapRegionDecoder? { + poolLock.withLock { + var decoderRef = decoderPool.firstOrNull { it.requestKey == requestKey } + if (decoderRef == null) { + val newDecoder = StorageUtils.openInputStream(context, uri)?.use { input -> + BitmapRegionDecoderCompat.newInstance(input) + } + if (newDecoder == null) { + return null + } + decoderRef = DecoderRef(requestKey, newDecoder) + } else { + decoderPool.remove(decoderRef) + } + decoderPool.add(0, decoderRef) + while (decoderPool.size > DECODER_POOL_SIZE) { + decoderPool.removeAt(decoderPool.size - 1) + } + return decoderRef.decoder + } + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/decoding/SvgRegionFetcher.kt b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/SvgRegionFetcher.kt new file mode 100644 index 0000000..8eadcf5 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/SvgRegionFetcher.kt @@ -0,0 +1,145 @@ +package deckers.thibault.aves.decoding + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Rect +import android.graphics.RectF +import android.net.Uri +import androidx.core.graphics.createBitmap +import com.caverock.androidsvg.PreserveAspectRatio +import com.caverock.androidsvg.RenderOptions +import com.caverock.androidsvg.SVG +import com.caverock.androidsvg.SVGParseException +import com.caverock.androidsvg.utils.SVGAndroidRenderer +import deckers.thibault.aves.channel.streams.darttoplatform.ByteSink +import deckers.thibault.aves.metadata.SVGParserBufferedInputStream +import deckers.thibault.aves.metadata.SvgHelper.IMAGE_BASE64_SIZE_DANGER_THRESHOLD +import deckers.thibault.aves.metadata.SvgHelper.normalizeSize +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.MemoryUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.StorageUtils +import java.io.ByteArrayInputStream +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock +import kotlin.math.ceil + +class SvgRegionFetcher internal constructor( + private val context: Context, +) { + suspend fun fetch( + uri: Uri, + decoded: Boolean, + sizeBytes: Long?, + scale: Int, + regionRect: Rect, + imageWidth: Int, + imageHeight: Int, + result: ByteSink, + ) { + if (!MemoryUtils.canAllocate(sizeBytes)) { + // opening an SVG that large would yield an OOM during parsing from `com.caverock.androidsvg.SVGParser` + result.error("fetch-read-large-file", "SVG too large at $sizeBytes bytes, for uri=$uri regionRect=$regionRect", null) + return + } + + try { + val svg = getOrCreateDecoder(context, uri) + if (svg == null) { + result.error("fetch-read-null", "failed to open file for uri=$uri regionRect=$regionRect", null) + return + } + + // we scale the requested region accordingly to the viewbox size + val viewBox = svg.documentViewBox + val svgWidth = viewBox.width() + val svgHeight = viewBox.height() + val xf = imageWidth / scale / ceil(svgWidth) + val yf = imageHeight / scale / ceil(svgHeight) + // some SVG paths do not respect the rendering viewbox and do not reach its edges + // so we render to a slightly larger bitmap, using a slightly larger viewbox, + // and crop that bitmap to the target region size + val bleedX = xf.toInt() + val bleedY = yf.toInt() + val effectiveRect = RectF( + (regionRect.left - bleedX) / xf, + (regionRect.top - bleedY) / yf, + (regionRect.right + bleedX) / xf, + (regionRect.bottom + bleedY) / yf, + ) + effectiveRect.offset(viewBox.left, viewBox.top) + + val renderOptions = RenderOptions() + renderOptions.viewBox(effectiveRect.left, effectiveRect.top, effectiveRect.width(), effectiveRect.height()) + renderOptions.preserveAspectRatio(PreserveAspectRatio.FULLSCREEN_START) + + val targetBitmapWidth = regionRect.width() + val targetBitmapHeight = regionRect.height() + val canvasWidth = targetBitmapWidth + bleedX * 2 + val canvasHeight = targetBitmapHeight + bleedY * 2 + + val config = PREFERRED_CONFIG + val pixelCount = canvasWidth * canvasHeight + val targetBitmapSizeBytes = BitmapUtils.getExpectedImageSize(pixelCount.toLong(), config) + if (!MemoryUtils.canAllocate(targetBitmapSizeBytes)) { + // decoding a region that large would yield an OOM when creating the bitmap + result.error("fetch-large-region", "SVG region too large for uri=$uri regionRect=$regionRect", null) + return + } + + var bitmap = createBitmap(canvasWidth, canvasHeight, config) + val canvas = Canvas(bitmap) + SVGAndroidRenderer.setImageBase64StringMaxSize(IMAGE_BASE64_SIZE_DANGER_THRESHOLD) + svg.renderToCanvas(canvas, renderOptions) + + bitmap = Bitmap.createBitmap(bitmap, bleedX, bleedY, targetBitmapWidth, targetBitmapHeight) + val bytes = BitmapUtils.getBytes(bitmap, recycle = true, decoded = decoded, MimeTypes.SVG) + if (bytes == null) { + result.error("fetch-null", "failed to decode SVG for uri=$uri regionRect=$regionRect", null) + } else { + result.streamBytes(ByteArrayInputStream(bytes)) + } + } catch (e: SVGParseException) { + result.error("fetch-parse", "failed to parse SVG for uri=$uri regionRect=$regionRect", e.message) + } catch (e: Exception) { + result.error("fetch-exception", "failed to initialize region decoder for uri=$uri regionRect=$regionRect", e.message) + } + } + + private data class DecoderRef( + val uri: Uri, + val decoder: SVG, + ) + + companion object { + private val PREFERRED_CONFIG = Bitmap.Config.ARGB_8888 + private const val DECODER_POOL_SIZE = 3 + private val decoderPool = ArrayList<DecoderRef>() + + private val poolLock = ReentrantLock() + + private fun getOrCreateDecoder(context: Context, uri: Uri): SVG? { + poolLock.withLock { + var decoderRef = decoderPool.firstOrNull { it.uri == uri } + if (decoderRef == null) { + val newDecoder = StorageUtils.openInputStream(context, uri)?.use { input -> + SVG.getFromInputStream(SVGParserBufferedInputStream(input)) + } + if (newDecoder == null) { + return null + } + newDecoder.normalizeSize() + decoderRef = DecoderRef(uri, newDecoder) + } else { + decoderPool.remove(decoderRef) + } + decoderPool.add(0, decoderRef) + while (decoderPool.size > DECODER_POOL_SIZE) { + decoderPool.removeAt(decoderPool.size - 1) + } + return decoderRef.decoder + } + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/decoding/ThumbnailFetcher.kt b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/ThumbnailFetcher.kt new file mode 100644 index 0000000..4b46a05 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/ThumbnailFetcher.kt @@ -0,0 +1,182 @@ +package deckers.thibault.aves.decoding + +import android.content.Context +import android.graphics.Bitmap +import android.net.Uri +import android.os.Build +import android.provider.MediaStore +import android.util.Log +import android.util.Size +import androidx.annotation.RequiresApi +import androidx.core.graphics.scale +import androidx.core.net.toUri +import com.bumptech.glide.Glide +import com.bumptech.glide.load.DecodeFormat +import com.bumptech.glide.load.engine.DiskCacheStrategy +import com.bumptech.glide.request.RequestOptions +import com.bumptech.glide.signature.ObjectKey +import deckers.thibault.aves.channel.streams.darttoplatform.ByteSink +import deckers.thibault.aves.glide.AvesAppGlideModule +import deckers.thibault.aves.glide.MultiPageImage +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.BitmapUtils.applyExifOrientation +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.SVG +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.MimeTypes.needRotationAfterContentResolverThumbnail +import deckers.thibault.aves.utils.MimeTypes.needRotationAfterGlide +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.UriUtils.tryParseId +import java.io.ByteArrayInputStream +import kotlin.math.min +import kotlin.math.roundToInt + +class ThumbnailFetcher internal constructor( + private val context: Context, + uri: String, + private val pageId: Int?, + private val decoded: Boolean, + private val mimeType: String, + private val dateModifiedMillis: Long, + private val rotationDegrees: Int, + private val isFlipped: Boolean, + width: Int?, + height: Int?, + private val defaultSize: Int, + private val quality: Int, + private val result: ByteSink, +) { + private val uri: Uri = uri.toUri() + private val width: Int = if (width?.takeIf { it > 0 } != null) width else defaultSize + private val height: Int = if (height?.takeIf { it > 0 } != null) height else defaultSize + private val svgFetch = mimeType == SVG + private val tiffFetch = mimeType == MimeTypes.TIFF + private val multiPageFetch = pageId != null && MultiPageImage.isSupported(mimeType) + private val customFetch = svgFetch || tiffFetch || multiPageFetch + + suspend fun fetch() { + var bitmap: Bitmap? = null + var exception: Exception? = null + + try { + if (!customFetch && (width == defaultSize || height == defaultSize) && !isFlipped) { + // Fetch low quality thumbnails when size is not specified. + // As of Android 11, the Media Store content resolver may return a thumbnail + // that is automatically rotated according to EXIF orientation, but not flipped, + // so we skip this step for flipped entries. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + bitmap = getByResolver() + } else if (StorageUtils.isMediaStoreContentUri(uri)) { + bitmap = getByMediaStore() + } + } + } catch (e: Exception) { + exception = e + } + + // fallback if the native methods failed or for higher quality thumbnails + if (bitmap == null) { + try { + bitmap = getByGlide() + } catch (e: Exception) { + exception = e + } + } + + if (bitmap != null) { + if (bitmap.width > width && bitmap.height > height) { + // rescale when the resulting bitmap is larger than requested + val scalingFactor: Double = min(bitmap.width.toDouble() / width, bitmap.height.toDouble() / height) + val dstWidth = (bitmap.width / scalingFactor).roundToInt() + val dstHeight = (bitmap.height / scalingFactor).roundToInt() + Log.d( + LOG_TAG, "rescale thumbnail for mimeType=$mimeType uri=$uri width=$width height=$height" + + ", with bitmap byteCount=${bitmap.byteCount} size=${bitmap.width}x${bitmap.height}" + + ", to target=${dstWidth}x${dstHeight}" + ) + bitmap = bitmap.scale(dstWidth, dstHeight) + } + + if (bitmap.byteCount > BITMAP_SIZE_DANGER_THRESHOLD) { + result.error( + "getThumbnail-large", "thumbnail bitmap dangerously large" + + " for mimeType=$mimeType uri=$uri pageId=$pageId width=$width height=$height" + + ", with bitmap byteCount=${bitmap.byteCount} size=${bitmap.width}x${bitmap.height} config=${bitmap.config?.name}", null + ) + return + } + } + + // do not recycle bitmaps fetched from `ContentResolver` or Glide as their lifecycle is unknown + val bytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = decoded, mimeType) + if (bytes == null) { + var errorDetails: String? = exception?.message + if (errorDetails?.isNotEmpty() == true) { + errorDetails = errorDetails.split(Regex("\n"), 2).first() + } + result.error("getThumbnail-null", "failed to get thumbnail for mimeType=$mimeType uri=$uri", errorDetails) + } else { + result.streamBytes(ByteArrayInputStream(bytes)) + } + } + + @RequiresApi(api = Build.VERSION_CODES.Q) + private fun getByResolver(): Bitmap? { + val resolver = context.contentResolver + var bitmap: Bitmap? = resolver.loadThumbnail(uri, Size(width, height), null) + if (needRotationAfterContentResolverThumbnail(mimeType)) { + bitmap = applyExifOrientation(context, bitmap, rotationDegrees, isFlipped) + } + return bitmap + } + + private fun getByMediaStore(): Bitmap? { + val contentId = uri.tryParseId() ?: return null + val resolver = context.contentResolver + return if (isVideo(mimeType)) { + @Suppress("deprecation") + MediaStore.Video.Thumbnails.getThumbnail(resolver, contentId, MediaStore.Video.Thumbnails.MINI_KIND, null) + } else { + @Suppress("deprecation") + var bitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver, contentId, MediaStore.Images.Thumbnails.MINI_KIND, null) + // from Android 10 (API 29), returned thumbnail is already rotated according to EXIF orientation + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && bitmap != null) { + bitmap = applyExifOrientation(context, bitmap, rotationDegrees, isFlipped) + } + bitmap + } + } + + private fun getByGlide(): Bitmap? { + // add signature to ignore cache for images which got modified but kept the same URI + var options = RequestOptions() + .format(if (quality == 100) DecodeFormat.PREFER_ARGB_8888 else DecodeFormat.PREFER_RGB_565) + .signature(ObjectKey("$dateModifiedMillis-$rotationDegrees-$isFlipped-$width-$pageId")) + .override(width, height) + if (isVideo(mimeType)) { + options = options.diskCacheStrategy(DiskCacheStrategy.RESOURCE) + } + + val target = Glide.with(context) + .asBitmap() + .apply(options) + .load(AvesAppGlideModule.getModel(context, uri, mimeType, pageId)) + .submit(width, height) + + return try { + var bitmap = target.get() + if (needRotationAfterGlide(mimeType, pageId)) { + bitmap = applyExifOrientation(context, bitmap, rotationDegrees, isFlipped) + } + bitmap + } finally { + Glide.with(context).clear(target) + } + } + + companion object { + private val LOG_TAG = LogUtils.createTag<ThumbnailFetcher>() + private const val BITMAP_SIZE_DANGER_THRESHOLD = 20 * (1 shl 20) // MB + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/decoding/TiffRegionFetcher.kt b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/TiffRegionFetcher.kt new file mode 100644 index 0000000..7c58df0 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/TiffRegionFetcher.kt @@ -0,0 +1,51 @@ +package deckers.thibault.aves.decoding + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Rect +import android.net.Uri +import deckers.thibault.aves.channel.streams.darttoplatform.ByteSink +import deckers.thibault.aves.glide.TiffFetcher +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.MimeTypes +import org.beyka.tiffbitmapfactory.DecodeArea +import org.beyka.tiffbitmapfactory.TiffBitmapFactory +import java.io.ByteArrayInputStream + +class TiffRegionFetcher internal constructor( + private val context: Context, +) { + suspend fun fetch( + uri: Uri, + page: Int, + decoded: Boolean, + sampleSize: Int, + regionRect: Rect, + result: ByteSink, + ) { + try { + val pfd = context.contentResolver.openFileDescriptor(uri, "r") + if (pfd == null) { + result.error("fetch-fd", "failed to get file descriptor for uri=$uri", null) + return + } + pfd.use { + val fd = pfd.detachFd() + val options = TiffFetcher.buildOptions().apply { + inDirectoryNumber = page + inSampleSize = sampleSize + inDecodeArea = DecodeArea(regionRect.left, regionRect.top, regionRect.width(), regionRect.height()) + } + val bitmap: Bitmap? = TiffBitmapFactory.decodeFileDescriptor(fd, options) + val bytes = BitmapUtils.getBytes(bitmap, recycle = true, decoded = decoded, MimeTypes.TIFF) + if (bytes == null) { + result.error("fetch-null", "failed to decode region for uri=$uri page=$page regionRect=$regionRect", null) + } else { + result.streamBytes(ByteArrayInputStream(bytes)) + } + } + } catch (e: Exception) { + result.error("fetch-exception", "failed to read from uri=$uri page=$page regionRect=$regionRect", e.message) + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/AvesAppGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/AvesAppGlideModule.kt new file mode 100644 index 0000000..0b2951a --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/AvesAppGlideModule.kt @@ -0,0 +1,92 @@ +package deckers.thibault.aves.glide + +import android.content.Context +import android.net.Uri +import android.text.format.Formatter +import android.util.Log +import com.bumptech.glide.Glide +import com.bumptech.glide.GlideBuilder +import com.bumptech.glide.Registry +import com.bumptech.glide.annotation.GlideModule +import com.bumptech.glide.load.DecodeFormat +import com.bumptech.glide.load.ImageHeaderParser +import com.bumptech.glide.load.engine.DiskCacheStrategy +import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPoolAdapter +import com.bumptech.glide.load.engine.bitmap_recycle.LruArrayPool +import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool +import com.bumptech.glide.load.engine.cache.DiskCache +import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory +import com.bumptech.glide.load.engine.cache.LruResourceCache +import com.bumptech.glide.load.engine.cache.MemorySizeCalculator +import com.bumptech.glide.load.resource.bitmap.ExifInterfaceImageHeaderParser +import com.bumptech.glide.module.AppGlideModule +import com.bumptech.glide.request.RequestOptions +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.compatRemoveIf + +@GlideModule +class AvesAppGlideModule : AppGlideModule() { + override fun applyOptions(context: Context, builder: GlideBuilder) { + // hide noisy warning (e.g. for images that can't be decoded) + builder.setLogLevel(Log.ERROR) + + // sizing + val memorySizeCalculator = MemorySizeCalculator.Builder(context).build() + builder.setMemorySizeCalculator(memorySizeCalculator) + val size: Int = memorySizeCalculator.bitmapPoolSize + if (size > 0) { + builder.setBitmapPool(LruBitmapPool(size.toLong())) + } else { + builder.setBitmapPool(BitmapPoolAdapter()) + } + builder.setArrayPool(LruArrayPool(memorySizeCalculator.arrayPoolSizeInBytes)) + builder.setMemoryCache(LruResourceCache(memorySizeCalculator.memoryCacheSize.toLong())) + + val diskCacheSize = DiskCache.Factory.DEFAULT_DISK_CACHE_SIZE + val internalCacheDiskCacheFactory = InternalCacheDiskCacheFactory(context, DiskCache.Factory.DEFAULT_DISK_CACHE_DIR, diskCacheSize.toLong()) + builder.setDiskCache(internalCacheDiskCacheFactory) + + fun toMb(bytes: Int) = Formatter.formatFileSize(context, bytes.toLong()) + Log.d( + LOG_TAG, "Glide disk cache size=${toMb(diskCacheSize)}" + + ", memory cache size=${toMb(memorySizeCalculator.memoryCacheSize)}" + + ", bitmap pool size=${toMb(memorySizeCalculator.bitmapPoolSize)}" + + ", array pool size=${toMb(memorySizeCalculator.arrayPoolSizeInBytes)}" + ) + } + + override fun registerComponents(context: Context, glide: Glide, registry: Registry) { + // prevent ExifInterface error logs + // cf https://github.com/bumptech/glide/issues/3383 + registry.imageHeaderParsers.compatRemoveIf { parser: ImageHeaderParser? -> parser is ExifInterfaceImageHeaderParser } + } + + override fun isManifestParsingEnabled(): Boolean = false + + companion object { + private val LOG_TAG = LogUtils.createTag<AvesAppGlideModule>() + + // request a fresh image with the highest quality format + val uncachedFullImageOptions = RequestOptions() + .format(DecodeFormat.PREFER_ARGB_8888) + .diskCacheStrategy(DiskCacheStrategy.NONE) + .skipMemoryCache(true) + + fun getModel(context: Context, uri: Uri, mimeType: String, pageId: Int?, sizeBytes: Long? = null): Any { + return if (pageId != null && MultiPageImage.isSupported(mimeType)) { + MultiPageImage(context, uri, mimeType, pageId) + } else if (mimeType == MimeTypes.TIFF) { + TiffImage(context, uri, pageId) + } else if (mimeType == MimeTypes.SVG) { + SvgImage(context, uri) + } else if (isVideo(mimeType)) { + VideoThumbnail(context, uri) + } else { + StorageUtils.getGlideSafeUri(context, uri, mimeType, sizeBytes) + } + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/MultiPageImageGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/MultiPageImageGlideModule.kt new file mode 100644 index 0000000..a87a7c9 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/MultiPageImageGlideModule.kt @@ -0,0 +1,89 @@ +package deckers.thibault.aves.glide + +import android.content.Context +import android.graphics.Bitmap +import android.net.Uri +import android.os.Build +import com.bumptech.glide.Glide +import com.bumptech.glide.Priority +import com.bumptech.glide.Registry +import com.bumptech.glide.annotation.GlideModule +import com.bumptech.glide.load.DataSource +import com.bumptech.glide.load.Options +import com.bumptech.glide.load.data.DataFetcher +import com.bumptech.glide.load.data.DataFetcher.DataCallback +import com.bumptech.glide.load.model.ModelLoader +import com.bumptech.glide.load.model.ModelLoaderFactory +import com.bumptech.glide.load.model.MultiModelLoaderFactory +import com.bumptech.glide.module.LibraryGlideModule +import com.bumptech.glide.signature.ObjectKey +import deckers.thibault.aves.metadata.MultiPage +import deckers.thibault.aves.metadata.MultiTrackMedia +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.isIsoBMFFImage + +@GlideModule +class MultiPageImageGlideModule : LibraryGlideModule() { + override fun registerComponents(context: Context, glide: Glide, registry: Registry) { + registry.append(MultiPageImage::class.java, Bitmap::class.java, MultiPageThumbnailLoader.Factory()) + } +} + +class MultiPageImage(val context: Context, val uri: Uri, val mimeType: String, val pageId: Int?) { + override fun toString(): String = "MultiPageImage#${hashCode()}{uri=$uri mimeType=$mimeType pageId=$pageId}" + + companion object { + fun isSupported(mimeType: String) = isIsoBMFFImage(mimeType) || mimeType == MimeTypes.JPEG + } +} + +internal class MultiPageThumbnailLoader : ModelLoader<MultiPageImage, Bitmap> { + override fun buildLoadData(model: MultiPageImage, width: Int, height: Int, options: Options): ModelLoader.LoadData<Bitmap> { + return ModelLoader.LoadData(ObjectKey(model.uri), MultiPageImageFetcher(model, width, height)) + } + + override fun handles(model: MultiPageImage): Boolean = true + + internal class Factory : ModelLoaderFactory<MultiPageImage, Bitmap> { + override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<MultiPageImage, Bitmap> = MultiPageThumbnailLoader() + + override fun teardown() {} + } +} + +internal class MultiPageImageFetcher(val model: MultiPageImage, val width: Int, val height: Int) : DataFetcher<Bitmap> { + override fun loadData(priority: Priority, callback: DataCallback<in Bitmap>) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + callback.onLoadFailed(Exception("unsupported Android version")) + return + } + + val context = model.context + val uri = model.uri + val mimeType = model.mimeType + + var bitmap: Bitmap? = null + if (isIsoBMFFImage(mimeType)) { + val trackIndex = model.pageId + bitmap = MultiTrackMedia.getImage(context, uri, trackIndex) + } else if (mimeType == MimeTypes.JPEG) { + val pageIndex = model.pageId ?: 0 + bitmap = MultiPage.getJpegMpfBitmap(context, uri, pageIndex) + } + + if (bitmap == null) { + callback.onLoadFailed(Exception("null bitmap")) + } else { + callback.onDataReady(bitmap) + } + } + + override fun cleanup() {} + + // cannot cancel + override fun cancel() {} + + override fun getDataClass(): Class<Bitmap> = Bitmap::class.java + + override fun getDataSource(): DataSource = DataSource.LOCAL +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/SvgGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/SvgGlideModule.kt new file mode 100644 index 0000000..2a43d4b --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/SvgGlideModule.kt @@ -0,0 +1,102 @@ +package deckers.thibault.aves.glide + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.net.Uri +import androidx.core.graphics.createBitmap +import com.bumptech.glide.Glide +import com.bumptech.glide.Priority +import com.bumptech.glide.Registry +import com.bumptech.glide.annotation.GlideModule +import com.bumptech.glide.load.DataSource +import com.bumptech.glide.load.Options +import com.bumptech.glide.load.data.DataFetcher +import com.bumptech.glide.load.model.ModelLoader +import com.bumptech.glide.load.model.ModelLoaderFactory +import com.bumptech.glide.load.model.MultiModelLoaderFactory +import com.bumptech.glide.module.LibraryGlideModule +import com.bumptech.glide.signature.ObjectKey +import com.caverock.androidsvg.SVG +import com.caverock.androidsvg.SVGParseException +import com.caverock.androidsvg.utils.SVGAndroidRenderer +import deckers.thibault.aves.metadata.SVGParserBufferedInputStream +import deckers.thibault.aves.metadata.SvgHelper.IMAGE_BASE64_SIZE_DANGER_THRESHOLD +import deckers.thibault.aves.metadata.SvgHelper.normalizeSize +import deckers.thibault.aves.utils.StorageUtils +import kotlin.math.ceil + +@GlideModule +class SvgGlideModule : LibraryGlideModule() { + override fun registerComponents(context: Context, glide: Glide, registry: Registry) { + registry.append(SvgImage::class.java, Bitmap::class.java, SvgLoader.Factory()) + } +} + +class SvgImage(val context: Context, val uri: Uri) + +internal class SvgLoader : ModelLoader<SvgImage, Bitmap> { + override fun buildLoadData(model: SvgImage, width: Int, height: Int, options: Options): ModelLoader.LoadData<Bitmap> { + return ModelLoader.LoadData(ObjectKey(model.uri), SvgFetcher(model, width, height)) + } + + override fun handles(model: SvgImage): Boolean = true + + internal class Factory : ModelLoaderFactory<SvgImage, Bitmap> { + override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<SvgImage, Bitmap> = SvgLoader() + + override fun teardown() {} + } +} + +internal class SvgFetcher(val model: SvgImage, val width: Int, val height: Int) : DataFetcher<Bitmap> { + override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in Bitmap>) { + val context = model.context + val uri = model.uri + + val bitmap: Bitmap? = StorageUtils.openInputStream(context, uri)?.use { input -> + try { + SVG.getFromInputStream(SVGParserBufferedInputStream(input))?.let { svg -> + svg.normalizeSize() + val viewBox = svg.documentViewBox + val svgWidth = viewBox.width() + val svgHeight = viewBox.height() + + val bitmapWidth: Int + val bitmapHeight: Int + if (width / height.toFloat() > svgWidth / svgHeight) { + bitmapWidth = ceil(svgWidth * height / svgHeight).toInt() + bitmapHeight = height + } else { + bitmapWidth = width + bitmapHeight = ceil(svgHeight * width / svgWidth).toInt() + } + val bitmap = createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888) + + val canvas = Canvas(bitmap) + SVGAndroidRenderer.setImageBase64StringMaxSize(IMAGE_BASE64_SIZE_DANGER_THRESHOLD) + svg.renderToCanvas(canvas) + bitmap + } + } catch (ex: SVGParseException) { + callback.onLoadFailed(ex) + return + } + } + + if (bitmap == null) { + callback.onLoadFailed(Exception("failed to load SVG for uri=$uri")) + } else { + callback.onDataReady(bitmap) + } + } + + override fun cleanup() {} + + // cannot cancel + override fun cancel() {} + + override fun getDataClass(): Class<Bitmap> = Bitmap::class.java + + override fun getDataSource(): DataSource = DataSource.LOCAL +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/TiffGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/TiffGlideModule.kt new file mode 100644 index 0000000..f0cd864 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/TiffGlideModule.kt @@ -0,0 +1,127 @@ +package deckers.thibault.aves.glide + +import android.content.Context +import android.graphics.Bitmap +import android.net.Uri +import androidx.core.graphics.scale +import com.bumptech.glide.Glide +import com.bumptech.glide.Priority +import com.bumptech.glide.Registry +import com.bumptech.glide.annotation.GlideModule +import com.bumptech.glide.load.DataSource +import com.bumptech.glide.load.Options +import com.bumptech.glide.load.data.DataFetcher +import com.bumptech.glide.load.data.DataFetcher.DataCallback +import com.bumptech.glide.load.model.ModelLoader +import com.bumptech.glide.load.model.ModelLoaderFactory +import com.bumptech.glide.load.model.MultiModelLoaderFactory +import com.bumptech.glide.module.LibraryGlideModule +import com.bumptech.glide.signature.ObjectKey +import org.beyka.tiffbitmapfactory.TiffBitmapFactory + +@GlideModule +class TiffGlideModule : LibraryGlideModule() { + override fun registerComponents(context: Context, glide: Glide, registry: Registry) { + registry.append(TiffImage::class.java, Bitmap::class.java, TiffLoader.Factory()) + } +} + +class TiffImage(val context: Context, val uri: Uri, val page: Int?) + +internal class TiffLoader : ModelLoader<TiffImage, Bitmap> { + override fun buildLoadData(model: TiffImage, width: Int, height: Int, options: Options): ModelLoader.LoadData<Bitmap> { + return ModelLoader.LoadData(ObjectKey(model.uri), TiffFetcher(model, width, height)) + } + + override fun handles(model: TiffImage): Boolean = true + + internal class Factory : ModelLoaderFactory<TiffImage, Bitmap> { + override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<TiffImage, Bitmap> = TiffLoader() + + override fun teardown() {} + } +} + +internal class TiffFetcher(val model: TiffImage, val width: Int, val height: Int) : DataFetcher<Bitmap> { + override fun loadData(priority: Priority, callback: DataCallback<in Bitmap>) { + val context = model.context + val uri = model.uri + val page = model.page ?: 0 + + var sampleSize = 1 + val customSize = width > 0 && height > 0 + if (customSize) { + // determine sample size + val fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd() + if (fd == null) { + callback.onLoadFailed(Exception("null file descriptor")) + return + } + val options = buildOptions().apply { + inJustDecodeBounds = true + inDirectoryNumber = page + } + TiffBitmapFactory.decodeFileDescriptor(fd, options) + val imageWidth = options.outWidth + val imageHeight = options.outHeight + if (imageWidth > width || imageHeight > height) { + while (imageHeight / (sampleSize * 2) >= height && imageWidth / (sampleSize * 2) >= width) { + sampleSize *= 2 + } + } + } + + // decode + val fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd() + if (fd == null) { + callback.onLoadFailed(Exception("null file descriptor")) + return + } + val options = buildOptions().apply { + inDirectoryNumber = page + inSampleSize = sampleSize + } + try { + val bitmap: Bitmap? = TiffBitmapFactory.decodeFileDescriptor(fd, options) + // calling `TiffBitmapFactory.closeFd(fd)` after decoding yields a segmentation fault + + if (bitmap == null) { + callback.onLoadFailed(Exception("Decoding full TIFF yielded null bitmap")) + } else if (customSize) { + val dstWidth: Int + val dstHeight: Int + val aspectRatio = bitmap.width.toFloat() / bitmap.height + if (aspectRatio > 1) { + dstWidth = (height * aspectRatio).toInt() + dstHeight = height + } else { + dstWidth = width + dstHeight = (width / aspectRatio).toInt() + } + callback.onDataReady(bitmap.scale(dstWidth, dstHeight)) + } else { + callback.onDataReady(bitmap) + } + } catch (e: Exception) { + callback.onLoadFailed(e) + } + } + + override fun cleanup() {} + + // cannot cancel + override fun cancel() {} + + override fun getDataClass(): Class<Bitmap> = Bitmap::class.java + + override fun getDataSource(): DataSource = DataSource.LOCAL + + companion object { + fun buildOptions(): TiffBitmapFactory.Options { + return TiffBitmapFactory.Options().apply { + inThrowException = true + inUseOrientationTag = false + } + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/VideoThumbnailGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/VideoThumbnailGlideModule.kt new file mode 100644 index 0000000..f3eef5f --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/VideoThumbnailGlideModule.kt @@ -0,0 +1,192 @@ +package deckers.thibault.aves.glide + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.media.MediaMetadataRetriever +import android.net.Uri +import android.os.Build +import androidx.annotation.RequiresApi +import com.bumptech.glide.Glide +import com.bumptech.glide.Priority +import com.bumptech.glide.Registry +import com.bumptech.glide.annotation.GlideModule +import com.bumptech.glide.load.DataSource +import com.bumptech.glide.load.Options +import com.bumptech.glide.load.data.DataFetcher +import com.bumptech.glide.load.data.DataFetcher.DataCallback +import com.bumptech.glide.load.model.ModelLoader +import com.bumptech.glide.load.model.ModelLoaderFactory +import com.bumptech.glide.load.model.MultiModelLoaderFactory +import com.bumptech.glide.module.LibraryGlideModule +import com.bumptech.glide.signature.ObjectKey +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.MemoryUtils +import deckers.thibault.aves.utils.StorageUtils.openMetadataRetriever +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import java.io.ByteArrayInputStream +import java.io.IOException +import kotlin.math.min +import kotlin.math.roundToInt + +@GlideModule +class VideoThumbnailGlideModule : LibraryGlideModule() { + override fun registerComponents(context: Context, glide: Glide, registry: Registry) { + registry.append(VideoThumbnail::class.java, Bitmap::class.java, VideoThumbnailLoader.Factory()) + } +} + +class VideoThumbnail(val context: Context, val uri: Uri) + +internal class VideoThumbnailLoader : ModelLoader<VideoThumbnail, Bitmap> { + override fun buildLoadData(model: VideoThumbnail, width: Int, height: Int, options: Options): ModelLoader.LoadData<Bitmap> { + return ModelLoader.LoadData(ObjectKey(model.uri), VideoThumbnailFetcher(model, width, height)) + } + + override fun handles(model: VideoThumbnail): Boolean = true + + internal class Factory : ModelLoaderFactory<VideoThumbnail, Bitmap> { + override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<VideoThumbnail, Bitmap> = VideoThumbnailLoader() + + override fun teardown() {} + } +} + +internal class VideoThumbnailFetcher(private val model: VideoThumbnail, val width: Int, val height: Int) : DataFetcher<Bitmap> { + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + override fun loadData(priority: Priority, callback: DataCallback<in Bitmap>) { + ioScope.launch { + val retriever = openMetadataRetriever(model.context, model.uri) + if (retriever == null) { + callback.onLoadFailed(Exception("failed to initialize MediaMetadataRetriever for uri=${model.uri}")) + } else { + try { + var bitmap: Bitmap? = null + + retriever.embeddedPicture?.let { bytes -> + try { + bitmap = BitmapFactory.decodeStream(ByteArrayInputStream(bytes)) + } catch (_: IOException) { + // ignore + } + } + + if (bitmap == null) { + // there is no consistent strategy across devices to match + // the thumbnails returned by the content resolver / Media Store + // so we derive one in an arbitrary way + var timeMillis: Long? = null + val durationMillis = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() + if (durationMillis != null) { + timeMillis = if (durationMillis < 15000) 0 else min(durationMillis / 2, 15000) + } + val timeMicros = if (timeMillis != null) timeMillis * 1000 else -1 + val option = MediaMetadataRetriever.OPTION_CLOSEST_SYNC + + var videoWidth = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toFloatOrNull() + var videoHeight = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toFloatOrNull() + if (videoWidth == null || videoHeight == null) { + throw Exception("failed to get video dimensions") + } + + val rotationDegrees = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull() ?: 0 + val isRotated = rotationDegrees % 180 == 90 + if (isRotated) { + videoWidth = videoHeight.also { videoHeight = videoWidth } + } + + var dstWidth = 0 + var dstHeight = 0 + if (width > 0 && height > 0) { + // cover fit + val targetAspectRatio = width / height.toFloat() + val videoAspectRatio = videoWidth / videoHeight + if (targetAspectRatio > videoAspectRatio) { + dstHeight = (width / videoAspectRatio).roundToInt() + dstWidth = (dstHeight * videoAspectRatio).roundToInt() + } else { + dstWidth = (height * videoAspectRatio).roundToInt() + dstHeight = (dstWidth / videoAspectRatio).roundToInt() + } + } + if (dstWidth == 0 || dstWidth > videoWidth || dstHeight == 0 || dstHeight > videoHeight) { + dstWidth = videoWidth.toInt() + dstHeight = videoHeight.toInt() + } + + // the returned frame is already rotated according to the video metadata + fun getFrameAtTime(timeMicros: Long): Bitmap? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { + val pixelCount = dstWidth * dstHeight + val targetBitmapSizeBytes = BitmapUtils.getExpectedImageSize(pixelCount.toLong(), getPreferredConfig()) + if (!MemoryUtils.canAllocate(targetBitmapSizeBytes)) { + throw Exception("not enough memory to allocate $targetBitmapSizeBytes bytes for the scaled frame at $dstWidth x $dstHeight") + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + retriever.getScaledFrameAtTime(timeMicros, option, dstWidth, dstHeight, getBitmapParams()) + } else { + retriever.getScaledFrameAtTime(timeMicros, option, dstWidth, dstHeight) + } + } else { + val pixelCount = videoWidth * videoHeight + val targetBitmapSizeBytes = BitmapUtils.getExpectedImageSize(pixelCount.toLong(), getPreferredConfig()) + if (!MemoryUtils.canAllocate(targetBitmapSizeBytes)) { + throw Exception("not enough memory to allocate $targetBitmapSizeBytes bytes for the full frame at $videoWidth x $videoHeight") + } + retriever.getFrameAtTime(timeMicros, option) + } + } + + bitmap = getFrameAtTime(timeMicros) + if (bitmap == null && timeMicros > 0) { + // retry to get the first frame instead of an arbitrary one + bitmap = getFrameAtTime(0) + } + } + + if (bitmap == null) { + callback.onLoadFailed(Exception("failed to get embedded picture or any frame for uri=${model.uri}")) + } else { + callback.onDataReady(bitmap) + } + } catch (e: Exception) { + callback.onLoadFailed(e) + } finally { + // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs + retriever.release() + } + } + } + } + + @RequiresApi(Build.VERSION_CODES.P) + private fun getBitmapParams(): MediaMetadataRetriever.BitmapParams { + val params = MediaMetadataRetriever.BitmapParams() + params.preferredConfig = this.getPreferredConfig() + return params + } + + private fun getPreferredConfig(): Bitmap.Config { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + // improved precision with the same memory cost as `ARGB_8888` (4 bytes per pixel) + // for wide-gamut and HDR content which does not require alpha blending + Bitmap.Config.RGBA_1010102 + } else { + Bitmap.Config.ARGB_8888 + } + } + + // already cleaned up in loadData and ByteArrayInputStream will be GC'd + override fun cleanup() {} + + // cannot cancel + override fun cancel() {} + + override fun getDataClass(): Class<Bitmap> = Bitmap::class.java + + override fun getDataSource(): DataSource = DataSource.LOCAL +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/DngTags.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/DngTags.kt new file mode 100644 index 0000000..3137919 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/DngTags.kt @@ -0,0 +1,229 @@ +package deckers.thibault.aves.metadata + +// DNG v1.6.0.0 +// cf https://helpx.adobe.com/content/dam/help/en/photoshop/pdf/dng_spec_1_6_0_0.pdf +object DngTags { + private const val DNG_VERSION = 0xC612 + private const val DNG_BACKWARD_VERSION = 0xC613 + private const val UNIQUE_CAMERA_MODEL = 0xC614 + private const val LOCALIZED_CAMERA_MODEL = 0xC615 + private const val CFA_PLANE_COLOR = 0xC616 + private const val CFA_LAYOUT = 0xC617 + private const val LINEARIZATION_TABLE = 0xC618 + private const val BLACK_LEVEL_REPEAT_DIM = 0xC619 + private const val BLACK_LEVEL = 0xC61A + private const val BLACK_LEVEL_DELTA_H = 0xC61B + private const val BLACK_LEVEL_DELTA_V = 0xC61C + private const val WHITE_LEVEL = 0xC61D + private const val DEFAULT_SCALE = 0xC61E + private const val DEFAULT_CROP_ORIGIN = 0xC61F + private const val DEFAULT_CROP_SIZE = 0xC620 + private const val COLOR_MATRIX_1 = 0xC621 + private const val COLOR_MATRIX_2 = 0xC622 + private const val CAMERA_CALIBRATION_1 = 0xC623 + private const val CAMERA_CALIBRATION_2 = 0xC624 + private const val REDUCTION_MATRIX_1 = 0xC625 + private const val REDUCTION_MATRIX_2 = 0xC626 + private const val ANALOG_BALANCE = 0xC627 + private const val AS_SHOT_NEUTRAL = 0xC628 + private const val AS_SHOT_WHITE_XY = 0xC629 + private const val BASELINE_EXPOSURE = 0xC62A + private const val BASELINE_NOISE = 0xC62B + private const val BASELINE_SHARPNESS = 0xC62C + private const val BAYER_GREEN_SPLIT = 0xC62D + private const val LINEAR_RESPONSE_LIMIT = 0xC62E + private const val CAMERA_SERIAL_NUMBER = 0xC62F + private const val LENS_INFO = 0xC630 + private const val CHROMA_BLUR_RADIUS = 0xC631 + private const val ANTI_ALIAS_STRENGTH = 0xC632 + private const val SHADOW_SCALE = 0xC633 + private const val DNG_PRIVATE_DATA = 0xC634 + private const val MAKER_NOTE_SAFETY = 0xC635 + private const val CALIBRATION_ILLUMINANT_1 = 0xC65A + private const val CALIBRATION_ILLUMINANT_2 = 0xC65B + private const val BEST_QUALITY_SCALE = 0xC65C + private const val RAW_DATA_UNIQUE_ID = 0xC65D + private const val ORIGINAL_RAW_FILE_NAME = 0xC68B + private const val ORIGINAL_RAW_FILE_DATA = 0xC68C + private const val ACTIVE_AREA = 0xC68D + private const val MASKED_AREAS = 0xC68E + private const val AS_SHOT_ICC_PROFILE = 0xC68F + private const val AS_SHOT_PRE_PROFILE_MATRIX = 0xC690 + private const val CURRENT_ICC_PROFILE = 0xC691 + private const val CURRENT_PRE_PROFILE_MATRIX = 0xC692 + private const val COLORIMETRIC_REFERENCE = 0xC6BF + private const val CAMERA_CALIBRATION_SIGNATURE = 0xC6F3 + private const val PROFILE_CALIBRATION_SIGNATURE = 0xC6F4 + private const val EXTRA_CAMERA_PROFILES = 0xC6F5 + private const val AS_SHOT_PROFILE_NAME = 0xC6F6 + private const val NOISE_REDUCTION_APPLIED = 0xC6F7 + private const val PROFILE_NAME = 0xC6F8 + private const val PROFILE_HUE_SAT_MAP_DIMS = 0xC6F9 + private const val PROFILE_HUE_SAT_MAP_DATA_1 = 0xC6FA + private const val PROFILE_HUE_SAT_MAP_DATA_2 = 0xC6FB + private const val PROFILE_TONE_CURVE = 0xC6FC + private const val PROFILE_EMBED_POLICY = 0xC6FD + private const val PROFILE_COPYRIGHT = 0xC6FE + private const val FORWARD_MATRIX_1 = 0xC714 + private const val FORWARD_MATRIX_2 = 0xC715 + private const val PREVIEW_APPLICATION_NAME = 0xC716 + private const val PREVIEW_APPLICATION_VERSION = 0xC717 + private const val PREVIEW_SETTINGS_NAME = 0xC718 + private const val PREVIEW_SETTINGS_DIGEST = 0xC719 + private const val PREVIEW_COLOR_SPACE = 0xC71A + private const val PREVIEW_DATE_TIME = 0xC71B + private const val RAW_IMAGE_DIGEST = 0xC71C + private const val ORIGINAL_RAW_FILE_DIGEST = 0xC71D + private const val SUB_TILE_BLOCK_SIZE = 0xC71E + private const val ROW_INTERLEAVE_FACTOR = 0xC71F + private const val PROFILE_LOOK_TABLE_DIMS = 0xC725 + private const val PROFILE_LOOK_TABLE_DATA = 0xC726 + private const val OPCODE_LIST_1 = 0xC740 + private const val OPCODE_LIST_2 = 0xC741 + private const val OPCODE_LIST_3 = 0xC74E + private const val NOISE_PROFILE = 0xC761 + private const val ORIGINAL_DEFAULT_FINAL_SIZE = 0xC791 + private const val ORIGINAL_BEST_QUALITY_FINAL_SIZE = 0xC792 + private const val ORIGINAL_DEFAULT_CROP_SIZE = 0xC793 + private const val PROFILE_HUE_SAT_MAP_ENCODING = 0xC7A3 + private const val PROFILE_LOOK_TABLE_ENCODING = 0xC7A4 + private const val BASELINE_EXPOSURE_OFFSET = 0xC7A5 + private const val DEFAULT_BLACK_RENDER = 0xC7A6 + private const val NEW_RAW_IMAGE_DIGEST = 0xC7A7 + private const val RAW_TO_PREVIEW_GAIN = 0xC7A8 + private const val DEFAULT_USER_CROP = 0xC7B5 + private const val DEPTH_FORMAT = 0xC7E9 + private const val DEPTH_NEAR = 0xC7EA + private const val DEPTH_FAR = 0xC7EB + private const val DEPTH_UNITS = 0xC7EC + private const val DEPTH_MEASURE_TYPE = 0xC7ED + private const val ENHANCE_PARAMS = 0xC7EE + private const val PROFILE_GAIN_TABLE_MAP = 0xCD2D + private const val SEMANTIC_NAME = 0xCD2E + private const val SEMANTIC_INSTANCE_ID = 0xCD30 + private const val CALIBRATION_ILLUMINANT_3 = 0xCD31 + private const val CAMERA_CALIBRATION_3 = 0xCD32 + private const val COLOR_MATRIX_3 = 0xCD33 + private const val FORWARD_MATRIX_3 = 0xCD34 + private const val ILLUMINANT_DATA_1 = 0xCD35 + private const val ILLUMINANT_DATA_2 = 0xCD36 + private const val ILLUMINANT_DATA_3 = 0xCD37 + private const val MASK_SUB_AREA = 0xCD38 + private const val PROFILE_HUE_SAT_MAP_DATA_3 = 0xCD39 + private const val REDUCTION_MATRIX_3 = 0xCD3A + private const val RGB_TABLES = 0xCD3F + + val tagNameMap = hashMapOf( + DNG_VERSION to "DNG Version", + DNG_BACKWARD_VERSION to "DNG Backward Version", + UNIQUE_CAMERA_MODEL to "Unique Camera Model", + LOCALIZED_CAMERA_MODEL to "Localized Camera Model", + CFA_PLANE_COLOR to "CFA Plane Color", + CFA_LAYOUT to "CFA Layout", + LINEARIZATION_TABLE to "Linearization Table", + BLACK_LEVEL_REPEAT_DIM to "Black Level Repeat Dim", + BLACK_LEVEL to "Black Level", + BLACK_LEVEL_DELTA_H to "Black Level Delta H", + BLACK_LEVEL_DELTA_V to "Black Level Delta V", + WHITE_LEVEL to "White Level", + DEFAULT_SCALE to "Default Scale", + DEFAULT_CROP_ORIGIN to "Default Crop Origin", + DEFAULT_CROP_SIZE to "Default Crop Size", + COLOR_MATRIX_1 to "Color Matrix 1", + COLOR_MATRIX_2 to "Color Matrix 2", + CAMERA_CALIBRATION_1 to "Camera Calibration 1", + CAMERA_CALIBRATION_2 to "Camera Calibration 2", + REDUCTION_MATRIX_1 to "Reduction Matrix 1", + REDUCTION_MATRIX_2 to "Reduction Matrix 2", + ANALOG_BALANCE to "Analog Balance", + AS_SHOT_NEUTRAL to "As Shot Neutral", + AS_SHOT_WHITE_XY to "As Shot White XY", + BASELINE_EXPOSURE to "Baseline Exposure", + BASELINE_NOISE to "Baseline Noise", + BASELINE_SHARPNESS to "Baseline Sharpness", + BAYER_GREEN_SPLIT to "Bayer Green Split", + LINEAR_RESPONSE_LIMIT to "Linear Response Limit", + CAMERA_SERIAL_NUMBER to "Camera Serial Number", + LENS_INFO to "Lens Info", + CHROMA_BLUR_RADIUS to "Chroma Blur Radius", + ANTI_ALIAS_STRENGTH to "Anti Alias Strength", + SHADOW_SCALE to "Shadow Scale", + DNG_PRIVATE_DATA to "DNG Private Data", + MAKER_NOTE_SAFETY to "Maker Note Safety", + CALIBRATION_ILLUMINANT_1 to "Calibration Illuminant 1", + CALIBRATION_ILLUMINANT_2 to "Calibration Illuminant 2", + BEST_QUALITY_SCALE to "Best Quality Scale", + RAW_DATA_UNIQUE_ID to "Raw Data Unique ID", + ORIGINAL_RAW_FILE_NAME to "Original Raw File Name", + ORIGINAL_RAW_FILE_DATA to "Original Raw File Data", + ACTIVE_AREA to "Active Area", + MASKED_AREAS to "Masked Areas", + AS_SHOT_ICC_PROFILE to "As Shot ICC Profile", + AS_SHOT_PRE_PROFILE_MATRIX to "As Shot Pre Profile Matrix", + CURRENT_ICC_PROFILE to "Current ICC Profile", + CURRENT_PRE_PROFILE_MATRIX to "Current Pre Profile Matrix", + COLORIMETRIC_REFERENCE to "Colorimetric Reference", + CAMERA_CALIBRATION_SIGNATURE to "Camera Calibration Signature", + PROFILE_CALIBRATION_SIGNATURE to "Profile Calibration Signature", + EXTRA_CAMERA_PROFILES to "Extra Camera Profiles", + AS_SHOT_PROFILE_NAME to "As Shot Profile Name", + NOISE_REDUCTION_APPLIED to "Noise Reduction Applied", + PROFILE_NAME to "Profile Name", + PROFILE_HUE_SAT_MAP_DIMS to "Profile Hue Sat Map Dims", + PROFILE_HUE_SAT_MAP_DATA_1 to "Profile Hue Sat Map Data 1", + PROFILE_HUE_SAT_MAP_DATA_2 to "Profile Hue Sat Map Data 2", + PROFILE_TONE_CURVE to "Profile Tone Curve", + PROFILE_EMBED_POLICY to "Profile Embed Policy", + PROFILE_COPYRIGHT to "Profile Copyright", + FORWARD_MATRIX_1 to "Forward Matrix 1", + FORWARD_MATRIX_2 to "Forward Matrix 2", + PREVIEW_APPLICATION_NAME to "Preview Application Name", + PREVIEW_APPLICATION_VERSION to "Preview Application Version", + PREVIEW_SETTINGS_NAME to "Preview Settings Name", + PREVIEW_SETTINGS_DIGEST to "Preview Settings Digest", + PREVIEW_COLOR_SPACE to "Preview Color Space", + PREVIEW_DATE_TIME to "Preview Date Time", + RAW_IMAGE_DIGEST to "Raw Image Digest", + ORIGINAL_RAW_FILE_DIGEST to "Original Raw File Digest", + SUB_TILE_BLOCK_SIZE to "Sub Tile Block Size", + ROW_INTERLEAVE_FACTOR to "Row Interleave Factor", + PROFILE_LOOK_TABLE_DIMS to "Profile Look Table Dims", + PROFILE_LOOK_TABLE_DATA to "Profile Look Table Data", + OPCODE_LIST_1 to "Opcode List 1", + OPCODE_LIST_2 to "Opcode List 2", + OPCODE_LIST_3 to "Opcode List 3", + NOISE_PROFILE to "Noise Profile", + ORIGINAL_DEFAULT_FINAL_SIZE to "Original Default Final Size", + ORIGINAL_BEST_QUALITY_FINAL_SIZE to "Original Best Quality Final Size", + ORIGINAL_DEFAULT_CROP_SIZE to "Original Default Crop Size", + PROFILE_HUE_SAT_MAP_ENCODING to "Profile Hue Sat Map Encoding", + PROFILE_LOOK_TABLE_ENCODING to "Profile Look Table Encoding", + BASELINE_EXPOSURE_OFFSET to "Baseline Exposure Offset", + DEFAULT_BLACK_RENDER to "Default Black Render", + NEW_RAW_IMAGE_DIGEST to "New Raw Image Digest", + RAW_TO_PREVIEW_GAIN to "Raw To Preview Gain", + DEFAULT_USER_CROP to "Default User Crop", + DEPTH_FORMAT to "Depth Format", + DEPTH_NEAR to "Depth Near", + DEPTH_FAR to "Depth Far", + DEPTH_UNITS to "Depth Units", + DEPTH_MEASURE_TYPE to "Depth Measure Type", + ENHANCE_PARAMS to "Enhance Params", + PROFILE_GAIN_TABLE_MAP to "Profile Gain Table Map", + SEMANTIC_NAME to "Semantic Name", + SEMANTIC_INSTANCE_ID to "Semantic Instance ID", + CALIBRATION_ILLUMINANT_3 to "Calibration Illuminant 3", + CAMERA_CALIBRATION_3 to "Camera Calibration 3", + COLOR_MATRIX_3 to "Color Matrix 3", + FORWARD_MATRIX_3 to "Forward Matrix 3", + ILLUMINANT_DATA_1 to "Illuminant Data 1", + ILLUMINANT_DATA_2 to "Illuminant Data 2", + ILLUMINANT_DATA_3 to "Illuminant Data 3", + MASK_SUB_AREA to "Mask Sub Area", + PROFILE_HUE_SAT_MAP_DATA_3 to "Profile Hue Sat Map Data 3", + REDUCTION_MATRIX_3 to "Reduction Matrix 3", + RGB_TABLES to "RGB Tables", + ) + + val tags = tagNameMap.keys +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifInterfaceHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifInterfaceHelper.kt new file mode 100644 index 0000000..2f9b652 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifInterfaceHelper.kt @@ -0,0 +1,420 @@ +package deckers.thibault.aves.metadata + +import android.util.Log +import com.drew.lang.Rational +import com.drew.metadata.Directory +import com.drew.metadata.exif.ExifDirectoryBase +import com.drew.metadata.exif.ExifIFD0Directory +import com.drew.metadata.exif.ExifThumbnailDirectory +import com.drew.metadata.exif.GpsDirectory +import com.drew.metadata.exif.PanasonicRawIFD0Directory +import com.drew.metadata.exif.makernotes.OlympusCameraSettingsMakernoteDirectory +import com.drew.metadata.exif.makernotes.OlympusImageProcessingMakernoteDirectory +import com.drew.metadata.exif.makernotes.OlympusMakernoteDirectory +import deckers.thibault.aves.utils.LogUtils +import java.text.ParseException +import java.text.SimpleDateFormat +import java.util.Locale +import kotlin.math.abs +import kotlin.math.floor +import kotlin.math.roundToLong +import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface + +object ExifInterfaceHelper { + private val LOG_TAG = LogUtils.createTag<ExifInterfaceHelper>() + val DATETIME_FORMAT = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.ROOT) + val GPS_DATE_FORMAT = SimpleDateFormat("yyyy:MM:dd", Locale.ROOT) + val GPS_TIME_FORMAT = SimpleDateFormat("HH:mm:ss", Locale.ROOT) + + private const val PRECISION_ERROR_TOLERANCE = 1e-10 + + // ExifInterface always states it has the following attributes + // and returns "0" instead of "null" when they are actually missing + private val neverNullTags = listOf( + ExifInterface.TAG_IMAGE_LENGTH, + ExifInterface.TAG_IMAGE_WIDTH, + ExifInterface.TAG_LIGHT_SOURCE, + ExifInterface.TAG_ORIENTATION, + ) + + private fun isNeverNull(tag: String): Boolean = neverNullTags.contains(tag) + + private val baseTags: Map<String, TagMapper?> = mapOf( + ExifInterface.TAG_APERTURE_VALUE to TagMapper(ExifDirectoryBase.TAG_APERTURE, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_ARTIST to TagMapper(ExifDirectoryBase.TAG_ARTIST, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_BITS_PER_SAMPLE to TagMapper(ExifDirectoryBase.TAG_BITS_PER_SAMPLE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_BODY_SERIAL_NUMBER to TagMapper(ExifDirectoryBase.TAG_BODY_SERIAL_NUMBER, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_BRIGHTNESS_VALUE to TagMapper(ExifDirectoryBase.TAG_BRIGHTNESS_VALUE, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_CAMERA_OWNER_NAME to TagMapper(ExifDirectoryBase.TAG_CAMERA_OWNER_NAME, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_CFA_PATTERN to TagMapper(ExifDirectoryBase.TAG_CFA_PATTERN, DirType.EXIF_IFD0, TagFormat.BYTE), // spec format: UNDEFINED, e.g. [Red,Green][Green,Blue] + ExifInterface.TAG_COLOR_SPACE to TagMapper(ExifDirectoryBase.TAG_COLOR_SPACE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_COMPONENTS_CONFIGURATION to TagMapper(ExifDirectoryBase.TAG_COMPONENTS_CONFIGURATION, DirType.EXIF_IFD0, TagFormat.BYTE), // spec format: UNDEFINED, e.g. [Y,Cb,Cr] + ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL to TagMapper(ExifDirectoryBase.TAG_COMPRESSED_AVERAGE_BITS_PER_PIXEL, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_COMPRESSION to TagMapper(ExifDirectoryBase.TAG_COMPRESSION, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_CONTRAST to TagMapper(ExifDirectoryBase.TAG_CONTRAST, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_COPYRIGHT to TagMapper(ExifDirectoryBase.TAG_COPYRIGHT, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_CUSTOM_RENDERED to TagMapper(ExifDirectoryBase.TAG_CUSTOM_RENDERED, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_DATETIME to TagMapper(ExifDirectoryBase.TAG_DATETIME, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_DATETIME_DIGITIZED to TagMapper(ExifDirectoryBase.TAG_DATETIME_DIGITIZED, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_DATETIME_ORIGINAL to TagMapper(ExifDirectoryBase.TAG_DATETIME_ORIGINAL, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION to TagMapper(ExifDirectoryBase.TAG_DEVICE_SETTING_DESCRIPTION, DirType.EXIF_IFD0, TagFormat.UNDEFINED), + ExifInterface.TAG_DIGITAL_ZOOM_RATIO to TagMapper(ExifDirectoryBase.TAG_DIGITAL_ZOOM_RATIO, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_EXIF_VERSION to TagMapper(ExifDirectoryBase.TAG_EXIF_VERSION, DirType.EXIF_IFD0, TagFormat.UNDEFINED), + ExifInterface.TAG_EXPOSURE_BIAS_VALUE to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_BIAS, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_EXPOSURE_INDEX to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_INDEX, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_EXPOSURE_MODE to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_MODE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_EXPOSURE_PROGRAM to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_PROGRAM, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_EXPOSURE_TIME to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_TIME, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_FILE_SOURCE to TagMapper(ExifDirectoryBase.TAG_FILE_SOURCE, DirType.EXIF_IFD0, TagFormat.SHORT), // spec format: UNDEFINED + ExifInterface.TAG_FLASH to TagMapper(ExifDirectoryBase.TAG_FLASH, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_FLASHPIX_VERSION to TagMapper(ExifDirectoryBase.TAG_FLASHPIX_VERSION, DirType.EXIF_IFD0, TagFormat.UNDEFINED), + ExifInterface.TAG_FLASH_ENERGY to TagMapper(ExifDirectoryBase.TAG_FLASH_ENERGY, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_FOCAL_LENGTH to TagMapper(ExifDirectoryBase.TAG_FOCAL_LENGTH, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM to TagMapper(ExifDirectoryBase.TAG_35MM_FILM_EQUIV_FOCAL_LENGTH, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT to TagMapper(ExifDirectoryBase.TAG_FOCAL_PLANE_RESOLUTION_UNIT, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION to TagMapper(ExifDirectoryBase.TAG_FOCAL_PLANE_X_RESOLUTION, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION to TagMapper(ExifDirectoryBase.TAG_FOCAL_PLANE_Y_RESOLUTION, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_F_NUMBER to TagMapper(ExifDirectoryBase.TAG_FNUMBER, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_GAIN_CONTROL to TagMapper(ExifDirectoryBase.TAG_GAIN_CONTROL, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_GAMMA to TagMapper(ExifDirectoryBase.TAG_GAMMA, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_IMAGE_DESCRIPTION to TagMapper(ExifDirectoryBase.TAG_IMAGE_DESCRIPTION, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_IMAGE_LENGTH to TagMapper(ExifDirectoryBase.TAG_IMAGE_HEIGHT, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_IMAGE_UNIQUE_ID to TagMapper(ExifDirectoryBase.TAG_IMAGE_UNIQUE_ID, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_IMAGE_WIDTH to TagMapper(ExifDirectoryBase.TAG_IMAGE_WIDTH, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_INTEROPERABILITY_INDEX to TagMapper(ExifDirectoryBase.TAG_INTEROP_INDEX, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_ISO_SPEED to TagMapper(ExifDirectoryBase.TAG_ISO_SPEED, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_ISO_SPEED_LATITUDE_YYY to TagMapper(ExifDirectoryBase.TAG_ISO_SPEED_LATITUDE_YYY, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_ISO_SPEED_LATITUDE_ZZZ to TagMapper(ExifDirectoryBase.TAG_ISO_SPEED_LATITUDE_ZZZ, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_LENS_MAKE to TagMapper(ExifDirectoryBase.TAG_LENS_MAKE, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_LENS_MODEL to TagMapper(ExifDirectoryBase.TAG_LENS_MODEL, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_LENS_SERIAL_NUMBER to TagMapper(ExifDirectoryBase.TAG_LENS_SERIAL_NUMBER, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_LENS_SPECIFICATION to TagMapper(ExifDirectoryBase.TAG_LENS_SPECIFICATION, DirType.EXIF_IFD0, TagFormat.RATIONAL_ARRAY), + ExifInterface.TAG_LIGHT_SOURCE to TagMapper(ExifDirectoryBase.TAG_WHITE_BALANCE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_MAKE to TagMapper(ExifDirectoryBase.TAG_MAKE, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_MAKER_NOTE to TagMapper(ExifDirectoryBase.TAG_MAKERNOTE, DirType.EXIF_IFD0, TagFormat.UNDEFINED), + ExifInterface.TAG_MAX_APERTURE_VALUE to TagMapper(ExifDirectoryBase.TAG_MAX_APERTURE, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_METERING_MODE to TagMapper(ExifDirectoryBase.TAG_METERING_MODE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_MODEL to TagMapper(ExifDirectoryBase.TAG_MODEL, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_NEW_SUBFILE_TYPE to TagMapper(ExifDirectoryBase.TAG_NEW_SUBFILE_TYPE, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_OECF to TagMapper(ExifDirectoryBase.TAG_OPTO_ELECTRIC_CONVERSION_FUNCTION, DirType.EXIF_IFD0, TagFormat.UNDEFINED), + ExifInterface.TAG_OFFSET_TIME to TagMapper(ExifDirectoryBase.TAG_TIME_ZONE, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_OFFSET_TIME_DIGITIZED to TagMapper(ExifDirectoryBase.TAG_TIME_ZONE_DIGITIZED, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_OFFSET_TIME_ORIGINAL to TagMapper(ExifDirectoryBase.TAG_TIME_ZONE_ORIGINAL, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_ORIENTATION to TagMapper(ExifDirectoryBase.TAG_ORIENTATION, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY to TagMapper(ExifDirectoryBase.TAG_ISO_EQUIVALENT, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION to TagMapper(ExifDirectoryBase.TAG_PHOTOMETRIC_INTERPRETATION, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_PIXEL_X_DIMENSION to TagMapper(ExifDirectoryBase.TAG_EXIF_IMAGE_WIDTH, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_PIXEL_Y_DIMENSION to TagMapper(ExifDirectoryBase.TAG_EXIF_IMAGE_HEIGHT, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_PLANAR_CONFIGURATION to TagMapper(ExifDirectoryBase.TAG_PLANAR_CONFIGURATION, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_PRIMARY_CHROMATICITIES to TagMapper(ExifDirectoryBase.TAG_PRIMARY_CHROMATICITIES, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_RECOMMENDED_EXPOSURE_INDEX to TagMapper(ExifDirectoryBase.TAG_RECOMMENDED_EXPOSURE_INDEX, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_REFERENCE_BLACK_WHITE to TagMapper(ExifDirectoryBase.TAG_REFERENCE_BLACK_WHITE, DirType.EXIF_IFD0, TagFormat.RATIONAL_ARRAY), + ExifInterface.TAG_RELATED_SOUND_FILE to TagMapper(ExifDirectoryBase.TAG_RELATED_SOUND_FILE, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_RESOLUTION_UNIT to TagMapper(ExifDirectoryBase.TAG_RESOLUTION_UNIT, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_ROWS_PER_STRIP to TagMapper(ExifDirectoryBase.TAG_ROWS_PER_STRIP, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_SAMPLES_PER_PIXEL to TagMapper(ExifDirectoryBase.TAG_SAMPLES_PER_PIXEL, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SATURATION to TagMapper(ExifDirectoryBase.TAG_SATURATION, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SCENE_CAPTURE_TYPE to TagMapper(ExifDirectoryBase.TAG_SCENE_CAPTURE_TYPE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SCENE_TYPE to TagMapper(ExifDirectoryBase.TAG_SCENE_TYPE, DirType.EXIF_IFD0, TagFormat.SHORT), // spec format: UNDEFINED + ExifInterface.TAG_SENSING_METHOD to TagMapper(ExifDirectoryBase.TAG_SENSING_METHOD, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SENSITIVITY_TYPE to TagMapper(ExifDirectoryBase.TAG_SENSITIVITY_TYPE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SHARPNESS to TagMapper(ExifDirectoryBase.TAG_SHARPNESS, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SHUTTER_SPEED_VALUE to TagMapper(ExifDirectoryBase.TAG_SHUTTER_SPEED, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_SOFTWARE to TagMapper(ExifDirectoryBase.TAG_SOFTWARE, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE to TagMapper(ExifDirectoryBase.TAG_SPATIAL_FREQ_RESPONSE, DirType.EXIF_IFD0, TagFormat.UNDEFINED), + ExifInterface.TAG_SPECTRAL_SENSITIVITY to TagMapper(ExifDirectoryBase.TAG_SPECTRAL_SENSITIVITY, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_STANDARD_OUTPUT_SENSITIVITY to TagMapper(ExifDirectoryBase.TAG_STANDARD_OUTPUT_SENSITIVITY, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_STRIP_BYTE_COUNTS to TagMapper(ExifDirectoryBase.TAG_STRIP_BYTE_COUNTS, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_STRIP_OFFSETS to TagMapper(ExifDirectoryBase.TAG_STRIP_OFFSETS, DirType.EXIF_IFD0, TagFormat.LONG), + ExifInterface.TAG_SUBFILE_TYPE to TagMapper(ExifDirectoryBase.TAG_SUBFILE_TYPE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SUBJECT_AREA to TagMapper(ExifDirectoryBase.TAG_SUBJECT_LOCATION_TIFF_EP, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SUBJECT_DISTANCE to TagMapper(ExifDirectoryBase.TAG_SUBJECT_DISTANCE, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_SUBJECT_DISTANCE_RANGE to TagMapper(ExifDirectoryBase.TAG_SUBJECT_DISTANCE_RANGE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SUBJECT_LOCATION to TagMapper(ExifDirectoryBase.TAG_SUBJECT_LOCATION, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_SUBSEC_TIME to TagMapper(ExifDirectoryBase.TAG_SUBSECOND_TIME, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_SUBSEC_TIME_DIGITIZED to TagMapper(ExifDirectoryBase.TAG_SUBSECOND_TIME_DIGITIZED, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_SUBSEC_TIME_ORIGINAL to TagMapper(ExifDirectoryBase.TAG_SUBSECOND_TIME_ORIGINAL, DirType.EXIF_IFD0, TagFormat.ASCII), + ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH to TagMapper(ExifDirectoryBase.TAG_IMAGE_HEIGHT, DirType.EXIF_IFD0, TagFormat.LONG), // IFD_THUMBNAIL_TAGS 0x0101 + ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH to TagMapper(ExifDirectoryBase.TAG_IMAGE_WIDTH, DirType.EXIF_IFD0, TagFormat.LONG), // IFD_THUMBNAIL_TAGS 0x0100 + ExifInterface.TAG_TRANSFER_FUNCTION to TagMapper(ExifDirectoryBase.TAG_TRANSFER_FUNCTION, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_USER_COMMENT to TagMapper(ExifDirectoryBase.TAG_USER_COMMENT, DirType.EXIF_IFD0, TagFormat.COMMENT), + ExifInterface.TAG_WHITE_BALANCE to TagMapper(ExifDirectoryBase.TAG_WHITE_BALANCE, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_WHITE_POINT to TagMapper(ExifDirectoryBase.TAG_WHITE_POINT, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_X_RESOLUTION to TagMapper(ExifDirectoryBase.TAG_X_RESOLUTION, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_Y_CB_CR_COEFFICIENTS to TagMapper(ExifDirectoryBase.TAG_YCBCR_COEFFICIENTS, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ExifInterface.TAG_Y_CB_CR_POSITIONING to TagMapper(ExifDirectoryBase.TAG_YCBCR_POSITIONING, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING to TagMapper(ExifDirectoryBase.TAG_YCBCR_SUBSAMPLING, DirType.EXIF_IFD0, TagFormat.SHORT), + ExifInterface.TAG_Y_RESOLUTION to TagMapper(ExifDirectoryBase.TAG_Y_RESOLUTION, DirType.EXIF_IFD0, TagFormat.RATIONAL), + ) + + private val thumbnailTags: Map<String, TagMapper?> = mapOf( + ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT to TagMapper(ExifThumbnailDirectory.TAG_THUMBNAIL_OFFSET, DirType.EXIF_THUMBNAIL, TagFormat.LONG), // IFD_TIFF_TAGS or IFD_THUMBNAIL_TAGS 0x0201 + ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH to TagMapper(ExifThumbnailDirectory.TAG_THUMBNAIL_LENGTH, DirType.EXIF_THUMBNAIL, TagFormat.LONG), // IFD_TIFF_TAGS or IFD_THUMBNAIL_TAGS 0x0202 + ) + + private val gpsTags: Map<String, TagMapper?> = mapOf( + ExifInterface.TAG_GPS_ALTITUDE to TagMapper(GpsDirectory.TAG_ALTITUDE, DirType.GPS, TagFormat.RATIONAL), + ExifInterface.TAG_GPS_ALTITUDE_REF to TagMapper(GpsDirectory.TAG_ALTITUDE_REF, DirType.GPS, TagFormat.BYTE), + ExifInterface.TAG_GPS_AREA_INFORMATION to TagMapper(GpsDirectory.TAG_AREA_INFORMATION, DirType.GPS, TagFormat.COMMENT), + ExifInterface.TAG_GPS_DATESTAMP to TagMapper(GpsDirectory.TAG_DATE_STAMP, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_DEST_BEARING to TagMapper(GpsDirectory.TAG_DEST_BEARING, DirType.GPS, TagFormat.RATIONAL), + ExifInterface.TAG_GPS_DEST_BEARING_REF to TagMapper(GpsDirectory.TAG_DEST_BEARING_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_DEST_DISTANCE to TagMapper(GpsDirectory.TAG_DEST_DISTANCE, DirType.GPS, TagFormat.RATIONAL), + ExifInterface.TAG_GPS_DEST_DISTANCE_REF to TagMapper(GpsDirectory.TAG_DEST_DISTANCE_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_DEST_LATITUDE to TagMapper(GpsDirectory.TAG_DEST_LATITUDE, DirType.GPS, TagFormat.RATIONAL_ARRAY), + ExifInterface.TAG_GPS_DEST_LATITUDE_REF to TagMapper(GpsDirectory.TAG_DEST_LATITUDE_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_DEST_LONGITUDE to TagMapper(GpsDirectory.TAG_DEST_LONGITUDE, DirType.GPS, TagFormat.RATIONAL_ARRAY), + ExifInterface.TAG_GPS_DEST_LONGITUDE_REF to TagMapper(GpsDirectory.TAG_DEST_LONGITUDE_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_DIFFERENTIAL to TagMapper(GpsDirectory.TAG_DIFFERENTIAL, DirType.GPS, TagFormat.SHORT), + ExifInterface.TAG_GPS_DOP to TagMapper(GpsDirectory.TAG_DOP, DirType.GPS, TagFormat.RATIONAL), + ExifInterface.TAG_GPS_H_POSITIONING_ERROR to TagMapper(GpsDirectory.TAG_H_POSITIONING_ERROR, DirType.GPS, TagFormat.RATIONAL), + ExifInterface.TAG_GPS_IMG_DIRECTION to TagMapper(GpsDirectory.TAG_IMG_DIRECTION, DirType.GPS, TagFormat.RATIONAL), + ExifInterface.TAG_GPS_IMG_DIRECTION_REF to TagMapper(GpsDirectory.TAG_IMG_DIRECTION_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_LATITUDE to TagMapper(GpsDirectory.TAG_LATITUDE, DirType.GPS, TagFormat.RATIONAL_ARRAY), + ExifInterface.TAG_GPS_LATITUDE_REF to TagMapper(GpsDirectory.TAG_LATITUDE_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_LONGITUDE to TagMapper(GpsDirectory.TAG_LONGITUDE, DirType.GPS, TagFormat.RATIONAL_ARRAY), + ExifInterface.TAG_GPS_LONGITUDE_REF to TagMapper(GpsDirectory.TAG_LONGITUDE_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_MAP_DATUM to TagMapper(GpsDirectory.TAG_MAP_DATUM, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_MEASURE_MODE to TagMapper(GpsDirectory.TAG_MEASURE_MODE, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_PROCESSING_METHOD to TagMapper(GpsDirectory.TAG_PROCESSING_METHOD, DirType.GPS, TagFormat.COMMENT), + ExifInterface.TAG_GPS_SATELLITES to TagMapper(GpsDirectory.TAG_SATELLITES, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_SPEED to TagMapper(GpsDirectory.TAG_SPEED, DirType.GPS, TagFormat.RATIONAL), + ExifInterface.TAG_GPS_SPEED_REF to TagMapper(GpsDirectory.TAG_SPEED_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_STATUS to TagMapper(GpsDirectory.TAG_STATUS, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_TIMESTAMP to TagMapper(GpsDirectory.TAG_TIME_STAMP, DirType.GPS, TagFormat.RATIONAL_ARRAY), + ExifInterface.TAG_GPS_TRACK to TagMapper(GpsDirectory.TAG_TRACK, DirType.GPS, TagFormat.RATIONAL), + ExifInterface.TAG_GPS_TRACK_REF to TagMapper(GpsDirectory.TAG_TRACK_REF, DirType.GPS, TagFormat.ASCII), + ExifInterface.TAG_GPS_VERSION_ID to TagMapper(GpsDirectory.TAG_VERSION_ID, DirType.GPS, TagFormat.BYTE), + ) + + private val xmpTags: Map<String, TagMapper?> = mapOf( + ExifInterface.TAG_XMP to null, // IFD_TIFF_TAGS 0x02BC + ) + + private val rawTags: Map<String, TagMapper?> = mapOf( + // DNG + ExifInterface.TAG_DEFAULT_CROP_SIZE to null, // IFD_EXIF_TAGS 0xC620 + ExifInterface.TAG_DNG_VERSION to null, // IFD_EXIF_TAGS 0xC612 + // ORF + ExifInterface.TAG_ORF_ASPECT_FRAME to TagMapper(OlympusImageProcessingMakernoteDirectory.TagAspectFrame, DirType.OIPM, TagFormat.LONG), // ORF_IMAGE_PROCESSING_TAGS 0x1113 + ExifInterface.TAG_ORF_PREVIEW_IMAGE_LENGTH to TagMapper(OlympusCameraSettingsMakernoteDirectory.TagPreviewImageLength, DirType.OCSM, TagFormat.LONG), // ORF_CAMERA_SETTINGS_TAGS 0x0102 + ExifInterface.TAG_ORF_PREVIEW_IMAGE_START to TagMapper(OlympusCameraSettingsMakernoteDirectory.TagPreviewImageStart, DirType.OCSM, TagFormat.LONG), // ORF_CAMERA_SETTINGS_TAGS 0x0101 + ExifInterface.TAG_ORF_THUMBNAIL_IMAGE to TagMapper(OlympusMakernoteDirectory.TAG_THUMBNAIL_IMAGE, DirType.OM, TagFormat.UNDEFINED), // ORF_MAKER_NOTE_TAGS 0x0100 + // RW2 + ExifInterface.TAG_RW2_ISO to TagMapper(PanasonicRawIFD0Directory.TagIso, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0017 + ExifInterface.TAG_RW2_JPG_FROM_RAW to TagMapper(PanasonicRawIFD0Directory.TagJpgFromRaw, DirType.PRIFD0, TagFormat.UNDEFINED), // IFD_TIFF_TAGS 0x002E + ExifInterface.TAG_RW2_SENSOR_BOTTOM_BORDER to TagMapper(PanasonicRawIFD0Directory.TagSensorBottomBorder, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0006 + ExifInterface.TAG_RW2_SENSOR_LEFT_BORDER to TagMapper(PanasonicRawIFD0Directory.TagSensorLeftBorder, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0005 + ExifInterface.TAG_RW2_SENSOR_RIGHT_BORDER to TagMapper(PanasonicRawIFD0Directory.TagSensorRightBorder, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0007 + ExifInterface.TAG_RW2_SENSOR_TOP_BORDER to TagMapper(PanasonicRawIFD0Directory.TagSensorTopBorder, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0004 + ) + + // list of known ExifInterface tags (as of androidx.exifinterface:exifinterface:1.3.0) + // mapped to metadata-extractor tags (as of v2.14.0) + val allTags: Map<String, TagMapper?> = hashMapOf<String, TagMapper?>( + ).apply { + putAll(baseTags) + putAll(thumbnailTags) + putAll(gpsTags) + putAll(xmpTags) + putAll(rawTags) + } + + fun describeAll(exif: ExifInterface): Map<String, Map<String, String>> { + // initialize metadata-extractor directories that we will fill + // by tags converted from the ExifInterface attributes + // so that we can rely on metadata-extractor descriptions + val dirs = DirType.entries.associateWith { it.createDirectory() } + + // exclude Exif directory when it only includes image size + val isUselessExif = fun(it: Map<String, String>): Boolean { + return it.size == 2 && it.containsKey("Image Height") && it.containsKey("Image Width") + } + + return HashMap<String, Map<String, String>>().apply { + put("Exif", describeDir(exif, dirs, baseTags).takeUnless(isUselessExif) ?: hashMapOf()) + put("Exif Thumbnail", describeDir(exif, dirs, thumbnailTags)) + put(Metadata.DIR_GPS, describeDir(exif, dirs, gpsTags)) + put(Metadata.DIR_XMP, describeDir(exif, dirs, xmpTags)) + put("Exif Raw", describeDir(exif, dirs, rawTags)) + }.filterValues { it.isNotEmpty() } + } + + private fun describeDir(exif: ExifInterface, metadataExtractorDirs: Map<DirType, Directory>, tags: Map<String, TagMapper?>): Map<String, String> { + val dirMap = HashMap<String, String>() + + fillMetadataExtractorDir(exif, metadataExtractorDirs, tags) + + for ((exifInterfaceTag, mapper) in tags) { + if (exif.hasAttribute(exifInterfaceTag)) { + val value: String? = exif.getAttribute(exifInterfaceTag) + if (value != null && !(value == "0" && isNeverNull(exifInterfaceTag))) { + if (mapper != null) { + val dir = metadataExtractorDirs[mapper.dirType] ?: error("Directory type ${mapper.dirType} does not have a matching Directory instance") + val type = mapper.type + val tagName = dir.getTagName(type) + + val description: String? = dir.getDescription(type) + if (description != null) { + dirMap[tagName] = description + } else { + Log.w(LOG_TAG, "failed to get description for tag=$exifInterfaceTag value=$value") + dirMap[tagName] = value + } + } else { + dirMap[exifInterfaceTag] = value + } + } + } + } + return dirMap + } + + private fun fillMetadataExtractorDir(exif: ExifInterface, metadataExtractorDirs: Map<DirType, Directory>, tags: Map<String, TagMapper?>) { + for ((exifInterfaceTag, mapper) in tags) { + if (exif.hasAttribute(exifInterfaceTag) && mapper != null) { + val value: String? = exif.getAttribute(exifInterfaceTag) + if (value != null && (value != "0" || !neverNullTags.contains(exifInterfaceTag))) { + val obj: Any? = when (mapper.format) { + TagFormat.ASCII, TagFormat.COMMENT, TagFormat.UNDEFINED -> value + TagFormat.BYTE -> exif.getAttributeBytes(exifInterfaceTag) + TagFormat.SHORT -> value.toShortOrNull() + TagFormat.LONG -> value.toLongOrNull() + TagFormat.RATIONAL -> toRational(value) + TagFormat.RATIONAL_ARRAY -> toRationalArray(value) + null -> null + } + if (obj != null) { + val dir = metadataExtractorDirs[mapper.dirType] ?: error("Directory type ${mapper.dirType} does not have a matching Directory instance") + dir.setObject(mapper.type, obj) + } + } + } + } + } + + private fun toRational(s: String?): Rational? { + s ?: return null + + // e.g. "12345/100" to Rational(12345, 100) + val parts = s.split("/") + if (parts.size == 2) { + val numerator = parts[0].toLongOrNull() ?: return null + val denominator = parts[1].toLongOrNull() ?: return null + return Rational(numerator, denominator) + } + + var d = s.toDoubleOrNull() ?: return null + if (d == 0.0) return Rational(0, 1) + + // e.g. "0.02564102564102564" to Rational(1, 39) + if (d < 1) { + val numerator = 1L + val f = numerator / d + val denominator = f.roundToLong() + if (abs(f - denominator) < PRECISION_ERROR_TOLERANCE) { + return Rational(numerator, denominator) + } + } + + // e.g. "123.45" to Rational(12345, 100) + var denominator: Long = 1 + while (d != floor(d)) { + denominator *= 10 + d *= 10 + if (denominator > 10000000000) { + // let's not get irrational + return null + } + } + val numerator: Long = d.roundToLong() + return Rational(numerator, denominator) + } + + private fun toRationalArray(s: String?): Array<Rational>? { + s ?: return null + val list = s.split(",").mapNotNull { toRational(it) } + if (list.isEmpty()) return null + return list.toTypedArray() + } + + // extensions + + fun ExifInterface.getSafeInt(tag: String, acceptZero: Boolean = true, save: (value: Int) -> Unit) { + if (this.hasAttribute(tag)) { + val value = this.getAttributeInt(tag, 0) + if (acceptZero || value != 0) { + save(value) + } + } + } + + fun ExifInterface.getSafeDouble(tag: String, save: (value: Double) -> Unit) { + if (this.hasAttribute(tag)) { + val value = this.getAttributeDouble(tag, Double.NaN) + if (!value.isNaN()) { + save(value) + } + } + } + + fun ExifInterface.getSafeRational(tag: String, save: (value: Rational) -> Unit) { + if (this.hasAttribute(tag)) { + val value = toRational(this.getAttribute(tag)) + if (value != null) { + save(value) + } + } + } + + fun ExifInterface.getSafeDateMillis(tag: String, subSecTag: String?, save: (value: Long) -> Unit) { + if (this.hasAttribute(tag)) { + val dateString = this.getAttribute(tag) + if (dateString != null) { + try { + DATETIME_FORMAT.parse(dateString)?.let { date -> + var dateMillis = date.time + if (subSecTag != null && this.hasAttribute(subSecTag)) { + dateMillis += Metadata.parseSubSecond(this.getAttribute(subSecTag)) + } + save(dateMillis) + } + } catch (e: ParseException) { + Log.w(LOG_TAG, "failed to parse date=$dateString", e) + } + } + } + } +} + +enum class DirType { + EXIF_IFD0 { + override fun createDirectory() = ExifIFD0Directory() + }, + EXIF_THUMBNAIL { + override fun createDirectory() = ExifThumbnailDirectory(0) + }, + GPS { + override fun createDirectory() = GpsDirectory() + }, + OIPM { + override fun createDirectory() = OlympusImageProcessingMakernoteDirectory() + }, + OCSM { + override fun createDirectory() = OlympusCameraSettingsMakernoteDirectory() + }, + OM { + override fun createDirectory() = OlympusMakernoteDirectory() + }, + PRIFD0 { + override fun createDirectory() = PanasonicRawIFD0Directory() + }; + + abstract fun createDirectory(): Directory +} + +enum class TagFormat { + ASCII, COMMENT, BYTE, SHORT, LONG, RATIONAL, RATIONAL_ARRAY, UNDEFINED +} + +data class TagMapper(val type: Int, val dirType: DirType, val format: TagFormat?) diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifTags.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifTags.kt new file mode 100644 index 0000000..723bac0 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifTags.kt @@ -0,0 +1,61 @@ +package deckers.thibault.aves.metadata + +/* +Exif tags missing from `metadata-extractor` + +Photoshop +https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ +https://www.adobe.io/content/dam/udp/en/open/standards/tiff/TIFFphotoshop.pdf + */ +object ExifTags { + private const val PROCESSING_SOFTWARE = 0x000b + private const val X_POSITION = 0x011e + private const val Y_POSITION = 0x011f + private const val T4_OPTIONS = 0x0124 + private const val T6_OPTIONS = 0x0125 + private const val COLOR_MAP = 0x0140 + private const val EXTRA_SAMPLES = 0x0152 + private const val SAMPLE_FORMAT = 0x0153 + private const val SMIN_SAMPLE_VALUE = 0x0154 + private const val SMAX_SAMPLE_VALUE = 0x0155 + private const val SONY_RAW_FILE_TYPE = 0x7000 + private const val SONY_TONE_CURVE = 0x7010 + private const val MATTEING = 0x80e3 + + // sensing method (0x9217) redundant with sensing method (0xA217) + private const val SENSING_METHOD = 0x9217 + private const val IMAGE_SOURCE_DATA = 0x935c + private const val GDAL_METADATA = 0xa480 + private const val GDAL_NO_DATA = 0xa481 + + private val tagNameMap = hashMapOf( + PROCESSING_SOFTWARE to "Processing Software", + X_POSITION to "X Position", + Y_POSITION to "Y Position", + T4_OPTIONS to "T4 Options", + T6_OPTIONS to "T6 Options", + COLOR_MAP to "Color Map", + EXTRA_SAMPLES to "Extra Samples", + SAMPLE_FORMAT to "Sample Format", + SMIN_SAMPLE_VALUE to "S Min Sample Value", + SMAX_SAMPLE_VALUE to "S Max Sample Value", + SONY_RAW_FILE_TYPE to "Sony Raw File Type", + SONY_TONE_CURVE to "Sony Tone Curve", + MATTEING to "Matteing", + SENSING_METHOD to "Sensing Method (0x9217)", + IMAGE_SOURCE_DATA to "Image Source Data", + GDAL_METADATA to "GDAL Metadata", + GDAL_NO_DATA to "GDAL No Data", + ).apply { + putAll(DngTags.tagNameMap) + putAll(ExifGeoTiffTags.tagNameMap) + } + + fun isDngTag(tag: Int) = DngTags.tags.contains(tag) + + fun isGeoTiffTag(tag: Int) = ExifGeoTiffTags.tags.contains(tag) + + fun getTagName(tag: Int): String? { + return tagNameMap[tag] + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/GeoTiffTags.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/GeoTiffTags.kt new file mode 100644 index 0000000..e31cca4 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/GeoTiffTags.kt @@ -0,0 +1,116 @@ +package deckers.thibault.aves.metadata + +object GeoTiffKeys { + // not a standard tag + const val GEOTIFF_VERSION = 0 + + private const val MODEL_TYPE = 0x0400 + private const val RASTER_TYPE = 0x0401 + private const val CITATION = 0x0402 + private const val GEOG_TYPE = 0x0800 + private const val GEOG_CITATION = 0x0801 + private const val GEOG_GEODETIC_DATUM = 0x0802 + private const val GEOG_LINEAR_UNITS = 0x0804 + private const val GEOG_ANGULAR_UNITS = 0x0806 + private const val GEOG_ELLIPSOID = 0x0808 + private const val GEOG_SEMI_MAJOR_AXIS = 0x0809 + private const val GEOG_SEMI_MINOR_AXIS = 0x080a + private const val GEOG_INV_FLATTENING = 0x080b + private const val PROJ_CS_TYPE = 0x0c00 + private const val PROJ_CS_CITATION = 0x0c01 + private const val PROJECTION = 0x0c02 + private const val PROJ_COORD_TRANS = 0x0c03 + private const val PROJ_LINEAR_UNITS = 0x0c04 + private const val PROJ_STD_PARALLEL_1 = 0x0c06 + private const val PROJ_STD_PARALLEL_2 = 0x0c07 + private const val PROJ_NAT_ORIGIN_LONG = 0x0c08 + private const val PROJ_NAT_ORIGIN_LAT = 0x0c09 + private const val PROJ_FALSE_EASTING = 0x0c0a + private const val PROJ_FALSE_NORTHING = 0x0c0b + private const val PROJ_SCALE_AT_NAT_ORIGIN = 0x0c14 + private const val PROJ_AZIMUTH_ANGLE = 0x0c16 + private const val VERTICAL_UNITS = 0x1003 + + private val tagNameMap = hashMapOf( + GEOTIFF_VERSION to "GeoTIFF Version", + MODEL_TYPE to "Model Type", + RASTER_TYPE to "Raster Type", + CITATION to "Citation", + GEOG_TYPE to "Geographic Type", + GEOG_CITATION to "Geographic Citation", + GEOG_GEODETIC_DATUM to "Geographic Geodetic Datum", + GEOG_LINEAR_UNITS to "Geographic Linear Units", + GEOG_ANGULAR_UNITS to "Geographic Angular Units", + GEOG_ELLIPSOID to "Geographic Ellipsoid", + GEOG_SEMI_MAJOR_AXIS to "Semi-major axis", + GEOG_SEMI_MINOR_AXIS to "Semi-minor axis", + GEOG_INV_FLATTENING to "Inv. Flattening", + PROJ_CS_TYPE to "Projected Coordinate System Type", + PROJ_CS_CITATION to "Projected Coordinate System Citation", + PROJECTION to "Projection", + PROJ_COORD_TRANS to "Projected Coordinate Transform", + PROJ_LINEAR_UNITS to "Projection Linear Units", + PROJ_STD_PARALLEL_1 to "Projection Standard Parallel 1", + PROJ_STD_PARALLEL_2 to "Projection Standard Parallel 2", + PROJ_NAT_ORIGIN_LONG to "Projection Natural Origin Longitude", + PROJ_NAT_ORIGIN_LAT to "Projection Natural Origin Latitude", + PROJ_FALSE_EASTING to "Projection False Easting", + PROJ_FALSE_NORTHING to "Projection False Northing", + PROJ_SCALE_AT_NAT_ORIGIN to "Projection Scale at Natural Origin", + PROJ_AZIMUTH_ANGLE to "Projection Azimuth Angle", + VERTICAL_UNITS to "Vertical Units", + ) + + fun getTagName(tag: Int): String? { + return tagNameMap[tag] + } +} + +object ExifGeoTiffTags { + // ModelPixelScaleTag (optional) + // Tag = 33550 (830E.H) + // Type = DOUBLE + // Count = 3 + const val TAG_MODEL_PIXEL_SCALE = 0x830e + + // ModelTiePointTag (conditional) + // Tag = 33922 (8482.H) + // Type = DOUBLE + // Count = 6*K, K = number of tie points + const val TAG_MODEL_TIE_POINT = 0x8482 + + // ModelTransformationTag (conditional) + // Tag = 34264 (85D8.H) + // Type = DOUBLE + // Count = 16 + const val TAG_MODEL_TRANSFORMATION = 0x85d8 + + // GeoKeyDirectoryTag (mandatory) + // Tag = 34735 (87AF.H) + // Type = UNSIGNED SHORT + // Count = variable, >= 4 + const val TAG_GEO_KEY_DIRECTORY = 0x87af + + // GeoDoubleParamsTag (optional) + // Tag = 34736 (87BO.H) + // Type = DOUBLE + // Count = variable + const val TAG_GEO_DOUBLE_PARAMS = 0x87b0 + + // GeoAsciiParamsTag (optional) + // Tag = 34737 (87B1.H) + // Type = ASCII + // Count = variable + const val TAG_GEO_ASCII_PARAMS = 0x87b1 + + val tagNameMap = hashMapOf( + TAG_GEO_ASCII_PARAMS to "Geo Ascii Params", + TAG_GEO_DOUBLE_PARAMS to "Geo Double Params", + TAG_GEO_KEY_DIRECTORY to "Geo Key Directory", + TAG_MODEL_PIXEL_SCALE to "Model Pixel Scale", + TAG_MODEL_TIE_POINT to "Model Tie Points", + TAG_MODEL_TRANSFORMATION to "Model Transformation", + ) + + val tags = tagNameMap.keys +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MediaMetadataRetrieverHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MediaMetadataRetrieverHelper.kt new file mode 100644 index 0000000..fd840b9 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MediaMetadataRetrieverHelper.kt @@ -0,0 +1,187 @@ +package deckers.thibault.aves.metadata + +import android.media.MediaFormat +import android.media.MediaMetadataRetriever +import android.os.Build +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone + +object MediaMetadataRetrieverHelper { + val allKeys = hashMapOf( + MediaMetadataRetriever.METADATA_KEY_ALBUM to "Album", + MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST to "Album Artist", + MediaMetadataRetriever.METADATA_KEY_ARTIST to "Artist", + MediaMetadataRetriever.METADATA_KEY_AUTHOR to "Author", + MediaMetadataRetriever.METADATA_KEY_BITRATE to "Bitrate", + MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER to "CD Track Number", + MediaMetadataRetriever.METADATA_KEY_COMPILATION to "Compilation", + MediaMetadataRetriever.METADATA_KEY_COMPOSER to "Composer", + MediaMetadataRetriever.METADATA_KEY_DATE to "Date", + MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER to "Disc Number", + MediaMetadataRetriever.METADATA_KEY_DURATION to "Duration", + MediaMetadataRetriever.METADATA_KEY_GENRE to "Genre", + MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO to "Has Audio", + MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO to "Has Video", + MediaMetadataRetriever.METADATA_KEY_LOCATION to "Location", + MediaMetadataRetriever.METADATA_KEY_MIMETYPE to "MIME Type", + MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS to "Number of Tracks", + MediaMetadataRetriever.METADATA_KEY_TITLE to "Title", + MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT to "Video Height", + MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH to "Video Width", + MediaMetadataRetriever.METADATA_KEY_WRITER to "Writer", + MediaMetadataRetriever.METADATA_KEY_YEAR to "Year", + MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION to "Video Rotation", + ).apply { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + put(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE, "Capture Framerate") + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + putAll( + hashMapOf( + MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE to "Has Image", + MediaMetadataRetriever.METADATA_KEY_IMAGE_COUNT to "Image Count", + MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT to "Image Height", + MediaMetadataRetriever.METADATA_KEY_IMAGE_PRIMARY to "Image Primary", + MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION to "Image Rotation", + MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH to "Image Width", + MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT to "Video Frame Count", + ) + ) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + putAll( + hashMapOf( + MediaMetadataRetriever.METADATA_KEY_EXIF_LENGTH to "Exif Length", + MediaMetadataRetriever.METADATA_KEY_EXIF_OFFSET to "Exif Offset", + ) + ) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + putAll( + hashMapOf( + MediaMetadataRetriever.METADATA_KEY_COLOR_RANGE to "Color Range", + MediaMetadataRetriever.METADATA_KEY_COLOR_STANDARD to "Color Standard", + MediaMetadataRetriever.METADATA_KEY_COLOR_TRANSFER to "Color Transfer", + ) + ) + } + } + + private val durationFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.ROOT).apply { timeZone = TimeZone.getTimeZone("UTC") } + + // extensions + + fun MediaMetadataRetriever.getSafeString(tag: Int, save: (value: String) -> Unit) { + val value = this.extractMetadata(tag) + if (value != null) save(value) + } + + fun MediaMetadataRetriever.getSafeInt(tag: Int, save: (value: Int) -> Unit) { + val value = this.extractMetadata(tag)?.toIntOrNull() + if (value != null) save(value) + } + + fun MediaMetadataRetriever.getSafeLong(tag: Int, save: (value: Long) -> Unit) { + val value = this.extractMetadata(tag)?.toLongOrNull() + if (value != null) save(value) + } + + fun MediaMetadataRetriever.getSafeDateMillis(tag: Int, save: (value: Long) -> Unit) { + val dateString = this.extractMetadata(tag) + val dateMillis = Metadata.parseVideoMetadataDate(dateString) + // some entries have an invalid default date (19040101T000000.000Z) that is before Epoch time + if (dateMillis > 0) save(dateMillis) + } + + private fun formatBitrate(size: Long): String { + val divider = 1000 + val symbol = "bit/s" + + if (size < divider) return "$size $symbol" + if (size < divider * divider) return "${String.format(Locale.getDefault(), "%.2f", size.toDouble() / divider)} K$symbol" + return "${String.format(Locale.getDefault(), "%.2f", size.toDouble() / divider / divider)} M$symbol" + } + + fun MediaMetadataRetriever.getSafeDescription(tag: Int, save: (value: String) -> Unit) { + val value = this.extractMetadata(tag) + if (value != null) { + when (tag) { + // format + MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION, + MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION -> "$value°" + + MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT, MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH, + MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT, MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH -> "$value pixels" + + MediaMetadataRetriever.METADATA_KEY_BITRATE -> { + val bitrate = value.toLongOrNull() ?: 0 + if (bitrate > 0) formatBitrate(bitrate) else null + } + + MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE -> { + val framerate = value.toDoubleOrNull() ?: 0.0 + if (framerate > 0.0) "$framerate" else null + } + + MediaMetadataRetriever.METADATA_KEY_DURATION -> { + val dateMillis = value.toLongOrNull() ?: 0 + if (dateMillis > 0) durationFormat.format(Date(dateMillis)) else null + } + + MediaMetadataRetriever.METADATA_KEY_COLOR_RANGE -> { + when (value.toIntOrNull()) { + MediaFormat.COLOR_RANGE_FULL -> "Full" + MediaFormat.COLOR_RANGE_LIMITED -> "Limited" + else -> value + } + } + + MediaMetadataRetriever.METADATA_KEY_COLOR_STANDARD -> { + when (value.toIntOrNull()) { + MediaFormat.COLOR_STANDARD_BT709 -> "BT.709" + MediaFormat.COLOR_STANDARD_BT601_PAL -> "BT.601 625 (PAL)" + MediaFormat.COLOR_STANDARD_BT601_NTSC -> "BT.601 525 (NTSC)" + MediaFormat.COLOR_STANDARD_BT2020 -> "BT.2020" + else -> value + } + } + + MediaMetadataRetriever.METADATA_KEY_COLOR_TRANSFER -> { + when (value.toIntOrNull()) { + MediaFormat.COLOR_TRANSFER_LINEAR -> "Linear" + MediaFormat.COLOR_TRANSFER_SDR_VIDEO -> "SMPTE 170M" + MediaFormat.COLOR_TRANSFER_ST2084 -> "SMPTE ST 2084" + MediaFormat.COLOR_TRANSFER_HLG -> "ARIB STD-B67 (HLG)" + else -> value + } + } + // hide default or invalid values + MediaMetadataRetriever.METADATA_KEY_COMPILATION, + MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER, + MediaMetadataRetriever.METADATA_KEY_YEAR -> if (value != "0") value else null + + MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER -> if (value != "0/0") value else null + MediaMetadataRetriever.METADATA_KEY_DATE -> { + val dateMillis = Metadata.parseVideoMetadataDate(value) + // some entries have an invalid default date (19040101T000000.000Z) that is before Epoch time + if (dateMillis > 0) value else null + } + // hide + MediaMetadataRetriever.METADATA_KEY_LOCATION, + MediaMetadataRetriever.METADATA_KEY_MIMETYPE -> null + // as is + else -> value + }?.let { save(it) } + } + } + + fun MediaFormat.getSafeInt(key: String, save: (value: Int) -> Unit) { + if (this.containsKey(key)) save(this.getInteger(key)) + } + + fun MediaFormat.getSafeLong(key: String, save: (value: Long) -> Unit) { + if (this.containsKey(key)) save(this.getLong(key)) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Metadata.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Metadata.kt new file mode 100644 index 0000000..0d1dbff --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Metadata.kt @@ -0,0 +1,186 @@ +package deckers.thibault.aves.metadata + +import android.content.Context +import android.net.Uri +import android.util.Log +import deckers.thibault.aves.utils.FileUtils.transferFrom +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.StorageUtils +import java.io.File +import java.io.InputStream +import java.text.ParseException +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone +import java.util.regex.Pattern +import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface + +object Metadata { + private val LOG_TAG = LogUtils.createTag<Metadata>() + + const val IPTC_MARKER_BYTE: Byte = 0x1c + + // Pattern to extract latitude & longitude from a video location tag (cf ISO 6709) + // Examples: + // "+37.5090+127.0243/" (Samsung) + // "+51.3328-000.7053+113.474/" (Apple) + val VIDEO_LOCATION_PATTERN: Pattern = Pattern.compile("([+-][.0-9]+)([+-][.0-9]+).*") + + private val VIDEO_DATE_SUBSECOND_PATTERN = Pattern.compile("(\\d{6})(\\.\\d+)") + private val VIDEO_TIME_ZONE_PATTERN = Pattern.compile("(Z|[+-]\\d{4})$") + + // directory names, as shown when listing all metadata + const val DIR_GPS = "GPS" // from metadata-extractor + const val DIR_XMP = "XMP" // from metadata-extractor + const val DIR_MEDIA = "Media" // custom + const val DIR_COVER_ART = "Cover" // custom + const val DIR_DNG = "DNG" // custom + const val DIR_EXIF_GEOTIFF = "GeoTIFF" // custom + const val DIR_PNG_TEXTUAL_DATA = "PNG Textual Data" // custom + const val DIR_MP4_USER_DATA = "User Data" // custom + + // types of metadata + const val TYPE_COMMENT = "comment" + const val TYPE_EXIF = "exif" + const val TYPE_ICC_PROFILE = "icc_profile" + const val TYPE_IPTC = "iptc" + const val TYPE_JFIF = "jfif" + const val TYPE_JPEG_ADOBE = "jpeg_adobe" + const val TYPE_JPEG_DUCKY = "jpeg_ducky" + const val TYPE_MP4 = "mp4" + const val TYPE_PHOTOSHOP_IRB = "photoshop_irb" + const val TYPE_XMP = "xmp" + + // interpret EXIF code to angle (0, 90, 180 or 270 degrees) + fun getRotationDegreesForExifCode(exifOrientation: Int): Int = when (exifOrientation) { + ExifInterface.ORIENTATION_ROTATE_90, ExifInterface.ORIENTATION_TRANSVERSE -> 90 + ExifInterface.ORIENTATION_ROTATE_180, ExifInterface.ORIENTATION_FLIP_VERTICAL -> 180 + ExifInterface.ORIENTATION_ROTATE_270, ExifInterface.ORIENTATION_TRANSPOSE -> 270 + else -> 0 + } + + // interpret EXIF code to whether the image is flipped + fun isFlippedForExifCode(exifOrientation: Int): Boolean = when (exifOrientation) { + ExifInterface.ORIENTATION_FLIP_HORIZONTAL, ExifInterface.ORIENTATION_TRANSVERSE, ExifInterface.ORIENTATION_FLIP_VERTICAL, ExifInterface.ORIENTATION_TRANSPOSE -> true + else -> false + } + + fun getExifCode(rotationDegrees: Int, isFlipped: Boolean): Int { + return when (rotationDegrees) { + 90 -> if (isFlipped) ExifInterface.ORIENTATION_TRANSVERSE else ExifInterface.ORIENTATION_ROTATE_90 + 180 -> if (isFlipped) ExifInterface.ORIENTATION_FLIP_VERTICAL else ExifInterface.ORIENTATION_ROTATE_180 + 270 -> if (isFlipped) ExifInterface.ORIENTATION_TRANSPOSE else ExifInterface.ORIENTATION_ROTATE_270 + else -> if (isFlipped) ExifInterface.ORIENTATION_FLIP_HORIZONTAL else ExifInterface.ORIENTATION_NORMAL + } + } + + fun parseSubSecond(subSecond: String?): Int { + if (subSecond != null) { + try { + val millis = (".$subSecond".toDouble() * 1000).toInt() + if (millis in 0..999) { + return millis + } + } catch (_: NumberFormatException) { + // ignore + } + } + return 0 + } + + // not sure which standards are used for the different video formats, + // but looks like some form of ISO 8601 `basic format`: + // yyyyMMddTHHmmss(.sss)?(Z|+/-hhmm)? + fun parseVideoMetadataDate(metadataDate: String?): Long { + var dateString = metadataDate ?: return 0 + + // optional sub-second + var subSecond: String? = null + val subSecondMatcher = VIDEO_DATE_SUBSECOND_PATTERN.matcher(dateString) + if (subSecondMatcher.find()) { + subSecond = subSecondMatcher.group(2)?.substring(1) + dateString = subSecondMatcher.replaceAll("$1") + } + + // optional time zone + var timeZone: TimeZone? = null + val timeZoneMatcher = VIDEO_TIME_ZONE_PATTERN.matcher(dateString) + if (timeZoneMatcher.find()) { + timeZone = TimeZone.getTimeZone("GMT${timeZoneMatcher.group().replace("Z", "")}") + dateString = timeZoneMatcher.replaceAll("") + } + + val date: Date = try { + val parser = SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ROOT) + parser.timeZone = timeZone ?: TimeZone.getTimeZone("GMT") + parser.parse(dateString) + } catch (_: ParseException) { + // ignore + null + } ?: return 0 + + return date.time + parseSubSecond(subSecond) + } + + // Opening some large files yields an OOM (both with `metadata-extractor` v2.15.0 and `ExifInterface` v1.3.1), + // so we define an arbitrary threshold to avoid a crash on launch. + // It is not clear whether it is because of the file itself or its metadata. + private const val FILE_SIZE_MAX = 100 * (1 shl 20) // MB + + fun isDangerouslyLarge(sizeBytes: Long?) = sizeBytes == null || sizeBytes > FILE_SIZE_MAX + + // we try and read metadata from large files by copying an arbitrary amount from its beginning + // to a temporary file, and reusing that preview file for all metadata reading purposes + private const val PREVIEW_SIZE: Long = 5 * (1 shl 20) // MB + + private val previewFiles = HashMap<Uri, File>() + + private fun getSafeUri(context: Context, uri: Uri, mimeType: String?, sizeBytes: Long?): Uri { + // formats known to yield OOM for large files + return when (mimeType) { + // formats known to yield OOM for large files + MimeTypes.DNG, + MimeTypes.DNG_ADOBE, + MimeTypes.HEIC, + MimeTypes.HEIF, + MimeTypes.MP4, + MimeTypes.PSD_VND, + MimeTypes.PSD_X, + MimeTypes.TIFF, + null -> + if (isDangerouslyLarge(sizeBytes)) { + Log.d(LOG_TAG, "Dangerously large file with uri=$uri, mimeType=$mimeType, size=$sizeBytes") + // make a preview from the beginning of the file, + // hoping the metadata is accessible in the copied chunk + var previewFile = previewFiles[uri] + if (previewFile == null) { + previewFile = createPreviewFile(context, uri) + previewFiles[uri] = previewFile + } + Uri.fromFile(previewFile) + } else { + // small enough to be safe as it is + uri + } + + else -> + // *probably* safe + uri + } + } + + fun createPreviewFile(context: Context, uri: Uri): File { + val size = PREVIEW_SIZE + Log.d(LOG_TAG, "create preview of size=$size for uri=$uri") + return StorageUtils.createTempFile(context).apply { + transferFrom(StorageUtils.openInputStream(context, uri), size) + } + } + + fun openSafeInputStream(context: Context, uri: Uri, mimeType: String?, sizeBytes: Long?): InputStream? { + val safeUri = getSafeUri(context, uri, mimeType, sizeBytes) + return StorageUtils.openInputStream(context, safeUri) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Mp4ParserHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Mp4ParserHelper.kt new file mode 100644 index 0000000..42c1187 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Mp4ParserHelper.kt @@ -0,0 +1,436 @@ +package deckers.thibault.aves.metadata + +import android.content.Context +import android.net.Uri +import android.util.Log +import deckers.thibault.aves.metadata.xmp.XMP +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.toByteArray +import deckers.thibault.aves.utils.toHex +import org.mp4parser.BasicContainer +import org.mp4parser.Box +import org.mp4parser.Container +import org.mp4parser.IsoFile +import org.mp4parser.PropertyBoxParserImpl +import org.mp4parser.boxes.UnknownBox +import org.mp4parser.boxes.UserBox +import org.mp4parser.boxes.apple.AppleCoverBox +import org.mp4parser.boxes.apple.AppleGPSCoordinatesBox +import org.mp4parser.boxes.apple.AppleItemListBox +import org.mp4parser.boxes.apple.AppleVariableSignedIntegerBox +import org.mp4parser.boxes.apple.Utf8AppleDataBox +import org.mp4parser.boxes.iso14496.part12.FreeBox +import org.mp4parser.boxes.iso14496.part12.HandlerBox +import org.mp4parser.boxes.iso14496.part12.MediaDataBox +import org.mp4parser.boxes.iso14496.part12.MetaBox +import org.mp4parser.boxes.iso14496.part12.MovieBox +import org.mp4parser.boxes.iso14496.part12.MovieFragmentBox +import org.mp4parser.boxes.iso14496.part12.SampleTableBox +import org.mp4parser.boxes.iso14496.part12.SegmentIndexBox +import org.mp4parser.boxes.iso14496.part12.TrackHeaderBox +import org.mp4parser.boxes.iso14496.part12.UserDataBox +import org.mp4parser.boxes.threegpp.ts26244.AuthorBox +import org.mp4parser.boxes.threegpp.ts26244.LocationInformationBox +import org.mp4parser.support.AbstractBox +import org.mp4parser.support.Matrix +import org.mp4parser.tools.Path +import java.io.ByteArrayOutputStream +import java.io.FileInputStream +import java.nio.channels.Channels + +object Mp4ParserHelper { + private val LOG_TAG = LogUtils.createTag<Mp4ParserHelper>() + + // arbitrary size to detect boxes that may yield an OOM + private const val BOX_SIZE_DANGER_THRESHOLD = 3 * (1 shl 20) // MB + + const val SAMSUNG_MAKERNOTE_BOX_TYPE = "sefd" + const val SEFD_MOTION_PHOTO_NAME = "MotionPhoto_Data" + + private val largerTypeWhitelist = listOf( + // HEIC motion photo may contain Samsung maker notes in `sefd` box, + // including a video larger than the danger threshold + SAMSUNG_MAKERNOTE_BOX_TYPE, + ) + + fun computeEdits(context: Context, uri: Uri, modifier: (isoFile: IsoFile) -> Unit): List<Pair<Long, ByteArray>> { + // we can skip uninteresting boxes with a seekable data source + val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri") + pfd.use { + FileInputStream(it.fileDescriptor).use { stream -> + stream.channel.use { channel -> + val boxParser = PropertyBoxParserImpl().apply { + // do not skip anything inside `MovieBox` as it will be parsed and rewritten for editing + // do not skip weird boxes (like trailing "0000" box), to fail fast if it is large + val skippedTypes = listOf( + // parsing `MediaDataBox` can take a long time + MediaDataBox.TYPE, + ) + setBoxSkipper { type, size -> + if (skippedTypes.contains(type)) return@setBoxSkipper true + if (size > BOX_SIZE_DANGER_THRESHOLD) throw Mp4TooLargeException(type, "box (type=$type size=$size) is too large") + false + } + } + // creating `IsoFile` with a `File` or a `File.inputStream()` yields `No such device` + IsoFile(channel, boxParser).use { isoFile -> + val fragmented = isoFile.boxes.any { box -> box is MovieFragmentBox || box is SegmentIndexBox } + if (fragmented) throw Exception("editing fragmented movies is not supported") + + val lastContentBox = isoFile.boxes.reversed().firstOrNull { box -> + when { + box == isoFile.movieBox -> false + testXmpBox(box) -> false + box is FreeBox -> false + else -> true + } + } + lastContentBox ?: throw Exception("failed to find last content box") + val oldFileSize = isoFile.size + var appendOffset = (isoFile.getBoxOffset { box -> box == lastContentBox })!! + lastContentBox.size + + val edits = arrayListOf<Pair<Long, ByteArray>>() + fun addFreeBoxEdit(offset: Long, size: Long): Boolean { + val boxSize = size.toInt() - 8 + if (boxSize > BOX_SIZE_DANGER_THRESHOLD) throw Exception("dangerous free box replacement for size=$boxSize") + return edits.add(Pair(offset, FreeBox(boxSize).toBytes())) + } + + // replace existing movie box by a free box + isoFile.getBoxOffset { box -> box.type == MovieBox.TYPE }?.let { offset -> + addFreeBoxEdit(offset, isoFile.movieBox.size) + } + + // replace existing XMP box by a free box + isoFile.getBoxOffset { box -> testXmpBox(box) }?.let { offset -> + addFreeBoxEdit(offset, isoFile.xmpBox!!.size) + } + + modifier(isoFile) + + // write edited movie box + val movieBoxBytes = isoFile.movieBox.toBytes() + edits.removeAll { (offset, _) -> offset == appendOffset } + edits.add(Pair(appendOffset, movieBoxBytes)) + appendOffset += movieBoxBytes.size + + // write edited XMP box + isoFile.xmpBox?.let { box -> + edits.removeAll { (offset, _) -> offset == appendOffset } + edits.add(Pair(appendOffset, box.toBytes())) + appendOffset += box.size + } + + // write trailing free box instead of truncating + val trailing = oldFileSize - appendOffset + if (trailing > 0) { + addFreeBoxEdit(appendOffset, trailing) + } + return edits + } + } + } + } + } + + // according to XMP Specification Part 3 - Storage in Files, + // XMP is embedded in MPEG-4 files using a top-level UUID box + private fun testXmpBox(box: Box): Boolean { + if (box is UserBox) { + if (!box.isParsed) { + box.parseDetails() + } + return box.userType.contentEquals(XMP.mp4Uuid) + } + return false + } + + // returns the offset and data of the Samsung maker notes box + fun getSamsungSefd(context: Context, uri: Uri): Pair<Long, ByteArray>? { + try { + // we can skip uninteresting boxes with a seekable data source + val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri") + pfd.use { + FileInputStream(it.fileDescriptor).use { stream -> + stream.channel.use { channel -> + IsoFile(channel, metadataBoxParser()).use { isoFile -> + var offset = 0L + for (box in isoFile.boxes) { + if (box is UnknownBox && box.type == SAMSUNG_MAKERNOTE_BOX_TYPE) { + if (!box.isParsed) { + box.parseDetails() + } + return Pair(offset + 8, box.data.toByteArray()) // skip 8 bytes for box header + } + offset += box.size + } + } + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read sefd box", e) + } + return null + } + + // extensions + + fun IsoFile.updateLocation(locationIso6709: String?) { + // Apple GPS Coordinates Box can be in various locations: + // - moov[0]/udta[0]/©xyz + // - moov[0]/meta[0]/ilst/©xyz + // - others? + removeBoxes(AppleGPSCoordinatesBox::class.java, true) + + locationIso6709 ?: return + + var userDataBox = Path.getPath<UserDataBox>(movieBox, UserDataBox.TYPE) + if (userDataBox == null) { + userDataBox = UserDataBox() + movieBox.addBox(userDataBox) + } + + userDataBox.addBox(AppleGPSCoordinatesBox().apply { + value = locationIso6709 + }) + } + + fun IsoFile.updateRotation(degrees: Int): Boolean { + val matrix: Matrix = when (degrees) { + 0 -> Matrix.ROTATE_0 + 90 -> Matrix.ROTATE_90 + 180 -> Matrix.ROTATE_180 + 270 -> Matrix.ROTATE_270 + else -> throw Exception("failed because of invalid rotation degrees=$degrees") + } + + var success = false + movieBox.getBoxes(TrackHeaderBox::class.java, true).filter { tkhd -> + if (!tkhd.isParsed) { + tkhd.parseDetails() + } + tkhd.width > 0 && tkhd.height > 0 + }.forEach { tkhd -> + if (!setOf(Matrix.ROTATE_0, Matrix.ROTATE_90, Matrix.ROTATE_180, Matrix.ROTATE_270).contains(tkhd.matrix)) { + throw Exception("failed because existing matrix is not a simple rotation matrix") + } + tkhd.matrix = matrix + success = true + } + return success + } + + fun IsoFile.updateXmp(xmp: String?) { + val xmpBox = xmpBox + if (xmp != null) { + val xmpData = xmp.toByteArray(Charsets.UTF_8) + if (xmpBox == null) { + addBox(UserBox(XMP.mp4Uuid).apply { + data = xmpData + }) + } else { + xmpBox.data = xmpData + } + } else if (xmpBox != null) { + removeBox(xmpBox) + } + } + + private fun IsoFile.getBoxOffset(test: (box: Box) -> Boolean): Long? { + var offset = 0L + for (box in boxes) { + if (test(box)) { + return offset + } + offset += box.size + } + return null + } + + private val IsoFile.xmpBox: UserBox? + get() = boxes.firstOrNull { testXmpBox(it) } as UserBox? + + fun <T : Box> Container.processBoxes(clazz: Class<T>, recursive: Boolean, apply: (box: T, parent: Container) -> Unit) { + // use a copy, in case box processing removes boxes + for (box in ArrayList(boxes)) { + if (clazz.isInstance(box)) { + @Suppress("unchecked_cast") + apply(box as T, this) + } + if (recursive && box is Container) { + box.processBoxes(clazz, true, apply) + } + } + } + + private fun <T : Box> Container.removeBoxes(clazz: Class<T>, recursive: Boolean) { + processBoxes(clazz, recursive) { box, parent -> parent.removeBox(box) } + } + + private fun Container.removeBox(box: Box) { + boxes = boxes.apply { remove(box) } + } + + fun Container.dumpBoxes(sb: StringBuilder, indent: Int = 0) { + for (box in boxes) { + val boxType = box.type + try { + if (box is AbstractBox && !box.isParsed) { + box.parseDetails() + } + when (box) { + is BasicContainer -> { + sb.appendLine("${"\t".repeat(indent)}[$boxType] ${box.javaClass.simpleName}") + box.dumpBoxes(sb, indent + 1) + } + + is UserBox -> sb.appendLine("${"\t".repeat(indent)}[$boxType] userType=${box.userType.toHex()} $box") + else -> sb.appendLine("${"\t".repeat(indent)}[$boxType] $box") + } + } catch (e: Exception) { + sb.appendLine("${"\t".repeat(indent)}failed to access box type=$boxType exception=${e.message}") + } + } + } + + fun Box.toBytes(): ByteArray { + if (size > BOX_SIZE_DANGER_THRESHOLD) throw Mp4TooLargeException(type, "box (type=$type size=$size) is too large") + val stream = ByteArrayOutputStream(size.toInt()) + Channels.newChannel(stream).use { getBox(it) } + return stream.toByteArray() + } + + fun metadataBoxParser() = PropertyBoxParserImpl().apply { + val skippedTypes = listOf( + // parsing `MediaDataBox` can take a long time + MediaDataBox.TYPE, + // parsing `SampleTableBox` or `FreeBox` may yield OOM + SampleTableBox.TYPE, FreeBox.TYPE, + // some files are padded with `0` but the parser does not stop, reads type "0000", + // then a large size from following "0000", which may yield OOM + "0000", + ) + setBoxSkipper { type, size -> + if (skippedTypes.contains(type)) return@setBoxSkipper true + if (size > BOX_SIZE_DANGER_THRESHOLD && !largerTypeWhitelist.contains(type)) throw Mp4TooLargeException(type, "box (type=$type size=$size) is too large") + false + } + } + + fun getUserDataBox( + context: Context, + mimeType: String, + uri: Uri, + ): UserDataBox? { + if (mimeType != MimeTypes.MP4) return null + + try { + // we can skip uninteresting boxes with a seekable data source + val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri") + pfd.use { + FileInputStream(it.fileDescriptor).use { stream -> + stream.channel.use { channel -> + // creating `IsoFile` with a `File` or a `File.inputStream()` yields `No such device` + IsoFile(channel, metadataBoxParser()).use { isoFile -> + return Path.getPath(isoFile.movieBox, UserDataBox.TYPE) + } + } + } + } + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to parse MP4 for mimeType=$mimeType uri=$uri", e) + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get User Data box by MP4 parser for mimeType=$mimeType uri=$uri", e) + } + return null + } + + fun extractBoxFields(container: Container): HashMap<String, String> { + val fields = HashMap<String, String>() + for (box in container.boxes) { + if (box is AbstractBox && !box.isParsed) { + box.parseDetails() + } + val type = box.type + val key = boxTypeMetadataKey(type) + when (box) { + is AuthorBox -> fields[key] = box.author + is AppleCoverBox -> fields[key] = "[${box.coverData.size} bytes]" + is AppleGPSCoordinatesBox -> fields[key] = box.value + is AppleItemListBox -> fields.putAll(extractBoxFields(box)) + is AppleVariableSignedIntegerBox -> fields[key] = box.value.toString() + is HandlerBox -> {} + is LocationInformationBox -> { + hashMapOf<String, String>( + "Language" to box.language, + "Name" to box.name, + "Role" to box.role.toString(), + "Longitude" to box.longitude.toString(), + "Latitude" to box.latitude.toString(), + "Altitude" to box.altitude.toString(), + "Astronomical Body" to box.astronomicalBody, + "Additional Notes" to box.additionalNotes, + ).forEach { (k, v) -> fields["$key/$k"] = v } + } + + is MetaBox -> { + val handlerBox = Path.getPath<HandlerBox>(box, HandlerBox.TYPE).apply { parseDetails() } + when (val handlerType = handlerBox?.handlerType ?: MetaBox.TYPE) { + "mdir" -> fields.putAll(extractBoxFields(box)) + else -> fields.putAll(extractBoxFields(box).map { Pair("$handlerType/${it.key}", it.value) }.toMap()) + } + } + + is UnknownBox -> { + val byteBuffer = box.data + val remaining = byteBuffer.remaining() + if (remaining > 512) { + fields[key] = "[$remaining bytes]" + } else { + val bytes = byteBuffer.toByteArray() + when (type) { + "SDLN", + "smrd" -> fields[key] = String(bytes) + + else -> fields[key] = "0x${bytes.toHex()}" + } + } + } + + is Utf8AppleDataBox -> fields[key] = box.value + + else -> fields[key] = box.toString() + } + } + return fields + } + + // cf https://exiftool.org/TagNames/QuickTime.html + private fun boxTypeMetadataKey(type: String) = when (type) { + "auth" -> "Author" + "catg" -> "Category" + "covr" -> "Cover Art" + "keyw" -> "Keyword" + "loci" -> "Location" + "mcvr" -> "Preview Image" + "pcst" -> "Podcast" + "SDLN" -> "Play Mode" + "stik" -> "Media Type" + "©alb" -> "Album" + "©ART" -> "Artist" + "©aut" -> "Author" + "©cmt" -> "Comment" + "©day" -> "Year" + "©des" -> "Description" + "©gen" -> "Genre" + "©nam" -> "Title" + "©too" -> "Encoder" + "©xyz" -> "GPS Coordinates" + else -> type + } +} + +class Mp4TooLargeException(val type: String, message: String) : RuntimeException(message) diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiPage.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiPage.kt new file mode 100644 index 0000000..948b2ae --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiPage.kt @@ -0,0 +1,451 @@ +package deckers.thibault.aves.metadata + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.media.MediaExtractor +import android.media.MediaFormat +import android.net.Uri +import android.os.Build +import android.os.ParcelFileDescriptor +import android.util.Log +import com.adobe.internal.xmp.XMPMeta +import com.drew.imaging.jpeg.JpegSegmentType +import com.drew.metadata.exif.ExifDirectoryBase +import com.drew.metadata.exif.ExifIFD0Directory +import com.drew.metadata.xmp.XmpDirectory +import deckers.thibault.aves.glide.TiffFetcher +import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeInt +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeInt +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeLong +import deckers.thibault.aves.metadata.metadataextractor.Helper +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeInt +import deckers.thibault.aves.metadata.metadataextractor.mpf.MpEntry +import deckers.thibault.aves.metadata.metadataextractor.mpf.MpEntryDirectory +import deckers.thibault.aves.metadata.xmp.GoogleXMP +import deckers.thibault.aves.metadata.xmp.XMP +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MemoryUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.canReadWithMetadataExtractor +import deckers.thibault.aves.utils.MimeTypes.isHeic +import deckers.thibault.aves.utils.MimeTypes.isIsoBMFFImage +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.indexOfBytes +import org.beyka.tiffbitmapfactory.TiffBitmapFactory +import java.io.DataInputStream +import java.io.EOFException +import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface + +object MultiPage { + private val LOG_TAG = LogUtils.createTag<MultiPage>() + + // TODO TLAD more generic support, (e.g. 0x00000014 + `ftyp` + `qt `) + // atom length (variable, e.g. `0x00000018`) + atom type (`ftyp`) + type (variable, e.g. `mp42`, `qt`) + private val heicMotionPhotoVideoStartIndicator = byteArrayOf(0x00, 0x00, 0x00, 0x18) + "ftypmp42".toByteArray() + + // page info + private const val KEY_MIME_TYPE = "mimeType" + private const val KEY_HEIGHT = "height" + private const val KEY_WIDTH = "width" + private const val KEY_PAGE = "page" + private const val KEY_IS_DEFAULT = "isDefault" + private const val KEY_DURATION = "durationMillis" + private const val KEY_ROTATION_DEGREES = "rotationDegrees" + + fun getHeicTracks(context: Context, uri: Uri): ArrayList<FieldMap> { + val tracks = ArrayList<FieldMap>() + val extractor = MediaExtractor() + extractor.setDataSource(context, uri, null) + for (pageIndex in 0 until extractor.trackCount) { + try { + val format = extractor.getTrackFormat(pageIndex) + format.getString(MediaFormat.KEY_MIME)?.let { mime -> + val trackMime = if (mime == MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC) MimeTypes.HEIC else mime + val track: FieldMap = hashMapOf( + KEY_PAGE to pageIndex, + KEY_MIME_TYPE to trackMime, + ) + + // do not use `MediaFormat.KEY_TRACK_ID` as it is actually not unique between tracks + // e.g. there could be both a video track and an image track with KEY_TRACK_ID == 1 + + format.getSafeInt(MediaFormat.KEY_WIDTH) { track[KEY_WIDTH] = it } + format.getSafeInt(MediaFormat.KEY_HEIGHT) { track[KEY_HEIGHT] = it } + format.getSafeInt(MediaFormat.KEY_IS_DEFAULT) { track[KEY_IS_DEFAULT] = it != 0 } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + format.getSafeInt(MediaFormat.KEY_ROTATION) { track[KEY_ROTATION_DEGREES] = it } + } + if (MimeTypes.isVideo(trackMime)) { + format.getSafeLong(MediaFormat.KEY_DURATION) { track[KEY_DURATION] = it / 1000 } + } + tracks.add(track) + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get HEIC track information for uri=$uri, pageIndex=$pageIndex", e) + } + } + extractor.release() + return tracks + } + + fun isIsoBMFFImageSefdMotionPhoto(context: Context, uri: Uri): Boolean { + return getIsoBMFFImageSefdMotionPhotoVideoSizing(context, uri) != null + } + + private fun getIsoBMFFImageSefdMotionPhotoVideoSizing(context: Context, uri: Uri): Pair<Long, Long>? { + Mp4ParserHelper.getSamsungSefd(context, uri)?.let { (sefdOffset, sefdBytes) -> + // we could properly parse each tag until we find the "embedded video" tag (0x0a30) + // but it seems that decoding the SEFT trailer is necessary for this, + // so we simply search for the "MotionPhoto_Data" sequence instead + val name = Mp4ParserHelper.SEFD_MOTION_PHOTO_NAME + val index = sefdBytes.indexOfBytes(name.toByteArray(Charsets.UTF_8)) + if (index != -1) { + val videoOffset = sefdOffset + index + name.length + val videoSize = sefdBytes.size - (videoOffset - sefdOffset) + return Pair(videoOffset, videoSize) + } + } + return null + } + + private fun getJpegMpfPrimaryRotation(context: Context, uri: Uri, sizeBytes: Long): Int { + val mimeType = MimeTypes.JPEG + var rotationDegrees = 0 + + var foundExif = false + if (canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + foundExif = metadata.directories.any { it is ExifDirectoryBase && it.tagCount > 0 } + for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) { + dir.getSafeInt(ExifDirectoryBase.TAG_ORIENTATION) { + rotationDegrees = Metadata.getRotationDegreesForExifCode(it) + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + + if (!foundExif) { + // fallback to read EXIF via ExifInterface + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val exif = ExifInterface(input) + exif.getSafeInt(ExifInterface.TAG_ORIENTATION, acceptZero = false) { + rotationDegrees = exif.rotationDegrees + } + } + } catch (e: Exception) { + // ExifInterface initialization can fail with a RuntimeException + // caused by an internal MediaMetadataRetriever failure + Log.w(LOG_TAG, "failed to get metadata by ExifInterface for mimeType=$mimeType uri=$uri", e) + } + } + + return rotationDegrees + } + + // starts after `[APP2 marker (1 byte)] [segment size (2 bytes)] [MPF marker (4 bytes)]` + fun getJpegMpfBaseOffset(context: Context, uri: Uri, sizeBytes: Long?): Int? { + val mimeType = MimeTypes.JPEG + val endMarker = 0xFF + val app2Marker = JpegSegmentType.APP2.byteValue + val mpfMarker = "MPF".toByteArray() + 0x00 + + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + var offset = 0 + val marker = ByteArray(4) + while (true) { + // look for APP2 marker (0xFFE2) + var found = false + while (!found) { + var i = input.read() + if (i == -1) throw EOFException() + offset++ + if (i == endMarker) { + i = input.read() + if (i == -1) throw EOFException() + offset++ + found = i.toByte() == app2Marker + } + } + // skip 2 bytes for segment size + input.skip(2) + offset += 2 + input.read(marker, 0, marker.size) + offset += 4 + if (marker.contentEquals(mpfMarker)) { + return offset + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get MPF base offset from uri=$uri", e) + } + return null + } + + fun getJpegMpfEntries(context: Context, uri: Uri, sizeBytes: Long?): List<MpEntry>? { + val mimeType = MimeTypes.JPEG + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + return metadata.getDirectoriesOfType(MpEntryDirectory::class.java).map { it.entry } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to find MPF entries", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to find MPF entries", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to find MPF entries", e) + } + return null + } + + fun getJpegMpfPages(context: Context, uri: Uri, sizeBytes: Long): ArrayList<FieldMap> { + val primaryRotation = getJpegMpfPrimaryRotation(context, uri, sizeBytes) + + val pages = ArrayList<FieldMap>() + val baseOffset = getJpegMpfBaseOffset(context, uri, sizeBytes) + val mpEntries = getJpegMpfEntries(context, uri, sizeBytes) + if (mpEntries != null && baseOffset != null) { + for ((pageIndex, mpEntry) in mpEntries.withIndex()) { + mpEntry.mimeType?.let { embedMimeType -> + val page = hashMapOf<String, Any?>( + KEY_PAGE to pageIndex, + KEY_MIME_TYPE to embedMimeType, + KEY_IS_DEFAULT to (pageIndex == 0), + KEY_ROTATION_DEGREES to primaryRotation, + ) + + var dataOffset = mpEntry.dataOffset + if (dataOffset > 0) { + dataOffset += baseOffset + } + StorageUtils.openInputStream(context, uri)?.let { input -> + input.skip(dataOffset) + val options = BitmapFactory.Options().apply { + inJustDecodeBounds = true + } + BitmapFactory.decodeStream(input, null, options) + options.outWidth.takeIf { it >= 0 }?.let { page[KEY_WIDTH] = it } + options.outHeight.takeIf { it >= 0 }?.let { page[KEY_HEIGHT] = it } + + pages.add(page) + } + } + } + } + + return pages + } + + fun getJpegMpfBitmap(context: Context, uri: Uri, pageIndex: Int): Bitmap? { + val mpEntries = getJpegMpfEntries(context, uri, null) + if (mpEntries != null && pageIndex < mpEntries.size) { + val mpEntry = mpEntries[pageIndex] + var dataOffset = mpEntry.dataOffset + if (dataOffset > 0) { + val baseOffset = getJpegMpfBaseOffset(context, uri, null) + if (baseOffset != null) { + dataOffset += baseOffset + } + } + StorageUtils.openInputStream(context, uri)?.let { input -> + input.skip(dataOffset) + return BitmapFactory.decodeStream(input) + } + } + return null + } + + fun getMotionPhotoPages(context: Context, uri: Uri, mimeType: String, sizeBytes: Long): ArrayList<FieldMap> { + val pages = ArrayList<FieldMap>() + getMotionPhotoVideoInfo(context, uri, mimeType, sizeBytes)?.let { videoInfo -> + // set the original image as the first and default track + var pageIndex = 0 + pages.add( + hashMapOf( + KEY_PAGE to pageIndex++, + KEY_MIME_TYPE to mimeType, + KEY_IS_DEFAULT to true, + ) + ) + // add video tracks from the appended video + videoInfo.getString(MediaFormat.KEY_MIME)?.let { mime -> + if (MimeTypes.isVideo(mime)) { + val page: FieldMap = hashMapOf( + KEY_PAGE to pageIndex++, + KEY_MIME_TYPE to MimeTypes.MP4, + KEY_IS_DEFAULT to false, + ) + videoInfo.getSafeInt(MediaFormat.KEY_WIDTH) { page[KEY_WIDTH] = it } + videoInfo.getSafeInt(MediaFormat.KEY_HEIGHT) { page[KEY_HEIGHT] = it } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + videoInfo.getSafeInt(MediaFormat.KEY_ROTATION) { page[KEY_ROTATION_DEGREES] = it } + } + videoInfo.getSafeLong(MediaFormat.KEY_DURATION) { page[KEY_DURATION] = it / 1000 } + pages.add(page) + } + } + } + return pages + } + + fun getTrailerVideoSize(context: Context, uri: Uri, mimeType: String, sizeBytes: Long): Long? { + if (isHeic(mimeType)) { + // XMP in HEIC motion photos (as taken with a Samsung Camera v12.0.01.50) indicates an `Item:Length` of 68 bytes for the video. + // This item does not contain the video itself, but only some kind of metadata (no doc, no spec), + // so we ignore the `Item:Length` and look instead for the MP4 marker bytes indicating the start of the video. + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + if (MemoryUtils.canAllocate(sizeBytes)) { + val bytes = ByteArray(sizeBytes.toInt()) + DataInputStream(input).use { + it.readFully(bytes) + } + val index = bytes.indexOfBytes(heicMotionPhotoVideoStartIndicator) + if (index != -1) { + return sizeBytes - index + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get motion photo offset from uri=$uri", e) + } + } + + var offsetFromEnd: Long? = null + var foundXmp = false + + fun processXmp(xmpMeta: XMPMeta) { + offsetFromEnd = offsetFromEnd ?: GoogleXMP.getTrailingVideoOffsetFromEnd(xmpMeta) + } + + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + foundXmp = metadata.directories.any { it is XmpDirectory && it.tagCount > 0 } + metadata.getDirectoriesOfType(XmpDirectory::class.java).map { it.xmpMeta }.forEach(::processXmp) + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get motion photo offset from uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to get motion photo offset from uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to get motion photo offset from uri=$uri", e) + } + + XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::processXmp) + + return offsetFromEnd + } + + private fun getMotionPhotoVideoInfo(context: Context, uri: Uri, mimeType: String, sizeBytes: Long): MediaFormat? { + getMotionPhotoVideoSizing(context, uri, mimeType, sizeBytes)?.let { (videoOffset, videoSize) -> + return getEmbedVideoInfo(context, uri, videoOffset, videoSize) + } + return null + } + + fun getTrailerVideoInfo(context: Context, uri: Uri, fileSize: Long, videoSize: Long): MediaFormat? { + return getEmbedVideoInfo(context, uri, videoOffset = fileSize - videoSize, videoSize = videoSize) + } + + private fun getEmbedVideoInfo(context: Context, uri: Uri, videoOffset: Long, videoSize: Long): MediaFormat? { + val extractor = MediaExtractor() + var pfd: ParcelFileDescriptor? = null + try { + pfd = context.contentResolver.openFileDescriptor(uri, "r") + pfd?.fileDescriptor?.let { fd -> + extractor.setDataSource(fd, videoOffset, videoSize) + // video track may be after an audio track + for (trackIndex in 0 until extractor.trackCount) { + try { + val format = extractor.getTrackFormat(trackIndex) + format.getString(MediaFormat.KEY_MIME)?.let { + if (MimeTypes.isVideo(it)) { + return format + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get track information for uri=$uri, track num=$trackIndex", e) + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to open motion photo for uri=$uri", e) + } finally { + extractor.release() + pfd?.close() + } + return null + } + + fun getMotionPhotoVideoSizing(context: Context, uri: Uri, mimeType: String, sizeBytes: Long): Pair<Long, Long>? { + // default to trailer videos + getTrailerVideoSize(context, uri, mimeType, sizeBytes)?.let { videoSize -> + val videoOffset = sizeBytes - videoSize + return Pair(videoOffset, videoSize) + } + + if (isIsoBMFFImage(mimeType)) { + // fallback to video within Samsung SEFD box + return getIsoBMFFImageSefdMotionPhotoVideoSizing(context, uri) + } + + return null + } + + fun getTiffPages(context: Context, uri: Uri): ArrayList<FieldMap> { + fun toMap(pageIndex: Int, options: TiffBitmapFactory.Options): FieldMap { + return hashMapOf( + KEY_PAGE to pageIndex, + KEY_MIME_TYPE to MimeTypes.TIFF, + KEY_WIDTH to options.outWidth, + KEY_HEIGHT to options.outHeight, + ) + } + + val pages = ArrayList<FieldMap>() + getTiffPageInfo(context, uri, 0)?.let { first -> + pages.add(toMap(0, first)) + val pageCount = first.outDirectoryCount + for (pageIndex in 1 until pageCount) { + getTiffPageInfo(context, uri, pageIndex)?.let { pages.add(toMap(pageIndex, it)) } + } + } + return pages + } + + fun isMultiPageTiff(context: Context, uri: Uri) = (getTiffPageInfo(context, uri, 0)?.outDirectoryCount ?: 1) > 1 + + private fun getTiffPageInfo(context: Context, uri: Uri, page: Int): TiffBitmapFactory.Options? { + try { + val fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd() + if (fd == null) { + Log.w(LOG_TAG, "failed to get TIFF file descriptor for uri=$uri") + return null + } + val options = TiffFetcher.buildOptions().apply { + inJustDecodeBounds = true + inDirectoryNumber = page + } + TiffBitmapFactory.decodeFileDescriptor(fd, options) + return options + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get TIFF page info for uri=$uri page=$page", e) + } + return null + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiTrackMedia.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiTrackMedia.kt new file mode 100644 index 0000000..d73bbe8 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiTrackMedia.kt @@ -0,0 +1,59 @@ +package deckers.thibault.aves.metadata + +import android.content.Context +import android.graphics.Bitmap +import android.media.MediaExtractor +import android.media.MediaFormat +import android.net.Uri +import android.os.Build +import android.util.Log +import androidx.annotation.RequiresApi +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.StorageUtils + +object MultiTrackMedia { + private val LOG_TAG = LogUtils.createTag<MultiTrackMedia>() + + @RequiresApi(Build.VERSION_CODES.P) + fun getImage(context: Context, uri: Uri, trackIndex: Int?): Bitmap? { + val retriever = StorageUtils.openMetadataRetriever(context, uri) ?: return null + try { + return if (trackIndex != null) { + val imageIndex = trackIndexToImageIndex(context, uri, trackIndex) ?: return null + retriever.getImageAtIndex(imageIndex) + } else { + retriever.primaryImage + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to extract image from uri=$uri trackIndex=$trackIndex", e) + } finally { + // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs + retriever.release() + } + return null + } + + private fun trackIndexToImageIndex(context: Context, uri: Uri, trackIndex: Int): Int? { + val extractor = MediaExtractor() + try { + extractor.setDataSource(context, uri, null) + val trackCount = extractor.trackCount + var imageIndex = 0 + for (i in 0 until trackCount) { + val trackFormat = extractor.getTrackFormat(i) + if (trackIndex == i) { + return imageIndex + } + if (MimeTypes.isImage(trackFormat.getString(MediaFormat.KEY_MIME))) { + imageIndex++ + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get image index for uri=$uri, trackIndex=$trackIndex", e) + } finally { + extractor.release() + } + return null + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/PixyMetaHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/PixyMetaHelper.kt new file mode 100644 index 0000000..2f3b17a --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/PixyMetaHelper.kt @@ -0,0 +1,172 @@ +package deckers.thibault.aves.metadata + +import android.content.Context +import android.net.Uri +import deckers.thibault.aves.metadata.Metadata.TYPE_COMMENT +import deckers.thibault.aves.metadata.Metadata.TYPE_EXIF +import deckers.thibault.aves.metadata.Metadata.TYPE_ICC_PROFILE +import deckers.thibault.aves.metadata.Metadata.TYPE_IPTC +import deckers.thibault.aves.metadata.Metadata.TYPE_JFIF +import deckers.thibault.aves.metadata.Metadata.TYPE_JPEG_ADOBE +import deckers.thibault.aves.metadata.Metadata.TYPE_JPEG_DUCKY +import deckers.thibault.aves.metadata.Metadata.TYPE_PHOTOSHOP_IRB +import deckers.thibault.aves.metadata.Metadata.TYPE_XMP +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.StorageUtils +import pixy.meta.meta.Metadata +import pixy.meta.meta.MetadataEntry +import pixy.meta.meta.MetadataType +import pixy.meta.meta.iptc.IPTC +import pixy.meta.meta.iptc.IPTCDataSet +import pixy.meta.meta.iptc.IPTCRecord +import pixy.meta.meta.jpeg.JPGMeta +import pixy.meta.meta.xmp.XMP +import pixy.meta.string.XMLUtils +import java.io.File +import java.io.InputStream +import java.io.OutputStream + +object PixyMetaHelper { + fun describe(input: InputStream): HashMap<String, String> { + val metadataMap = HashMap<String, String>() + + fun fetch(parents: String, entries: Iterable<MetadataEntry>) { + for (entry in entries) { + metadataMap["$parents ${entry.key}"] = entry.value + if (entry.isMetadataEntryGroup) { + fetch("$parents ${entry.key} /", entry.metadataEntries) + } + } + } + + val metadataByType = Metadata.readMetadata(input) + for ((type, metadata) in metadataByType.entries) { + if (type == MetadataType.XMP) { + val xmp = metadataByType[MetadataType.XMP] as XMP? + if (xmp != null) { + metadataMap["XMP"] = xmp.xmpDocString() + if (xmp.hasExtendedXmp()) { + metadataMap["XMP extended"] = xmp.extendedXmpDocString() + } + } + } else { + fetch("$type /", metadata) + } + } + + return metadataMap + } + + fun getIptc(input: InputStream): List<FieldMap>? { + val iptc = Metadata.readMetadata(input)[MetadataType.IPTC] as IPTC? ?: return null + + val iptcDataList = ArrayList<FieldMap>() + iptc.dataSets.forEach { dataSetEntry -> + val tag = dataSetEntry.key + val dataSets = dataSetEntry.value + iptcDataList.add( + hashMapOf( + "record" to tag.recordNumber, + "tag" to tag.tag, + "values" to dataSets.map { it.data }.toMutableList(), + ) + ) + } + return iptcDataList + } + + fun setIptc( + input: InputStream, + output: OutputStream, + iptcDataList: List<FieldMap>?, + ) { + val iptc: List<IPTCDataSet> = iptcDataList?.flatMap { + val record = it["record"] as Int + val tag = it["tag"] as Int + val values = it["values"] as List<*> + values.map { data -> IPTCDataSet(IPTCRecord.fromRecordNumber(record), tag, data as ByteArray) } + } ?: ArrayList() + Metadata.insertIPTC(input, output, iptc) + } + + fun getXmp(input: InputStream): XMP? = Metadata.readMetadata(input)[MetadataType.XMP] as XMP? + + // PixyMeta may fail with just a log, and write nothing to the output + fun setXmp( + input: InputStream, + output: OutputStream, + xmpString: String?, + extendedXmpString: String? + ) { + if (extendedXmpString != null) { + JPGMeta.insertXMP(input, output, xmpString, extendedXmpString) + } else { + Metadata.insertXMP(input, output, xmpString) + } + } + + fun XMP.xmpDocString(): String = XMLUtils.serializeToString(xmpDocument) + + fun XMP.extendedXmpDocString(): String = XMLUtils.serializeToString(extendedXmpDocument) + + fun copyIptcXmp( + context: Context, + sourceMimeType: String, + sourceUri: Uri, + targetMimeType: String, + targetUri: Uri, + editableFile: File, + ) { + var pixyIptc: IPTC? = null + var pixyXmp: XMP? = null + if (MimeTypes.canReadWithPixyMeta(sourceMimeType)) { + StorageUtils.openInputStream(context, sourceUri)?.use { input -> + val metadata = Metadata.readMetadata(input) + if (MimeTypes.canEditIptc(targetMimeType)) { + pixyIptc = metadata[MetadataType.IPTC] as IPTC? + } + if (MimeTypes.canEditXmp(targetMimeType)) { + pixyXmp = metadata[MetadataType.XMP] as XMP? + } + } + } + if (pixyIptc != null || pixyXmp != null) { + editableFile.outputStream().use { output -> + if (pixyIptc != null) { + // reopen input to read from start + StorageUtils.openInputStream(context, targetUri)?.use { input -> + val iptcs = pixyIptc!!.dataSets.flatMap { it.value } + Metadata.insertIPTC(input, output, iptcs) + } + } + if (pixyXmp != null) { + // reopen input to read from start + StorageUtils.openInputStream(context, targetUri)?.use { input -> + val xmpString = pixyXmp!!.xmpDocString() + val extendedXmp = if (pixyXmp!!.hasExtendedXmp()) pixyXmp!!.extendedXmpDocString() else null + setXmp(input, output, xmpString, if (targetMimeType == MimeTypes.JPEG) extendedXmp else null) + } + } + } + } + } + + fun removeMetadata(input: InputStream, output: OutputStream, metadataTypes: Set<String>) { + val types = metadataTypes.map(::toMetadataType).toTypedArray() + Metadata.removeMetadata(input, output, *types) + } + + private fun toMetadataType(typeString: String): MetadataType? = when (typeString) { + TYPE_COMMENT -> MetadataType.COMMENT + TYPE_EXIF -> MetadataType.EXIF + TYPE_ICC_PROFILE -> MetadataType.ICC_PROFILE + TYPE_IPTC -> MetadataType.IPTC + TYPE_JFIF -> MetadataType.JPG_JFIF + TYPE_JPEG_ADOBE -> MetadataType.JPG_ADOBE + TYPE_JPEG_DUCKY -> MetadataType.JPG_DUCKY + TYPE_PHOTOSHOP_IRB -> MetadataType.PHOTOSHOP_IRB + TYPE_XMP -> MetadataType.XMP + else -> null + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/QuickTimeMetadata.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/QuickTimeMetadata.kt new file mode 100644 index 0000000..e9b2206 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/QuickTimeMetadata.kt @@ -0,0 +1,99 @@ +package deckers.thibault.aves.metadata + +import deckers.thibault.aves.utils.toHex +import java.math.BigInteger +import java.nio.charset.Charset + +class QuickTimeMetadataBlock(val type: String, val value: String, val language: String) + +object QuickTimeMetadata { + // QuickTime Profile Tags + // cf https://exiftool.org/TagNames/QuickTime.html#Profile + const val PROF_UUID = "50524f46-21d2-4fce-bb88-695cfac9c740" + + // QuickTime UserMedia Tags + // cf https://exiftool.org/TagNames/QuickTime.html#UserMedia + const val USMT_UUID = "55534d54-21d2-4fce-bb88-695cfac9c740" + + private const val METADATA_BOX_ID = "MTDT" + + fun parseUuidUsmt(data: ByteArray): List<QuickTimeMetadataBlock> { + val blocks = ArrayList<QuickTimeMetadataBlock>() + val boxHeader = BoxHeader(data) + if (boxHeader.boxType == METADATA_BOX_ID) { + blocks.addAll(parseQuicktimeMtdtBox(boxHeader, data)) + } + return blocks + } + + private fun parseQuicktimeMtdtBox(boxHeader: BoxHeader, data: ByteArray): List<QuickTimeMetadataBlock> { + val blocks = ArrayList<QuickTimeMetadataBlock>() + var bytes = data + val blockCount = BigInteger(bytes.copyOfRange(8, 10)).toInt() + bytes = bytes.copyOfRange(10, boxHeader.boxDataSize) + + for (i in 0 until blockCount) { + val blockSize = BigInteger(bytes.copyOfRange(0, 2)).toInt() + val blockType = BigInteger(bytes.copyOfRange(2, 6)).toInt() + val language = parseLanguage(bytes.copyOfRange(6, 8)) + val encoding = BigInteger(bytes.copyOfRange(8, 10)).toInt() + val payload = bytes.copyOfRange(10, blockSize) + + val payloadString = when (encoding) { + // 0x00: short array + 0x00 -> { + payload + .asList() + .chunked(2) + .map { (h, l) -> ((h.toInt() shl 8) + l.toInt()).toShort() } + .joinToString() + } + // 0x01: string + 0x01 -> String(payload, Charset.forName("UTF-16BE")).trim() + // 0x101: artwork/icon + else -> "0x${payload.toHex()}" + } + + val blockTypeString = when (blockType) { + 0x01 -> "Title" + 0x03 -> "Creation Time" + 0x04 -> "Software" + 0x0A -> "Track property" + 0x0B -> "Time zone" + 0x0C -> "Modification Time" + else -> "0x${blockType.toByte().toHex()}" + } + + blocks.add( + QuickTimeMetadataBlock( + type = blockTypeString, + value = payloadString, + language = language, + ) + ) + bytes = bytes.copyOfRange(blockSize, bytes.size) + } + + return blocks + } + + // ISO 639 language code written as 3 groups of 5 bits for each letter (ascii code - 0x60) + // e.g. 0x55c4 -> 10101 01110 00100 -> 21 14 4 -> "und" + private fun parseLanguage(bytes: ByteArray): String { + val i = BigInteger(bytes).toInt() + val c1 = Character.toChars((i shr 10 and 0x1F) + 0x60)[0] + val c2 = Character.toChars((i shr 5 and 0x1F) + 0x60)[0] + val c3 = Character.toChars((i and 0x1F) + 0x60)[0] + return "$c1$c2$c3" + } +} + +class BoxHeader(bytes: ByteArray) { + var boxDataSize: Int = 0 + var boxType: String + + init { + boxDataSize = BigInteger(bytes.copyOfRange(0, 4)).toInt() + boxType = String(bytes.copyOfRange(4, 8)) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SphericalVideo.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SphericalVideo.kt new file mode 100644 index 0000000..783e4b2 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SphericalVideo.kt @@ -0,0 +1,109 @@ +package deckers.thibault.aves.metadata + +import android.util.Log +import android.util.Xml +import deckers.thibault.aves.utils.LogUtils +import org.xmlpull.v1.XmlPullParser +import java.io.ByteArrayInputStream + +// `xmlBytes`: bytes representing the XML embedded in a MP4 `uuid` box, according to Spherical Video V1 spec +class GSpherical(xmlBytes: ByteArray) { + private var spherical: Boolean = false + private var stitched: Boolean = false + private var stitchingSoftware: String = "" + private var projectionType: String = "" + private var stereoMode: String? = null + private var sourceCount: Int? = null + private var initialViewHeadingDegrees: Int? = null + private var initialViewPitchDegrees: Int? = null + private var initialViewRollDegrees: Int? = null + private var timestamp: Int? = null + private var fullPanoWidthPixels: Int? = null + private var fullPanoHeightPixels: Int? = null + private var croppedAreaImageWidthPixels: Int? = null + private var croppedAreaImageHeightPixels: Int? = null + private var croppedAreaLeftPixels: Int? = null + private var croppedAreaTopPixels: Int? = null + + init { + try { + ByteArrayInputStream(xmlBytes).use { + val parser = Xml.newPullParser().apply { + setInput(it, null) + nextTag() + require(XmlPullParser.START_TAG, RDF_NS, "SphericalVideo") + } + while (parser.next() != XmlPullParser.END_TAG) { + if (parser.eventType != XmlPullParser.START_TAG) continue + if (parser.namespace == GSPHERICAL_NS) { + when (val tag = parser.name) { + "Spherical" -> spherical = readTag(parser, tag) == "true" + "Stitched" -> stitched = readTag(parser, tag) == "true" + "StitchingSoftware" -> stitchingSoftware = readTag(parser, tag) + "ProjectionType" -> projectionType = readTag(parser, tag) + "StereoMode" -> stereoMode = readTag(parser, tag) + "SourceCount" -> sourceCount = readTag(parser, tag).toInt() + "InitialViewHeadingDegrees" -> initialViewHeadingDegrees = readTag(parser, tag).toInt() + "InitialViewPitchDegrees" -> initialViewPitchDegrees = readTag(parser, tag).toInt() + "InitialViewRollDegrees" -> initialViewRollDegrees = readTag(parser, tag).toInt() + "Timestamp" -> timestamp = readTag(parser, tag).toInt() + "FullPanoWidthPixels" -> fullPanoWidthPixels = readTag(parser, tag).toInt() + "FullPanoHeightPixels" -> fullPanoHeightPixels = readTag(parser, tag).toInt() + "CroppedAreaImageWidthPixels" -> croppedAreaImageWidthPixels = readTag(parser, tag).toInt() + "CroppedAreaImageHeightPixels" -> croppedAreaImageHeightPixels = readTag(parser, tag).toInt() + "CroppedAreaLeftPixels" -> croppedAreaLeftPixels = readTag(parser, tag).toInt() + "CroppedAreaTopPixels" -> croppedAreaTopPixels = readTag(parser, tag).toInt() + } + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to parse XML", e) + } + } + + fun describe(): Map<String, String> = hashMapOf( + "Spherical" to spherical.toString(), + "Stitched" to stitched.toString(), + "Stitching Software" to stitchingSoftware, + "Projection Type" to projectionType, + "Stereo Mode" to stereoMode, + "Source Count" to sourceCount?.toString(), + "Initial View Heading Degrees" to initialViewHeadingDegrees?.toString(), + "Initial View Pitch Degrees" to initialViewPitchDegrees?.toString(), + "Initial View Roll Degrees" to initialViewRollDegrees?.toString(), + "Timestamp" to timestamp?.toString(), + "Full Panorama Width Pixels" to fullPanoWidthPixels?.toString(), + "Full Panorama Height Pixels" to fullPanoHeightPixels?.toString(), + "Cropped Area Image Width Pixels" to croppedAreaImageWidthPixels?.toString(), + "Cropped Area Image Height Pixels" to croppedAreaImageHeightPixels?.toString(), + "Cropped Area Left Pixels" to croppedAreaLeftPixels?.toString(), + "Cropped Area Top Pixels" to croppedAreaTopPixels?.toString(), + ).filterValues { it != null }.mapValues { it.value as String } + + companion object SphericalVideo { + private val LOG_TAG = LogUtils.createTag<SphericalVideo>() + + // cf https://github.com/google/spatial-media + const val SPHERICAL_VIDEO_V1_UUID = "ffcc8263-f855-4a93-8814-587a02521fdd" + + const val RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" + const val GSPHERICAL_NS = "http://ns.google.com/videos/1.0/spherical/" + + private fun readText(parser: XmlPullParser): String { + var text = "" + if (parser.next() == XmlPullParser.TEXT) { + text = parser.text + parser.nextTag() + } + return text + } + + private fun readTag(parser: XmlPullParser, tag: String): String { + parser.require(XmlPullParser.START_TAG, GSPHERICAL_NS, tag) + val text = readText(parser) + parser.require(XmlPullParser.END_TAG, GSPHERICAL_NS, tag) + return text + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SvgHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SvgHelper.kt new file mode 100644 index 0000000..a170e4e --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SvgHelper.kt @@ -0,0 +1,33 @@ +package deckers.thibault.aves.metadata + +import com.caverock.androidsvg.SVG +import java.io.BufferedInputStream +import java.io.InputStream +import kotlin.math.max + +object SvgHelper { + const val IMAGE_BASE64_SIZE_DANGER_THRESHOLD: Long = 5 * (1 shl 20) // MB + + fun SVG.normalizeSize() { + if (documentViewBox == null) { + setDocumentViewBox(0f, 0f, documentWidth, documentHeight) + } + setDocumentWidth("100%") + setDocumentHeight("100%") + } +} + +// As of AndroidSVG v1.4, SVGParser.ENTITY_WATCH_BUFFER_SIZE is set at 4096. +// This constant is not configurable and used for the internal buffer mark read limit. +// Parsing will fail if the SVG header is larger than this value. +// So we define and apply a minimum read limit. +class SVGParserBufferedInputStream(input: InputStream) : BufferedInputStream(input) { + @Synchronized + override fun mark(readlimit: Int) { + super.mark(max(MINIMUM_READ_LIMIT, readlimit)) + } + + companion object { + private const val MINIMUM_READ_LIMIT = 1 shl 14 // 16kB + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/Helper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/Helper.kt new file mode 100644 index 0000000..748cba1 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/Helper.kt @@ -0,0 +1,403 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import android.util.Log +import com.drew.imaging.FileType +import com.drew.imaging.FileTypeDetector +import com.drew.imaging.ImageMetadataReader +import com.drew.imaging.ImageProcessingException +import com.drew.imaging.jpeg.JpegMetadataReader +import com.drew.imaging.jpeg.JpegSegmentMetadataReader +import com.drew.imaging.mp4.Mp4Reader +import com.drew.imaging.tiff.TiffProcessingException +import com.drew.imaging.tiff.TiffReader +import com.drew.lang.ByteArrayReader +import com.drew.lang.RandomAccessStreamReader +import com.drew.lang.Rational +import com.drew.lang.SequentialByteArrayReader +import com.drew.metadata.Directory +import com.drew.metadata.StringValue +import com.drew.metadata.exif.ExifDirectoryBase +import com.drew.metadata.exif.ExifIFD0Directory +import com.drew.metadata.exif.ExifReader +import com.drew.metadata.exif.ExifSubIFDDirectory +import com.drew.metadata.file.FileTypeDirectory +import com.drew.metadata.iptc.IptcReader +import com.drew.metadata.png.PngDirectory +import com.drew.metadata.xmp.XmpReader +import deckers.thibault.aves.metadata.ExifGeoTiffTags +import deckers.thibault.aves.metadata.GeoTiffKeys +import deckers.thibault.aves.metadata.Metadata +import deckers.thibault.aves.metadata.metadataextractor.mpf.MpfReader +import deckers.thibault.aves.utils.LogUtils +import java.io.BufferedInputStream +import java.io.IOException +import java.io.InputStream +import java.text.ParseException +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Date +import java.util.GregorianCalendar +import java.util.Locale +import java.util.TimeZone +import java.util.regex.Pattern + +object Helper { + private val LOG_TAG = LogUtils.createTag<Helper>() + + const val PNG_ITXT_DIR_NAME = "PNG-iTXt" + private const val PNG_TEXT_DIR_NAME = "PNG-tEXt" + const val PNG_TIME_DIR_NAME = "PNG-tIME" + private const val PNG_ZTXT_DIR_NAME = "PNG-zTXt" + private const val PNG_RAW_PROFILE_EXIF = "Raw profile type exif" + private const val PNG_RAW_PROFILE_IPTC = "Raw profile type iptc" + + val PNG_LAST_MODIFICATION_TIME_FORMAT = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.ROOT) + + // Pattern to extract profile name, length, and text data + // of raw profiles (EXIF, IPTC, etc.) in PNG `zTXt` chunks + // e.g. "iptc [...] 114 [...] 3842494d040400[...]" + // e.g. "exif [...] 134 [...] 4578696600004949[...]" + private val PNG_RAW_PROFILE_PATTERN = Regex("^\\n(.*?)\\n\\s*(\\d+)\\n(.*)", RegexOption.DOT_MATCHES_ALL) + + fun readMimeType(input: InputStream): String? { + val bufferedInputStream = if (input is BufferedInputStream) input else BufferedInputStream(input) + return FileTypeDetector.detectFileType(bufferedInputStream).mimeType + } + + @Throws(IOException::class, ImageProcessingException::class) + fun safeRead(input: InputStream, @Suppress("unused_parameter") sizeBytes: Long?): com.drew.metadata.Metadata { + val inputStream = if (input is BufferedInputStream) input else BufferedInputStream(input) + val fileType = FileTypeDetector.detectFileType(inputStream) + + // Providing the stream length is risky, as it may crash if it is incorrect. + // Not providing the stream length is also risky, as it may lead to OOM + // when `RandomAccessStreamReader` reads the entire stream to validate offsets. + val undefinedStreamLength = -1L + + val metadata = when (fileType) { + FileType.Jpeg -> safeReadJpeg(inputStream) + FileType.Mp4 -> safeReadMp4(inputStream) + FileType.Png -> safeReadPng(inputStream) + FileType.Psd -> safeReadPsd(inputStream) + FileType.Tiff, + FileType.Arw, + FileType.Cr2, + FileType.Nef, + FileType.Orf, + FileType.Rw2 -> safeReadTiff(inputStream, undefinedStreamLength) + + else -> ImageMetadataReader.readMetadata(inputStream, undefinedStreamLength, fileType) + } + + metadata.addDirectory(FileTypeDirectory(fileType)) + return metadata + } + + // Some JPEG, TIFF, MP4 (and other types?) contain XMP with a preposterous number of `DocumentAncestors`. + // This bloated XMP is unsafely loaded in memory by Adobe's `XMPMetaParser.parseInputSource` + // which easily yields OOM on Android, so we try to detect and strip extended XMP with a modified XMP reader. + private fun safeReadJpeg(input: InputStream): com.drew.metadata.Metadata { + val readers = ArrayList<JpegSegmentMetadataReader>().apply { + addAll(JpegMetadataReader.ALL_READERS.filter { it !is XmpReader }) + add(SafeXmpReader()) + add(MpfReader()) + } + + val metadata = com.drew.metadata.Metadata() + JpegMetadataReader.process(metadata, input, readers) + return metadata + } + + private fun safeReadPng(input: InputStream): com.drew.metadata.Metadata { + return SafePngMetadataReader.readMetadata(input) + } + + private fun safeReadPsd(input: InputStream): com.drew.metadata.Metadata { + return SafePsdMetadataReader.readMetadata(input) + } + + @Throws(IOException::class, TiffProcessingException::class) + fun safeReadTiff(input: InputStream, streamLength: Long): com.drew.metadata.Metadata { + val reader = RandomAccessStreamReader(input, RandomAccessStreamReader.DEFAULT_CHUNK_LENGTH, streamLength) + val metadata = com.drew.metadata.Metadata() + val handler = SafeExifTiffHandler(metadata, null, 0) + TiffReader().processTiff(reader, handler, 0) + return metadata + } + + private fun safeReadMp4(input: InputStream): com.drew.metadata.Metadata { + val metadata = com.drew.metadata.Metadata() + Mp4Reader.extract(input, SafeMp4BoxHandler(metadata)) + return metadata + } + + // extensions + + fun Directory.getSafeString(tag: Int, acceptBlank: Boolean = true, save: (value: String) -> Unit) { + if (this.containsTag(tag)) { + val string = this.getString(tag) + if (acceptBlank || string.isNotBlank()) { + save(string) + } + } + } + + fun Directory.getSafeBoolean(tag: Int, save: (value: Boolean) -> Unit) { + if (this.containsTag(tag)) save(this.getBoolean(tag)) + } + + fun Directory.getSafeInt(tag: Int, save: (value: Int) -> Unit) { + if (this.containsTag(tag)) save(this.getInt(tag)) + } + + fun Directory.getSafeLong(tag: Int, save: (value: Long) -> Unit) { + if (this.containsTag(tag)) save(this.getLong(tag)) + } + + fun Directory.getSafeRational(tag: Int, save: (value: Rational) -> Unit) { + if (this.containsTag(tag)) save(this.getRational(tag)) + } + + fun Directory.getSafeDateMillis(tag: Int, subSecond: String?): Long? { + if (this.containsTag(tag)) { + val date = this.getDatePlus(tag, subSecond, TimeZone.getDefault()) + if (date != null) return date.time + } + return null + } + + // This seems to cover all known Exif and Xmp date strings + // Note that " : : : : " is a valid date string according to the Exif spec (which means 'unknown date'): http://www.awaresystems.be/imaging/tiff/tifftags/privateifd/exif/datetimeoriginal.html + private val dateFormats = arrayOf( + "yyyy:MM:dd HH:mm:ss", + "yyyy:MM:dd HH:mm", + "yyyy-MM-dd HH:mm:ss", + "yyyy-MM-dd HH:mm", + "yyyy.MM.dd HH:mm:ss", + "yyyy.MM.dd HH:mm", + "yyyy-MM-dd'T'HH:mm:ss", + "yyyy-MM-dd'T'HH:mm", + "yyyy-MM-dd", + "yyyy-MM", + "yyyyMMdd", // as used in IPTC data + "yyyy" + ).map { SimpleDateFormat(it, Locale.ROOT) }.toTypedArray() + private val subsecondPattern = Pattern.compile("(\\d\\d:\\d\\d:\\d\\d)(\\.\\d+)") + private val timeZonePattern = Pattern.compile("(Z|[+-]\\d\\d:\\d\\d|[+-]\\d\\d\\d\\d)$") + private val calendar: Calendar = GregorianCalendar() + private const val PARSED_DATE_YEAR_MAX = 10000 + + // adapted from `metadata-extractor` v2.18.0 `Directory.getDate()` + // to also parse dates written as timestamps + private fun Directory.getDatePlus(tagType: Int, subSecond: String?, timeZone: TimeZone?): Date? { + var effectiveSubSecond = subSecond + var effectiveTimeZone = timeZone + val o = this.getObject(tagType) + if (o is Date) return o + + var date: Date? = null + if (o is String || o is StringValue) { + var dateString = o.toString() + + // if the date string has subsecond information, it supersedes the subsecond parameter + val subsecondMatcher = subsecondPattern.matcher(dateString) + if (subsecondMatcher.find()) { + effectiveSubSecond = subsecondMatcher.group(2)?.substring(1) + dateString = subsecondMatcher.replaceAll("$1") + } + + // if the date string has time zone information, it supersedes the timeZone parameter + val timeZoneMatcher = timeZonePattern.matcher(dateString) + if (timeZoneMatcher.find()) { + effectiveTimeZone = TimeZone.getTimeZone("GMT" + timeZoneMatcher.group().replace("Z".toRegex(), "")) + dateString = timeZoneMatcher.replaceAll("") + } + for (dateFormat in dateFormats) { + try { + dateFormat.timeZone = effectiveTimeZone ?: TimeZone.getTimeZone("GMT") // don't interpret zone time + val parsed = dateFormat.parse(dateString) + if (parsed != null) { + calendar.time = parsed + if (calendar.get(Calendar.YEAR) < PARSED_DATE_YEAR_MAX) { + date = parsed + break + } + } + } catch (_: ParseException) { + // simply try the next pattern + } + } + if (date == null) { + val dateLong = dateString.toLongOrNull() + if (dateLong != null) { + val epochTimeMillis = when (dateLong) { + in 0..99999999999 -> dateLong * 1000 // seconds + in 100000000000..99999999999999 -> dateLong // millis + in 100000000000000..9999999999999999 -> dateLong / 1000 // micros + else -> dateLong / 1000000 // nanos + } + date = Date(epochTimeMillis) + } + } + } + if (date == null) return null + + if (effectiveSubSecond != null) { + try { + val millisecond = (".$effectiveSubSecond".toDouble() * 1000).toInt() + if (millisecond in 0..999) { + val calendar = Calendar.getInstance() + calendar.time = date + calendar[Calendar.MILLISECOND] = millisecond + return calendar.time + } + } catch (_: NumberFormatException) { + // ignore + } + } + return date + } + + // time tag and sub-second tag are *not* in the same directory + fun ExifSubIFDDirectory.getDateModifiedMillis(save: (value: Long) -> Unit) { + val parent = parent + if (parent is ExifIFD0Directory) { + val subSecond = getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME) + val dateMillis = parent.getSafeDateMillis(ExifIFD0Directory.TAG_DATETIME, subSecond) + if (dateMillis != null) save(dateMillis) + } + } + + fun ExifSubIFDDirectory.getDateDigitizedMillis(save: (value: Long) -> Unit) { + val subSecond = getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME_DIGITIZED) + val dateMillis = this.getSafeDateMillis(ExifSubIFDDirectory.TAG_DATETIME_DIGITIZED, subSecond) + if (dateMillis != null) save(dateMillis) + } + + fun ExifSubIFDDirectory.getDateOriginalMillis(save: (value: Long) -> Unit) { + val subSecond = getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME_ORIGINAL) + val dateMillis = this.getSafeDateMillis(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL, subSecond) + if (dateMillis != null) save(dateMillis) + } + + // geotiff + + /* + cf http://docs.opengeospatial.org/is/19-008r4/19-008r4.html#_underlying_tiff_requirements + - One of ModelTiepointTag or ModelTransformationTag SHALL be included in an Image File Directory (IFD) + - If the ModelTransformationTag is included in an IFD, then a ModelPixelScaleTag SHALL NOT be included + - If the ModelPixelScaleTag is included in an IFD, then a ModelTiepointTag SHALL also be included. + */ + fun ExifDirectoryBase.containsGeoTiffTags(): Boolean { + if (!this.containsTag(ExifGeoTiffTags.TAG_GEO_KEY_DIRECTORY)) return false + + val modelTiePoints = this.containsTag(ExifGeoTiffTags.TAG_MODEL_TIE_POINT) + val modelTransformation = this.containsTag(ExifGeoTiffTags.TAG_MODEL_TRANSFORMATION) + if (!modelTiePoints && !modelTransformation) return false + + val modelPixelScale = this.containsTag(ExifGeoTiffTags.TAG_MODEL_PIXEL_SCALE) + return !((modelTransformation && modelPixelScale) || (modelPixelScale && !modelTiePoints)) + } + + // TODO TLAD use `GeoTiffDirectory` from the Java version of `metadata-extractor` when available + // adapted from https://github.com/drewnoakes/metadata-extractor-dotnet/blob/master/MetadataExtractor/Formats/Exif/ExifTiffHandler.cs + fun ExifIFD0Directory.extractGeoKeys(geoKeys: IntArray): HashMap<Int, Any?> { + val fields = HashMap<Int, Any?>() + if (geoKeys.size < 4) return fields + + var i = 0 + val directoryVersion = geoKeys[i++] + val revision = geoKeys[i++] + val minorRevision = geoKeys[i++] + val numberOfKeys = geoKeys[i++] + + fields[GeoTiffKeys.GEOTIFF_VERSION] = "$directoryVersion.$revision.$minorRevision" + + (0 until numberOfKeys).forEach { j -> + val keyId = geoKeys[i++] + val tiffTagLocation = geoKeys[i++] + val valueCount = geoKeys[i++] + val valueOffset = geoKeys[i++] + + try { + if (tiffTagLocation == 0) { + fields[keyId] = valueOffset + } else { + val sourceValue = getObject(tiffTagLocation) + if (sourceValue is StringValue) { + if (valueOffset + valueCount <= sourceValue.bytes.size) { + fields[keyId] = String(sourceValue.bytes, valueOffset, valueCount).trimEnd('|') + } else { + Log.w(LOG_TAG, "GeoTIFF key $keyId with offset $valueOffset and count $valueCount extends beyond length of source value (${sourceValue.bytes.size})") + } + } else if (sourceValue.javaClass.isArray) { + val sourceArray = sourceValue as DoubleArray + if (valueOffset + valueCount <= sourceArray.size) { + fields[keyId] = sourceArray.copyOfRange(valueOffset, valueOffset + valueCount) + } else { + Log.w(LOG_TAG, "GeoTIFF key $keyId with offset $valueOffset and count $valueCount extends beyond length of source value (${sourceArray.size})") + } + } else { + Log.w(LOG_TAG, "GeoTIFF key $keyId references tag $tiffTagLocation which has unsupported type of ${sourceValue?.javaClass}") + } + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to extract GeoTiff fields from keys", e) + } + } + + return fields + } + + // PNG + + fun Directory.isPngTextDir(): Boolean = this is PngDirectory && setOf(PNG_ITXT_DIR_NAME, PNG_TEXT_DIR_NAME, PNG_ZTXT_DIR_NAME).contains(this.name) + + fun extractPngProfile(key: String, valueString: String): Iterable<Directory>? { + if (key == PNG_RAW_PROFILE_EXIF || key == PNG_RAW_PROFILE_IPTC) { + val match = PNG_RAW_PROFILE_PATTERN.matchEntire(valueString) + if (match != null) { + val dataString = match.groupValues[3] + val hexString = dataString.replace(Regex("[\\r\\n]"), "") + val dataBytes = hexString.decodeHex() + if (dataBytes != null) { + val metadata = com.drew.metadata.Metadata() + when (key) { + PNG_RAW_PROFILE_EXIF -> { + if (ExifReader.startsWithJpegExifPreamble(dataBytes)) { + ExifReader().extract(ByteArrayReader(dataBytes), metadata, ExifReader.JPEG_SEGMENT_PREAMBLE.length) + } + } + + PNG_RAW_PROFILE_IPTC -> { + val start = dataBytes.indexOf(Metadata.IPTC_MARKER_BYTE) + if (start != -1) { + val segmentBytes = dataBytes.copyOfRange(fromIndex = start, toIndex = dataBytes.size) + IptcReader().extract(SequentialByteArrayReader(segmentBytes), metadata, segmentBytes.size.toLong()) + } + } + } + return metadata.directories + } + } + } + return null + } + + // convenience methods + + private fun String.decodeHex(): ByteArray? { + if (length % 2 != 0) return null + + try { + val byteIterator = chunkedSequence(2) + .map { it.toInt(16).toByte() } + .iterator() + + return ByteArray(length / 2) { byteIterator.next() } + } catch (e: NumberFormatException) { + Log.w(LOG_TAG, "failed to decode hex string=$this", e) + } + return null + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/PngActlDirectory.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/PngActlDirectory.kt new file mode 100644 index 0000000..9313882 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/PngActlDirectory.kt @@ -0,0 +1,22 @@ +package deckers.thibault.aves.metadata.metadataextractor +import com.drew.imaging.png.PngChunkType +import com.drew.metadata.png.PngDirectory + +class PngActlDirectory : PngDirectory(chunkType) { + override fun getTagNameMap(): HashMap<Int, String> { + return tagNames + } + + companion object { + val chunkType = PngChunkType("acTL") + + // tags should be distinct from those already defined in `PngDirectory` + const val TAG_NUM_FRAMES = 101 + const val TAG_NUM_PLAYS = 102 + + private val tagNames = hashMapOf( + TAG_NUM_FRAMES to "Number Of Frames", + TAG_NUM_PLAYS to "Number Of Plays", + ) + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeExifTiffHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeExifTiffHandler.kt new file mode 100644 index 0000000..39a4c49 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeExifTiffHandler.kt @@ -0,0 +1,28 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import com.drew.lang.RandomAccessReader +import com.drew.metadata.Directory +import com.drew.metadata.Metadata +import com.drew.metadata.exif.ExifIFD0Directory +import com.drew.metadata.exif.ExifSubIFDDirectory +import com.drew.metadata.exif.ExifTiffHandler +import java.io.IOException + +class SafeExifTiffHandler(metadata: Metadata, parentDirectory: Directory?, exifStartOffset: Int) : ExifTiffHandler(metadata, parentDirectory, exifStartOffset) { + @Throws(IOException::class) + override fun customProcessTag( + tagOffset: Int, + processedIfdOffsets: MutableSet<Int>?, + tiffHeaderOffset: Int, + reader: RandomAccessReader?, + tagId: Int, + byteCount: Int, + ): Boolean { + if (tagId == ExifSubIFDDirectory.TAG_APPLICATION_NOTES && (_currentDirectory is ExifIFD0Directory || _currentDirectory is ExifSubIFDDirectory)) { + SafeXmpReader().extract(reader!!.getNullTerminatedBytes(tagOffset, byteCount), _metadata, _currentDirectory) + return true + } + + return super.customProcessTag(tagOffset, processedIfdOffsets, tiffHeaderOffset, reader, tagId, byteCount) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4BoxHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4BoxHandler.kt new file mode 100644 index 0000000..b4e8377 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4BoxHandler.kt @@ -0,0 +1,20 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import com.drew.imaging.mp4.Mp4Handler +import com.drew.metadata.Metadata +import com.drew.metadata.mp4.Mp4BoxHandler +import com.drew.metadata.mp4.Mp4BoxTypes +import com.drew.metadata.mp4.Mp4Context +import java.io.IOException + +class SafeMp4BoxHandler(metadata: Metadata) : Mp4BoxHandler(metadata) { + @Throws(IOException::class) + override fun processBox(type: String, payload: ByteArray?, boxSize: Long, context: Mp4Context?): Mp4Handler<*>? { + if (payload != null && type == Mp4BoxTypes.BOX_USER_DEFINED) { + val userBoxHandler = SafeMp4UuidBoxHandler(metadata) + userBoxHandler.processBox(type, payload, boxSize, context) + return this + } + return super.processBox(type, payload, boxSize, context) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4UuidBoxHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4UuidBoxHandler.kt new file mode 100644 index 0000000..147f67f --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4UuidBoxHandler.kt @@ -0,0 +1,20 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import com.drew.imaging.mp4.Mp4Handler +import com.drew.metadata.Metadata +import com.drew.metadata.mp4.Mp4Context +import com.drew.metadata.mp4.media.Mp4UuidBoxHandler +import deckers.thibault.aves.metadata.xmp.XMP + +class SafeMp4UuidBoxHandler(metadata: Metadata) : Mp4UuidBoxHandler(metadata) { + override fun processBox(type: String?, payload: ByteArray?, boxSize: Long, context: Mp4Context?): Mp4Handler<*> { + if (payload != null && payload.size >= 16) { + val payloadUuid = payload.copyOfRange(0, 16) + if (payloadUuid.contentEquals(XMP.mp4Uuid)) { + SafeXmpReader().extract(payload, 16, payload.size - 16, metadata, directory) + return this + } + } + return super.processBox(type, payload, boxSize, context) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePhotoshopReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePhotoshopReader.kt new file mode 100644 index 0000000..d312569 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePhotoshopReader.kt @@ -0,0 +1,116 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import com.drew.imaging.ImageProcessingException +import com.drew.lang.ByteArrayReader +import com.drew.lang.SequentialByteArrayReader +import com.drew.lang.SequentialReader +import com.drew.metadata.Directory +import com.drew.metadata.Metadata +import com.drew.metadata.exif.ExifReader +import com.drew.metadata.icc.IccReader +import com.drew.metadata.iptc.IptcReader +import com.drew.metadata.photoshop.PhotoshopDirectory +import com.drew.metadata.photoshop.PhotoshopReader +import java.util.Arrays + +// adapted from `PhotoshopReader` to prevent OOM from reading large XMP +// as of `metadata-extractor` v2.18.0, there is no way to customize the Photoshop reader +// without copying the whole `extract` function +class SafePhotoshopReader : PhotoshopReader() { + override fun extract(reader: SequentialReader, length: Int, metadata: Metadata, parentDirectory: Directory?) { + val directory = PhotoshopDirectory() + metadata.addDirectory(directory) + + if (parentDirectory != null) { + directory.parent = parentDirectory + } + + // Data contains a sequence of Image Resource Blocks (IRBs): + // + // 4 bytes - Signature; mostly "8BIM" but "PHUT", "AgHg" and "DCSR" are also found + // 2 bytes - Resource identifier + // String - Pascal string, padded to make length even + // 4 bytes - Size of resource data which follows + // Data - The resource data, padded to make size even + // + // http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037504 + + var pos = 0 + var clippingPathCount = 0 + while (pos < length) { + try { + // 4 bytes for the signature ("8BIM", "PHUT", etc.) + val signature = reader.getString(4) + pos += 4 + + // 2 bytes for the resource identifier (tag type). + val tagType = reader.uInt16 // segment type + pos += 2 + + // A variable number of bytes holding a pascal string (two leading bytes for length). + var descriptionLength = reader.uInt8.toInt() + pos += 1 + // Some basic bounds checking + if (descriptionLength < 0 || descriptionLength + pos > length) { + throw ImageProcessingException("Invalid string length") + } + + // Get name (important for paths) + val description = StringBuilder() + descriptionLength += pos + // Loop through each byte and append to string + while (pos < descriptionLength) { + description.append(Char(reader.uInt8.toUShort())) + pos++ + } + + // The number of bytes is padded with a trailing zero, if needed, to make the size even. + if (pos % 2 != 0) { + reader.skip(1) + pos++ + } + + // 4 bytes for the size of the resource data that follows. + val byteCount = reader.int32 + pos += 4 + // The resource data. + var tagBytes = reader.getBytes(byteCount) + pos += byteCount + // The number of bytes is padded with a trailing zero, if needed, to make the size even. + if (pos % 2 != 0) { + reader.skip(1) + pos++ + } + + if (signature == "8BIM") { + when (tagType) { + PhotoshopDirectory.TAG_IPTC -> IptcReader().extract(SequentialByteArrayReader(tagBytes), metadata, tagBytes.size.toLong(), directory) + PhotoshopDirectory.TAG_ICC_PROFILE_BYTES -> IccReader().extract(ByteArrayReader(tagBytes), metadata, directory) + PhotoshopDirectory.TAG_EXIF_DATA_1, + PhotoshopDirectory.TAG_EXIF_DATA_3 -> ExifReader().extract(ByteArrayReader(tagBytes), metadata, 0, directory) + + PhotoshopDirectory.TAG_XMP_DATA -> SafeXmpReader().extract(tagBytes, metadata, directory) + in 0x07D0..0x0BB6 -> { + clippingPathCount++ + tagBytes = Arrays.copyOf(tagBytes, tagBytes.size + description.length + 1) + // Append description(name) to end of byte array with 1 byte before the description representing the length + for (i in tagBytes.size - description.length - 1 until tagBytes.size) { + if (i % (tagBytes.size - description.length - 1 + description.length) == 0) tagBytes[i] = description.length.toByte() else tagBytes[i] = description[i - (tagBytes.size - description.length - 1)].code.toByte() + } +// PhotoshopDirectory._tagNameMap[0x07CF + clippingPathCount] = "Path Info $clippingPathCount" + directory.setByteArray(0x07CF + clippingPathCount, tagBytes) + } + + else -> directory.setByteArray(tagType, tagBytes) + } +// if (tagType in 0x0fa0..0x1387) { +// PhotoshopDirectory._tagNameMap[tagType] = String.format("Plug-in %d Data", tagType - 0x0fa0 + 1) +// } + } + } catch (ex: Exception) { + directory.addError(ex.message) + return + } + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePngMetadataReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePngMetadataReader.kt new file mode 100644 index 0000000..719f08a --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePngMetadataReader.kt @@ -0,0 +1,335 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import android.util.Log +import com.drew.imaging.png.PngChromaticities +import com.drew.imaging.png.PngChunk +import com.drew.imaging.png.PngChunkReader +import com.drew.imaging.png.PngChunkType +import com.drew.imaging.png.PngHeader +import com.drew.imaging.png.PngProcessingException +import com.drew.imaging.tiff.TiffProcessingException +import com.drew.imaging.tiff.TiffReader +import com.drew.lang.ByteArrayReader +import com.drew.lang.ByteConvert +import com.drew.lang.Charsets +import com.drew.lang.DateUtil +import com.drew.lang.KeyValuePair +import com.drew.lang.RandomAccessStreamReader +import com.drew.lang.SequentialByteArrayReader +import com.drew.lang.SequentialReader +import com.drew.lang.StreamReader +import com.drew.lang.StreamUtil +import com.drew.metadata.ErrorDirectory +import com.drew.metadata.Metadata +import com.drew.metadata.StringValue +import com.drew.metadata.exif.ExifTiffHandler +import com.drew.metadata.icc.IccReader +import com.drew.metadata.png.PngChromaticitiesDirectory +import com.drew.metadata.png.PngDirectory +import com.drew.metadata.xmp.XmpReader +import deckers.thibault.aves.utils.LogUtils +import java.io.ByteArrayInputStream +import java.io.IOException +import java.io.InputStream +import java.util.Locale +import java.util.zip.InflaterInputStream +import java.util.zip.ZipException + +// adapted from `PngMetadataReader` to: +// - prevent OOM from reading large chunks. As of `metadata-extractor` v2.18.0, there is no way to customize the reader +// without copying `desiredChunkTypes` and the whole `processChunk` function. +// - parse `acTL` chunk to identify animated PNGs. +object SafePngMetadataReader { + private val LOG_TAG = LogUtils.createTag<SafePngMetadataReader>() + + // arbitrary size to detect chunks that may yield an OOM + private const val CHUNK_SIZE_DANGER_THRESHOLD = SafeXmpReader.SEGMENT_TYPE_SIZE_DANGER_THRESHOLD + + private val latin1Encoding = Charsets.ISO_8859_1 + private val utf8Encoding = Charsets.UTF_8 + private val desiredChunkTypes: Set<PngChunkType> = hashSetOf( + PngChunkType.IHDR, + PngChunkType.PLTE, + PngChunkType.tRNS, + PngChunkType.cHRM, + PngChunkType.sRGB, + PngChunkType.gAMA, + PngChunkType.iCCP, + PngChunkType.bKGD, + PngChunkType.tEXt, + PngChunkType.zTXt, + PngChunkType.iTXt, + PngChunkType.tIME, + PngChunkType.pHYs, + PngChunkType.sBIT, + PngChunkType.eXIf, + PngActlDirectory.chunkType, + ) + + @Throws(IOException::class, PngProcessingException::class) + fun readMetadata(inputStream: InputStream): Metadata { + val chunks = PngChunkReader().extract(StreamReader(inputStream), desiredChunkTypes) + val metadata = Metadata() + for (chunk in chunks) { + try { + processChunk(metadata, chunk) + } catch (e: Exception) { + metadata.addDirectory(ErrorDirectory("Exception reading PNG chunk: " + e.message)) + } + } + return metadata + } + + @Throws(PngProcessingException::class, IOException::class) + private fun processChunk(metadata: Metadata, chunk: PngChunk) { + val chunkType = chunk.type + val bytes = chunk.bytes + + // TLAD insert start + if (bytes.size > CHUNK_SIZE_DANGER_THRESHOLD) { + Log.w(LOG_TAG, "PNG chunk $chunkType is too large, with a size of ${bytes.size} B") + return + } + // TLAD insert end + + if (chunkType == PngChunkType.IHDR) { + val header = PngHeader(bytes) + val directory = PngDirectory(PngChunkType.IHDR) + directory.setInt(PngDirectory.TAG_IMAGE_WIDTH, header.imageWidth) + directory.setInt(PngDirectory.TAG_IMAGE_HEIGHT, header.imageHeight) + directory.setInt(PngDirectory.TAG_BITS_PER_SAMPLE, header.bitsPerSample.toInt()) + directory.setInt(PngDirectory.TAG_COLOR_TYPE, header.colorType.numericValue) + directory.setInt(PngDirectory.TAG_COMPRESSION_TYPE, header.compressionType.toInt() and 0xFF) // make sure it's unsigned + directory.setInt(PngDirectory.TAG_FILTER_METHOD, header.filterMethod.toInt()) + directory.setInt(PngDirectory.TAG_INTERLACE_METHOD, header.interlaceMethod.toInt()) + metadata.addDirectory(directory) + // TLAD insert start + } else if (chunkType == PngActlDirectory.chunkType) { + if (bytes.size != 8) { + throw PngProcessingException("Invalid number of bytes") + } + val reader = SequentialByteArrayReader(bytes) + try { + metadata.addDirectory(PngActlDirectory().apply { + setInt(PngActlDirectory.TAG_NUM_FRAMES, reader.int32) + setInt(PngActlDirectory.TAG_NUM_PLAYS, reader.int32) + }) + } catch (ex: IOException) { + throw PngProcessingException(ex) + } + // TLAD insert end + } else if (chunkType == PngChunkType.PLTE) { + val directory = PngDirectory(PngChunkType.PLTE) + directory.setInt(PngDirectory.TAG_PALETTE_SIZE, bytes.size / 3) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.tRNS) { + val directory = PngDirectory(PngChunkType.tRNS) + directory.setInt(PngDirectory.TAG_PALETTE_HAS_TRANSPARENCY, 1) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.sRGB) { + val srgbRenderingIntent = bytes[0].toInt() + val directory = PngDirectory(PngChunkType.sRGB) + directory.setInt(PngDirectory.TAG_SRGB_RENDERING_INTENT, srgbRenderingIntent) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.cHRM) { + val chromaticities = PngChromaticities(bytes) + val directory = PngChromaticitiesDirectory() + directory.setInt(PngChromaticitiesDirectory.TAG_WHITE_POINT_X, chromaticities.whitePointX) + directory.setInt(PngChromaticitiesDirectory.TAG_WHITE_POINT_Y, chromaticities.whitePointY) + directory.setInt(PngChromaticitiesDirectory.TAG_RED_X, chromaticities.redX) + directory.setInt(PngChromaticitiesDirectory.TAG_RED_Y, chromaticities.redY) + directory.setInt(PngChromaticitiesDirectory.TAG_GREEN_X, chromaticities.greenX) + directory.setInt(PngChromaticitiesDirectory.TAG_GREEN_Y, chromaticities.greenY) + directory.setInt(PngChromaticitiesDirectory.TAG_BLUE_X, chromaticities.blueX) + directory.setInt(PngChromaticitiesDirectory.TAG_BLUE_Y, chromaticities.blueY) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.gAMA) { + val gammaInt = ByteConvert.toInt32BigEndian(bytes) + SequentialByteArrayReader(bytes).int32 + val directory = PngDirectory(PngChunkType.gAMA) + directory.setDouble(PngDirectory.TAG_GAMMA, gammaInt / 100000.0) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.iCCP) { + val reader: SequentialReader = SequentialByteArrayReader(bytes) + + // Profile Name is 1-79 bytes, followed by the 1 byte null character + val profileNameBytes = reader.getNullTerminatedBytes(79 + 1) + val directory = PngDirectory(PngChunkType.iCCP) + directory.setStringValue(PngDirectory.TAG_ICC_PROFILE_NAME, StringValue(profileNameBytes, latin1Encoding)) + val compressionMethod = reader.int8 + // Only compression method allowed by the spec is zero: deflate + if (compressionMethod.toInt() == 0) { + // bytes left for compressed text is: + // total bytes length - (profileNameBytes length + null byte + compression method byte) + val bytesLeft = bytes.size - (profileNameBytes.size + 1 + 1) + val compressedProfile = reader.getBytes(bytesLeft) + try { + val inflateStream = InflaterInputStream(ByteArrayInputStream(compressedProfile)) + IccReader().extract(RandomAccessStreamReader(inflateStream), metadata, directory) + inflateStream.close() + } catch (zex: ZipException) { + directory.addError(String.format("Exception decompressing PNG iCCP chunk : %s", zex.message)) + metadata.addDirectory(directory) + } + } else { + directory.addError("Invalid compression method value") + } + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.bKGD) { + val directory = PngDirectory(PngChunkType.bKGD) + directory.setByteArray(PngDirectory.TAG_BACKGROUND_COLOR, bytes) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.tEXt) { + val reader: SequentialReader = SequentialByteArrayReader(bytes) + + // Keyword is 1-79 bytes, followed by the 1 byte null character + val keywordsv = reader.getNullTerminatedStringValue(79 + 1, latin1Encoding) + val keyword = keywordsv.toString() + + // bytes left for text is: + // total bytes length - (Keyword length + null byte) + val bytesLeft = bytes.size - (keywordsv.bytes.size + 1) + val value = reader.getNullTerminatedStringValue(bytesLeft, latin1Encoding) + val textPairs: MutableList<KeyValuePair> = ArrayList() + textPairs.add(KeyValuePair(keyword, value)) + val directory = PngDirectory(PngChunkType.tEXt) + directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.zTXt) { + val reader: SequentialReader = SequentialByteArrayReader(bytes) + + // Keyword is 1-79 bytes, followed by the 1 byte null character + val keywordsv = reader.getNullTerminatedStringValue(79 + 1, latin1Encoding) + val keyword = keywordsv.toString() + val compressionMethod = reader.int8 + + // bytes left for compressed text is: + // total bytes length - (Keyword length + null byte + compression method byte) + val bytesLeft = bytes.size - (keywordsv.bytes.size + 1 + 1) + var textBytes: ByteArray? = null + if (compressionMethod.toInt() == 0) { + try { + textBytes = StreamUtil.readAllBytes(InflaterInputStream(ByteArrayInputStream(bytes, bytes.size - bytesLeft, bytesLeft))) + } catch (zex: ZipException) { + val directory = PngDirectory(PngChunkType.zTXt) + directory.addError(String.format("Exception decompressing PNG zTXt chunk with keyword \"%s\": %s", keyword, zex.message)) + metadata.addDirectory(directory) + } + } else { + val directory = PngDirectory(PngChunkType.zTXt) + directory.addError("Invalid compression method value") + metadata.addDirectory(directory) + } + if (textBytes != null) { + if (keyword == "XML:com.adobe.xmp") { + // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary + XmpReader().extract(textBytes, metadata) + } else { + val textPairs: MutableList<KeyValuePair> = ArrayList() + textPairs.add(KeyValuePair(keyword, StringValue(textBytes, latin1Encoding))) + val directory = PngDirectory(PngChunkType.zTXt) + directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs) + metadata.addDirectory(directory) + } + } + } else if (chunkType == PngChunkType.iTXt) { + val reader: SequentialReader = SequentialByteArrayReader(bytes) + + // Keyword is 1-79 bytes, followed by the 1 byte null character + val keywordsv = reader.getNullTerminatedStringValue(79 + 1, utf8Encoding) + val keyword = keywordsv.toString() + val compressionFlag = reader.int8 + val compressionMethod = reader.int8 + // TODO we currently ignore languageTagBytes and translatedKeywordBytes + val languageTagBytes = reader.getNullTerminatedBytes(bytes.size) + val translatedKeywordBytes = reader.getNullTerminatedBytes(bytes.size) + + // bytes left for compressed text is: + // total bytes length - (Keyword length + null byte + comp flag byte + comp method byte + lang length + null byte + translated length + null byte) + val bytesLeft = bytes.size - (keywordsv.bytes.size + 1 + 1 + 1 + languageTagBytes.size + 1 + translatedKeywordBytes.size + 1) + var textBytes: ByteArray? = null + if (compressionFlag.toInt() == 0) { + textBytes = reader.getNullTerminatedBytes(bytesLeft) + } else if (compressionFlag.toInt() == 1) { + if (compressionMethod.toInt() == 0) { + try { + textBytes = StreamUtil.readAllBytes(InflaterInputStream(ByteArrayInputStream(bytes, bytes.size - bytesLeft, bytesLeft))) + } catch (zex: ZipException) { + val directory = PngDirectory(PngChunkType.iTXt) + directory.addError(String.format("Exception decompressing PNG iTXt chunk with keyword \"%s\": %s", keyword, zex.message)) + metadata.addDirectory(directory) + } + } else { + val directory = PngDirectory(PngChunkType.iTXt) + directory.addError("Invalid compression method value") + metadata.addDirectory(directory) + } + } else { + val directory = PngDirectory(PngChunkType.iTXt) + directory.addError("Invalid compression flag value") + metadata.addDirectory(directory) + } + if (textBytes != null) { + if (keyword == "XML:com.adobe.xmp") { + // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary + XmpReader().extract(textBytes, metadata) + } else { + val textPairs: MutableList<KeyValuePair> = ArrayList() + textPairs.add(KeyValuePair(keyword, StringValue(textBytes, utf8Encoding))) + val directory = PngDirectory(PngChunkType.iTXt) + directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs) + metadata.addDirectory(directory) + } + } + } else if (chunkType == PngChunkType.tIME) { + val reader = SequentialByteArrayReader(bytes) + val year = reader.uInt16 + val month = reader.uInt8.toInt() + val day = reader.uInt8.toInt() + val hour = reader.uInt8.toInt() + val minute = reader.uInt8.toInt() + val second = reader.uInt8.toInt() + val directory = PngDirectory(PngChunkType.tIME) + if (DateUtil.isValidDate(year, month - 1, day) && DateUtil.isValidTime(hour, minute, second)) { + val dateString = String.format(Locale.ROOT, "%04d:%02d:%02d %02d:%02d:%02d", year, month, day, hour, minute, second) + directory.setString(PngDirectory.TAG_LAST_MODIFICATION_TIME, dateString) + } else { + directory.addError( + String.format( + Locale.ROOT, + "PNG tIME data describes an invalid date/time: year=%d month=%d day=%d hour=%d minute=%d second=%d", + year, month, day, hour, minute, second + ) + ) + } + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.pHYs) { + val reader = SequentialByteArrayReader(bytes) + val pixelsPerUnitX = reader.int32 + val pixelsPerUnitY = reader.int32 + val unitSpecifier = reader.int8 + val directory = PngDirectory(PngChunkType.pHYs) + directory.setInt(PngDirectory.TAG_PIXELS_PER_UNIT_X, pixelsPerUnitX) + directory.setInt(PngDirectory.TAG_PIXELS_PER_UNIT_Y, pixelsPerUnitY) + directory.setInt(PngDirectory.TAG_UNIT_SPECIFIER, unitSpecifier.toInt()) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.sBIT) { + val directory = PngDirectory(PngChunkType.sBIT) + directory.setByteArray(PngDirectory.TAG_SIGNIFICANT_BITS, bytes) + metadata.addDirectory(directory) + } else if (chunkType == PngChunkType.eXIf) { + try { + val handler = ExifTiffHandler(metadata, null, 0) + TiffReader().processTiff(ByteArrayReader(bytes), handler, 0) + } catch (ex: TiffProcessingException) { + val directory = PngDirectory(PngChunkType.eXIf) + directory.addError(ex.message) + metadata.addDirectory(directory) + } catch (ex: IOException) { + val directory = PngDirectory(PngChunkType.eXIf) + directory.addError(ex.message) + metadata.addDirectory(directory) + } + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdMetadataReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdMetadataReader.kt new file mode 100644 index 0000000..6f93a23 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdMetadataReader.kt @@ -0,0 +1,13 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import com.drew.lang.StreamReader +import com.drew.metadata.Metadata +import java.io.InputStream + +object SafePsdMetadataReader { + fun readMetadata(inputStream: InputStream): Metadata { + val metadata = Metadata() + SafePsdReader().extract(StreamReader(inputStream), metadata) + return metadata + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdReader.kt new file mode 100644 index 0000000..3ca23f6 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdReader.kt @@ -0,0 +1,93 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import com.drew.lang.SequentialReader +import com.drew.metadata.Metadata +import com.drew.metadata.photoshop.PsdHeaderDirectory +import java.io.IOException + +// adapted from `PsdReader` to prevent OOM from reading large XMP +// as of `metadata-extractor` v2.18.0, there is no way to customize the Photoshop reader +// without copying the whole `extract` function +class SafePsdReader { + fun extract(reader: SequentialReader, metadata: Metadata) { + val directory = PsdHeaderDirectory() + metadata.addDirectory(directory) + + // FILE HEADER SECTION + + try { + val signature = reader.int32 + if (signature != 0x38425053) // "8BPS" + { + directory.addError("Invalid PSD file signature") + return + } + + val version = reader.uInt16 + if (version != 1 && version != 2) { + directory.addError("Invalid PSD file version (must be 1 or 2)") + return + } + + // 6 reserved bytes are skipped here. They should be zero. + reader.skip(6) + + val channelCount = reader.uInt16 + directory.setInt(PsdHeaderDirectory.TAG_CHANNEL_COUNT, channelCount) + + // even though this is probably an unsigned int, the max height in practice is 300,000 + val imageHeight = reader.int32 + directory.setInt(PsdHeaderDirectory.TAG_IMAGE_HEIGHT, imageHeight) + + // even though this is probably an unsigned int, the max width in practice is 300,000 + val imageWidth = reader.int32 + directory.setInt(PsdHeaderDirectory.TAG_IMAGE_WIDTH, imageWidth) + + val bitsPerChannel = reader.uInt16 + directory.setInt(PsdHeaderDirectory.TAG_BITS_PER_CHANNEL, bitsPerChannel) + + val colorMode = reader.uInt16 + directory.setInt(PsdHeaderDirectory.TAG_COLOR_MODE, colorMode) + } catch (_: IOException) { + directory.addError("Unable to read PSD header") + return + } + + // COLOR MODE DATA SECTION + + try { + val sectionLength = reader.uInt32 + + /* + * Only indexed color and duotone (see the mode field in the File header section) have color mode data. + * For all other modes, this section is just the 4-byte length field, which is set to zero. + * + * Indexed color images: length is 768; color data contains the color table for the image, + * in non-interleaved order. + * Duotone images: color data contains the duotone specification (the format of which is not documented). + * Other applications that read Photoshop files can treat a duotone image as a gray image, + * and just preserve the contents of the duotone information when reading and writing the + * file. + */ + reader.skip(sectionLength) + } catch (_: IOException) { + return + } + + // IMAGE RESOURCES SECTION + + try { + val sectionLength = reader.uInt32 + + assert(sectionLength <= Int.MAX_VALUE) + + SafePhotoshopReader().extract(reader, sectionLength.toInt(), metadata) + } catch (_: IOException) { + // ignore + } + + // LAYER AND MASK INFORMATION SECTION (skipped) + + // IMAGE DATA SECTION (skipped) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeXmpReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeXmpReader.kt new file mode 100644 index 0000000..603e3ed --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeXmpReader.kt @@ -0,0 +1,179 @@ +package deckers.thibault.aves.metadata.metadataextractor + +import android.util.Log +import com.adobe.internal.xmp.XMPException +import com.adobe.internal.xmp.XMPMeta +import com.adobe.internal.xmp.XMPMetaFactory +import com.adobe.internal.xmp.impl.ByteBuffer +import com.adobe.internal.xmp.options.ParseOptions +import com.adobe.internal.xmp.properties.XMPPropertyInfo +import com.drew.imaging.jpeg.JpegSegmentType +import com.drew.lang.SequentialByteArrayReader +import com.drew.lang.SequentialReader +import com.drew.metadata.Directory +import com.drew.metadata.Metadata +import com.drew.metadata.xmp.XmpDirectory +import com.drew.metadata.xmp.XmpReader +import deckers.thibault.aves.utils.LogUtils +import java.io.IOException +import java.util.Locale + +class SafeXmpReader : XmpReader() { + // adapted from `XmpReader` to detect and skip large extended XMP + override fun readJpegSegments(segments: Iterable<ByteArray>, metadata: Metadata, segmentType: JpegSegmentType) { + val preambleLength = XMP_JPEG_PREAMBLE.length + val extensionPreambleLength = XMP_EXTENSION_JPEG_PREAMBLE.length + var extendedXMPGUID: String? = null + var extendedXMPBuffer: ByteArray? = null + var loggedDanger = false + + for (segmentBytes in segments) { + if (segmentBytes.size >= preambleLength) { + if (XMP_JPEG_PREAMBLE.equals(String(segmentBytes, 0, preambleLength), ignoreCase = true) || + "XMP".equals(String(segmentBytes, 0, 3), ignoreCase = true) + ) { + val xmlBytes = ByteArray(segmentBytes.size - preambleLength) + System.arraycopy(segmentBytes, preambleLength, xmlBytes, 0, xmlBytes.size) + extract(xmlBytes, metadata) + extendedXMPGUID = getExtendedXMPGUID(metadata) + continue + } + } + if (extendedXMPGUID != null && segmentBytes.size >= extensionPreambleLength && + XMP_EXTENSION_JPEG_PREAMBLE.equals(String(segmentBytes, 0, extensionPreambleLength), ignoreCase = true) + ) { + extendedXMPBuffer = processExtendedXMPChunk(metadata, segmentBytes, extendedXMPGUID, extendedXMPBuffer) { fullLength -> + if (!loggedDanger) { + logError(metadata, fullLength) + loggedDanger = true + } + } + } + } + + extendedXMPBuffer?.let { xmpBytes -> + val totalSize = xmpBytes.size + if (totalSize > SEGMENT_TYPE_SIZE_DANGER_THRESHOLD) { + logError(metadata, totalSize) + } else { + extract(xmpBytes, metadata) + } + } + } + + // adapted from `XmpReader` to provide different parsing options + // and to detect large XMP when extracted directly (e.g. from Photoshop reader) + override fun extract(xmpBytes: ByteArray, offset: Int, length: Int, metadata: Metadata, parentDirectory: Directory?) { + val totalSize = xmpBytes.size + if (totalSize > SEGMENT_TYPE_SIZE_DANGER_THRESHOLD) { + logError(metadata, totalSize) + return + } + + val directory = XmpDirectory() + if (parentDirectory != null) directory.parent = parentDirectory + + try { + val xmpMeta: XMPMeta = if (offset == 0 && length == totalSize) { + XMPMetaFactory.parseFromBuffer(xmpBytes, PARSE_OPTIONS) + } else { + val buffer = ByteBuffer(xmpBytes, offset, length) + XMPMetaFactory.parse(buffer.byteStream, PARSE_OPTIONS) + } + directory.xmpMeta = xmpMeta + } catch (e: XMPException) { + directory.addError("Error processing XMP data: " + e.message) + } + if (!directory.isEmpty) metadata.addDirectory(directory) + } + + // adapted from `XmpReader` because original is private + private fun getExtendedXMPGUID(metadata: Metadata): String? { + val xmpDirectories = metadata.getDirectoriesOfType(XmpDirectory::class.java) + for (directory in xmpDirectories) { + val xmpMeta = directory.xmpMeta + try { + val itr = xmpMeta.iterator(SCHEMA_XMP_NOTES, null, null) ?: continue + while (itr.hasNext()) { + val pi = itr.next() as XMPPropertyInfo? + if (ATTRIBUTE_EXTENDED_XMP == pi!!.path) { + return pi.value + } + } + } catch (e: XMPException) { + // Fail silently here: we had a reading issue, not a decoding issue. + } + } + return null + } + + // adapted from `XmpReader` to prevent large allocation + private fun processExtendedXMPChunk(metadata: Metadata, segmentBytes: ByteArray, extendedXMPGUID: String, extendedXMPBufferIn: ByteArray?, onDangerSize: (fullLength: Int) -> Unit): ByteArray? { + var extendedXMPBuffer: ByteArray? = extendedXMPBufferIn + val extensionPreambleLength = XMP_EXTENSION_JPEG_PREAMBLE.length + val segmentLength = segmentBytes.size + val totalOffset = extensionPreambleLength + EXTENDED_XMP_GUID_LENGTH + EXTENDED_XMP_INT_LENGTH + EXTENDED_XMP_INT_LENGTH + if (segmentLength >= totalOffset) { + try { + val reader: SequentialReader = SequentialByteArrayReader(segmentBytes) + reader.skip(extensionPreambleLength.toLong()) + val segmentGUID = reader.getString(EXTENDED_XMP_GUID_LENGTH) + if (extendedXMPGUID == segmentGUID) { + val fullLength = reader.uInt32.toInt() + val chunkOffset = reader.uInt32.toInt() + if (extendedXMPBuffer == null) { + // TLAD insert start + if (fullLength > SEGMENT_TYPE_SIZE_DANGER_THRESHOLD) { + onDangerSize(fullLength) + return null + } + // TLAD insert end + extendedXMPBuffer = ByteArray(fullLength) + } + if (extendedXMPBuffer.size == fullLength) { + System.arraycopy(segmentBytes, totalOffset, extendedXMPBuffer, chunkOffset, segmentLength - totalOffset) + } else { + val directory = XmpDirectory() + directory.addError(String.format(Locale.ROOT, "Inconsistent length for the Extended XMP buffer: %d instead of %d", fullLength, extendedXMPBuffer.size)) + metadata.addDirectory(directory) + } + } + } catch (ex: IOException) { + val directory = XmpDirectory() + directory.addError(ex.message) + metadata.addDirectory(directory) + } + } + return extendedXMPBuffer + } + + private fun logError(metadata: Metadata, size: Int) { + val error = "Extended XMP is too large, with a size of $size B" + Log.w(LOG_TAG, error) + metadata.addDirectory(XmpDirectory().apply { + addError(error) + }) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<SafeXmpReader>() + + // arbitrary size to detect extended XMP that may yield an OOM + const val SEGMENT_TYPE_SIZE_DANGER_THRESHOLD = 3 * (1 shl 20) // MB + + // tighter node limits for faster loading + val PARSE_OPTIONS: ParseOptions = ParseOptions().setXMPNodesToLimit( + mapOf( + "photoshop:DocumentAncestors" to 200, + "xmpMM:History" to 200, + ) + ) + + private const val XMP_JPEG_PREAMBLE = "http://ns.adobe.com/xap/1.0/\u0000" + private const val XMP_EXTENSION_JPEG_PREAMBLE = "http://ns.adobe.com/xmp/extension/\u0000" + private const val SCHEMA_XMP_NOTES = "http://ns.adobe.com/xmp/note/" + private const val ATTRIBUTE_EXTENDED_XMP = "xmpNote:HasExtendedXMP" + private const val EXTENDED_XMP_GUID_LENGTH = 32 + private const val EXTENDED_XMP_INT_LENGTH = 4 + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntry.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntry.kt new file mode 100644 index 0000000..c99adc7 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntry.kt @@ -0,0 +1,37 @@ +package deckers.thibault.aves.metadata.metadataextractor.mpf + +import deckers.thibault.aves.utils.MimeTypes + +class MpEntry(val flags: Int, val format: Int, val type: Int, val size: Long, val dataOffset: Long, val dep1: Short, val dep2: Short) { + val mimeType: String? + get() = getMimeType(format) + + val isThumbnail: Boolean + get() = when (type) { + TYPE_THUMBNAIL_VGA, TYPE_THUMBNAIL_FULL_HD -> true + else -> false + } + + override fun toString(): String = "MpEntry#${hashCode()}{flags=$flags format=$format type=$type size=$size dataOffset=$dataOffset dep1=$dep1 dep2=$dep2}" + + companion object { + const val FLAG_REPRESENTATIVE = 1 shl 2 + const val FLAG_DEPENDENT_CHILD = 1 shl 3 + const val FLAG_DEPENDENT_PARENT = 1 shl 4 + + const val TYPE_PRIMARY = 0x030000 + const val TYPE_THUMBNAIL_VGA = 0x010001 + const val TYPE_THUMBNAIL_FULL_HD = 0x010002 + const val TYPE_PANORAMA = 0x020001 + const val TYPE_DISPARITY = 0x020002 + const val TYPE_MULTI_ANGLE = 0x020003 + const val TYPE_UNDEFINED = 0x000000 + + fun getMimeType(format: Int): String? { + return when (format) { + 0 -> MimeTypes.JPEG + else -> null + } + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntryDirectory.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntryDirectory.kt new file mode 100644 index 0000000..7dba552 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntryDirectory.kt @@ -0,0 +1,64 @@ +package deckers.thibault.aves.metadata.metadataextractor.mpf + +import com.drew.metadata.Directory +import com.drew.metadata.TagDescriptor + +class MpEntryDirectory(val id: Int, val entry: MpEntry) : Directory() { + private val descriptor = MpEntryDescriptor(this) + + init { + setDescriptor(descriptor) + } + + fun describe(): Map<String, String> { + return HashMap<String, String>().apply { + put("Flags", descriptor.getFlagsDescription(entry.flags)) + put("Format", descriptor.getFormatDescription(entry.format)) + put("Type", descriptor.getTypeDescription(entry.type)) + put("Size", "${entry.size} bytes") + put("Offset", "${entry.dataOffset} bytes") + put("Dependent Image 1 Entry Number", "${entry.dep1}") + put("Dependent Image 2 Entry Number", "${entry.dep2}") + } + } + + override fun getName(): String { + return "MPF Image #$id" + } + + override fun getTagNameMap(): HashMap<Int, String> { + return _tagNameMap + } + + companion object { + private val _tagNameMap = HashMap<Int, String>() + } +} + +class MpEntryDescriptor(directory: MpEntryDirectory?) : TagDescriptor<MpEntryDirectory>(directory) { + fun getFlagsDescription(flags: Int): String { + val flagStrings = ArrayList<String>().apply { + if (flags and MpEntry.FLAG_REPRESENTATIVE != 0) add("representative image") + if (flags and MpEntry.FLAG_DEPENDENT_CHILD != 0) add("dependent child image") + if (flags and MpEntry.FLAG_DEPENDENT_PARENT != 0) add("dependent parent image") + } + return if (flagStrings.isEmpty()) "none" else flagStrings.joinToString(", ") + } + + fun getFormatDescription(format: Int): String { + return MpEntry.getMimeType(format) ?: "Unknown ($format)" + } + + fun getTypeDescription(type: Int): String { + return when (type) { + MpEntry.TYPE_PRIMARY -> "Baseline MP Primary Image" + MpEntry.TYPE_THUMBNAIL_VGA -> "Large Thumbnail (VGA equivalent)" + MpEntry.TYPE_THUMBNAIL_FULL_HD -> "Large Thumbnail (full HD equivalent)" + MpEntry.TYPE_PANORAMA -> "Multi-frame Panorama" + MpEntry.TYPE_DISPARITY -> "Multi-frame Disparity" + MpEntry.TYPE_MULTI_ANGLE -> "Multi-angle" + MpEntry.TYPE_UNDEFINED -> "Undefined" + else -> "Unknown ($type)" + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfDirectory.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfDirectory.kt new file mode 100644 index 0000000..c0ea08c --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfDirectory.kt @@ -0,0 +1,36 @@ +package deckers.thibault.aves.metadata.metadataextractor.mpf + +import com.drew.metadata.Directory +import com.drew.metadata.TagDescriptor + +class MpfDirectory : Directory() { + init { + setDescriptor(MpfDescriptor(this)) + } + + override fun getName(): String { + return "MPF" + } + + override fun getTagNameMap(): HashMap<Int, String> { + return _tagNameMap + } + + companion object { + const val TAG_MPF_VERSION = 0xb000 + const val TAG_NUMBER_OF_IMAGES = 0xb001 + const val TAG_MP_ENTRY = 0xb002 + private const val TAG_IMAGE_UID_LIST = 0xb003 + private const val TAG_TOTAL_FRAMES = 0xb004 + + private val _tagNameMap = HashMap<Int, String>().apply { + put(TAG_MPF_VERSION, "MPF Version") + put(TAG_NUMBER_OF_IMAGES, "Number Of Images") + put(TAG_MP_ENTRY, "MP Entry") + put(TAG_IMAGE_UID_LIST, "Image UID List") + put(TAG_TOTAL_FRAMES, "Total Frames") + } + } +} + +class MpfDescriptor(directory: MpfDirectory?) : TagDescriptor<MpfDirectory>(directory)
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfReader.kt new file mode 100644 index 0000000..423ff56 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfReader.kt @@ -0,0 +1,95 @@ +package deckers.thibault.aves.metadata.metadataextractor.mpf + +import android.util.Log +import com.drew.imaging.jpeg.JpegSegmentMetadataReader +import com.drew.imaging.jpeg.JpegSegmentType +import com.drew.lang.ByteArrayReader +import com.drew.lang.RandomAccessReader +import com.drew.metadata.Metadata +import com.drew.metadata.MetadataReader +import deckers.thibault.aves.utils.LogUtils + +class MpfReader : JpegSegmentMetadataReader, MetadataReader { + override fun getSegmentTypes(): Iterable<JpegSegmentType> { + return listOf(JpegSegmentType.APP2) + } + + override fun readJpegSegments(segments: Iterable<ByteArray>, metadata: Metadata, segmentType: JpegSegmentType) { + for (segmentBytes in segments) { + // Skip segments not starting with the required header + if (segmentBytes.size >= PREAMBLE.length && PREAMBLE == String(segmentBytes, 0, PREAMBLE.length)) { + extract(ByteArrayReader(segmentBytes), metadata) + } + } + } + + override fun extract(reader: RandomAccessReader, metadata: Metadata) { + val directory = MpfDirectory() + metadata.addDirectory(directory) + + val baseOffset = 4 + + // MP Format Identifier (4Byte) + // MP header + // - MP Endian (4Byte) + val byteOrderIdentifier = reader.getInt16(baseOffset) + if (byteOrderIdentifier.toInt() == 0x4d4d) { // "MM" + reader.isMotorolaByteOrder = true + } else if (byteOrderIdentifier.toInt() == 0x4949) { // "II" + reader.isMotorolaByteOrder = false + } + // - Offset to First IFD (4Byte) + val firstIfdOffset = reader.getInt32(baseOffset + 4) + + // [in primary image only] MP Index IFD: + // - Count (2Byte) + var offset = baseOffset + firstIfdOffset + val tagCount = reader.getInt16(offset) + offset += 2 + // - MP Index Fields (Overall Structure Info.) + var imageCount = 0 + for (tag in 0..<tagCount) { + when (val tagId = reader.getUInt16(offset)) { + MpfDirectory.TAG_MPF_VERSION -> directory.setString(tagId, reader.getString(offset + 8, 4, Charsets.US_ASCII)) + MpfDirectory.TAG_NUMBER_OF_IMAGES -> { + imageCount = reader.getInt32(offset + 8) + directory.setInt(tagId, imageCount) + } + + MpfDirectory.TAG_MP_ENTRY -> { + var mpEntryOffset = baseOffset + reader.getInt32(offset + 8) + for (index in 0..<imageCount) { + // individual image + val attribute = reader.getUInt32(mpEntryOffset) + val flags = (attribute shr 27 and 0x1f).toInt() + val format = (attribute shr 24 and 0x7).toInt() + val type = (attribute and 0xffffff).toInt() + val size = reader.getUInt32(mpEntryOffset + 4) + val dataOffset = reader.getUInt32(mpEntryOffset + 8) + val dep1 = reader.getInt16(mpEntryOffset + 12) + val dep2 = reader.getInt16(mpEntryOffset + 14) + metadata.addDirectory(MpEntryDirectory(index + 1, MpEntry(flags, format, type, size, dataOffset, dep1, dep2))) + mpEntryOffset += 16 + } + } + + else -> Log.d(LOG_TAG, "unknown tag=$tagId") + } + offset += 12 + } + + // - Offset of Next IFD (4Byte) + // Value (MP Index IFD) + + // [in primary & other images] MP Attributes IFD: + // - Count (2Byte) + // - MP Attribute Fields (Details of Specific Image Usage) + // - Offset of Next IFD + // Value (MP Attribute IFD) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<MpfReader>() + private const val PREAMBLE = "MPF" + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleDeviceContainer.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleDeviceContainer.kt new file mode 100644 index 0000000..41d27f9 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleDeviceContainer.kt @@ -0,0 +1,85 @@ +package deckers.thibault.aves.metadata.xmp + +import android.content.Context +import android.net.Uri +import com.adobe.internal.xmp.XMPMeta +import deckers.thibault.aves.metadata.Metadata +import deckers.thibault.aves.metadata.xmp.XMP.countPropPathArrayItems +import deckers.thibault.aves.metadata.xmp.XMP.getSafeStructField +import deckers.thibault.aves.utils.indexOfBytes +import java.io.DataInputStream + +class GoogleDeviceContainer { + private val jfifSignature = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte(), 0xE0.toByte(), 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01) + + private val items: MutableList<GoogleDeviceContainerItem> = ArrayList() + private val offsets: MutableList<Int> = ArrayList() + + fun findItems(xmpMeta: XMPMeta) { + val containerDirectoryPath = listOf(GoogleXMP.GDEVICE_CONTAINER_PROP_NAME, GoogleXMP.GDEVICE_CONTAINER_DIRECTORY_PROP_NAME) + val count = xmpMeta.countPropPathArrayItems(containerDirectoryPath) + for (i in 1 until count + 1) { + val mimeType = xmpMeta.getSafeStructField(containerDirectoryPath + listOf(i, GoogleXMP.GDEVICE_CONTAINER_ITEM_MIME_PROP_NAME))?.value + val length = xmpMeta.getSafeStructField(containerDirectoryPath + listOf(i, GoogleXMP.GDEVICE_CONTAINER_ITEM_LENGTH_PROP_NAME))?.value?.toLongOrNull() + val dataUri = xmpMeta.getSafeStructField(containerDirectoryPath + listOf(i, GoogleXMP.GDEVICE_CONTAINER_ITEM_DATA_URI_PROP_NAME))?.value + if (mimeType != null && length != null && dataUri != null) { + items.add( + GoogleDeviceContainerItem( + mimeType = mimeType, + length = length, + dataUri = dataUri, + ) + ) + } else throw Exception("failed to extract Google device container item at index=$i with mimeType=$mimeType, length=$length, dataUri=$dataUri") + } + } + + fun findOffsets(context: Context, uri: Uri, mimeType: String, sizeBytes: Long) { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + val bytes = ByteArray(sizeBytes.toInt()) + DataInputStream(input).use { + it.readFully(bytes) + } + + var start = 0 + while (start < sizeBytes) { + val offset = bytes.indexOfBytes(jfifSignature, start) + if (offset != -1 && offset >= start) { + start = offset + jfifSignature.size + offsets.add(offset) + } else { + start = sizeBytes.toInt() + } + } + } + + // fix first offset as it may refer to included thumbnail instead of primary image + while (offsets.size < items.size) { + offsets.add(0, 0) + } + offsets[0] = 0 + } + + fun itemIndex(dataUri: String) = items.indexOfFirst { it.dataUri == dataUri } + + private fun item(index: Int): GoogleDeviceContainerItem? { + return if (0 <= index && index < items.size) { + items[index] + } else null + } + + fun itemStartOffset(index: Int): Long? { + return if (0 <= index && index < offsets.size) { + offsets[index].toLong() + } else null + } + + fun itemLength(index: Int): Long? { + val lengthByMeta = item(index)?.length ?: return null + return if (lengthByMeta != 0L) lengthByMeta else itemStartOffset(index + 1) + } + + fun itemMimeType(index: Int) = item(index)?.mimeType +} + +class GoogleDeviceContainerItem(val mimeType: String, val length: Long, val dataUri: String) diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleXMP.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleXMP.kt new file mode 100644 index 0000000..f5f42d3 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleXMP.kt @@ -0,0 +1,205 @@ +package deckers.thibault.aves.metadata.xmp + +import android.util.Log +import com.adobe.internal.xmp.XMPError +import com.adobe.internal.xmp.XMPException +import com.adobe.internal.xmp.XMPMeta +import deckers.thibault.aves.metadata.xmp.XMP.countPropArrayItems +import deckers.thibault.aves.metadata.xmp.XMP.doesPropExist +import deckers.thibault.aves.metadata.xmp.XMP.doesPropPathExist +import deckers.thibault.aves.metadata.xmp.XMP.getSafeInt +import deckers.thibault.aves.metadata.xmp.XMP.getSafeLong +import deckers.thibault.aves.metadata.xmp.XMP.getSafeString +import deckers.thibault.aves.metadata.xmp.XMP.getSafeStructField +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes + +object GoogleXMP { + private val LOG_TAG = LogUtils.createTag<GoogleXMP>() + + // namespaces + private const val GAUDIO_NS_URI = "http://ns.google.com/photos/1.0/audio/" + private const val GCAMERA_NS_URI = "http://ns.google.com/photos/1.0/camera/" + private const val GCONTAINER_NS_URI = "http://ns.google.com/photos/1.0/container/" + private const val GCONTAINER_ITEM_NS_URI = "http://ns.google.com/photos/1.0/container/item/" + private const val GDEPTH_NS_URI = "http://ns.google.com/photos/1.0/depthmap/" + private const val GDEVICE_NS_URI = "http://ns.google.com/photos/dd/1.0/device/" + private const val GDEVICE_CONTAINER_NS_URI = "http://ns.google.com/photos/dd/1.0/container/" + private const val GDEVICE_ITEM_NS_URI = "http://ns.google.com/photos/dd/1.0/item/" + private const val GIMAGE_NS_URI = "http://ns.google.com/photos/1.0/image/" + private const val GPANO_NS_URI = "http://ns.google.com/photos/1.0/panorama/" + + // embedded media data properties + // cf https://developers.google.com/depthmap-metadata + // cf https://developers.google.com/vr/reference/cardboard-camera-vr-photo-format + private val knownDataProps = listOf( + XMPPropName(GAUDIO_NS_URI, "Data"), + XMPPropName(GCAMERA_NS_URI, "RelitInputImageData"), + XMPPropName(GIMAGE_NS_URI, "Data"), + XMPPropName(GDEPTH_NS_URI, "Data"), + XMPPropName(GDEPTH_NS_URI, "Confidence"), + ) + + + fun isDataPath(path: String) = knownDataProps.map { it.toString() }.any { path == it } + + // google portrait + + val GDEVICE_CONTAINER_PROP_NAME = XMPPropName(GDEVICE_NS_URI, "Container") + val GDEVICE_CONTAINER_DIRECTORY_PROP_NAME = XMPPropName(GDEVICE_CONTAINER_NS_URI, "Directory") + val GDEVICE_CONTAINER_ITEM_DATA_URI_PROP_NAME = XMPPropName(GDEVICE_ITEM_NS_URI, "DataURI") + val GDEVICE_CONTAINER_ITEM_LENGTH_PROP_NAME = XMPPropName(GDEVICE_ITEM_NS_URI, "Length") + val GDEVICE_CONTAINER_ITEM_MIME_PROP_NAME = XMPPropName(GDEVICE_ITEM_NS_URI, "Mime") + + // container + + private val GCAMERA_VIDEO_OFFSET_PROP_NAME = XMPPropName(GCAMERA_NS_URI, "MicroVideoOffset") + private val GCONTAINER_DIRECTORY_PROP_NAME = XMPPropName(GCONTAINER_NS_URI, "Directory") + private val GCONTAINER_ITEM_PROP_NAME = XMPPropName(GCONTAINER_NS_URI, "Item") + private val GCONTAINER_ITEM_LENGTH_PROP_NAME = XMPPropName(GCONTAINER_ITEM_NS_URI, "Length") + private val GCONTAINER_ITEM_MIME_PROP_NAME = XMPPropName(GCONTAINER_ITEM_NS_URI, "Mime") + private val GCONTAINER_ITEM_SEMANTIC_PROP_NAME = XMPPropName(GCONTAINER_ITEM_NS_URI, "Semantic") + + private const val ITEM_SEMANTIC_GAIN_MAP = "GainMap" + + // panorama + // cf https://developers.google.com/streetview/spherical-metadata + + private val GPANO_CROPPED_AREA_HEIGHT_PROP_NAME = XMPPropName(GPANO_NS_URI, "CroppedAreaImageHeightPixels") + private val GPANO_CROPPED_AREA_WIDTH_PROP_NAME = XMPPropName(GPANO_NS_URI, "CroppedAreaImageWidthPixels") + private val GPANO_CROPPED_AREA_LEFT_PROP_NAME = XMPPropName(GPANO_NS_URI, "CroppedAreaLeftPixels") + private val GPANO_CROPPED_AREA_TOP_PROP_NAME = XMPPropName(GPANO_NS_URI, "CroppedAreaTopPixels") + private val GPANO_FULL_PANO_HEIGHT_PROP_NAME = XMPPropName(GPANO_NS_URI, "FullPanoHeightPixels") + private val GPANO_FULL_PANO_WIDTH_PROP_NAME = XMPPropName(GPANO_NS_URI, "FullPanoWidthPixels") + private val GPANO_PROJECTION_TYPE_PROP_NAME = XMPPropName(GPANO_NS_URI, "ProjectionType") + const val GPANO_PROJECTION_TYPE_DEFAULT = "equirectangular" + + // `GPano:ProjectionType` is required by spec but it is sometimes missing, assuming default + // `GPano:FullPanoHeightPixels` is required by spec but it is sometimes missing (e.g. Samsung Camera app panorama mode) + private val gpanoRequiredProps = listOf( + GPANO_CROPPED_AREA_HEIGHT_PROP_NAME, + GPANO_CROPPED_AREA_WIDTH_PROP_NAME, + GPANO_CROPPED_AREA_LEFT_PROP_NAME, + GPANO_CROPPED_AREA_TOP_PROP_NAME, + GPANO_FULL_PANO_WIDTH_PROP_NAME, + ) + + fun isUltraHdPhoto(meta: XMPMeta): Boolean { + if (meta.doesPropExist(GCONTAINER_DIRECTORY_PROP_NAME)) { + val count = meta.countPropArrayItems(GCONTAINER_DIRECTORY_PROP_NAME) + for (i in 1 until count + 1) { + val semantic = meta.getSafeStructField(listOf(GCONTAINER_DIRECTORY_PROP_NAME, i, GCONTAINER_ITEM_PROP_NAME, GCONTAINER_ITEM_SEMANTIC_PROP_NAME))?.value + if (semantic == ITEM_SEMANTIC_GAIN_MAP) { + return true + } + } + } + return false + } + + fun isMotionPhoto(meta: XMPMeta): Boolean { + try { + // GCamera motion photo + if (meta.doesPropExist(GCAMERA_VIDEO_OFFSET_PROP_NAME)) return true + + // Container motion photo + if (meta.doesPropExist(GCONTAINER_DIRECTORY_PROP_NAME)) { + val count = meta.countPropArrayItems(GCONTAINER_DIRECTORY_PROP_NAME) + var hasImage = false + var hasVideo = false + for (i in 1 until count + 1) { + val mime = getContainerItemAttribute(meta, i, GCONTAINER_ITEM_MIME_PROP_NAME) + val length = getContainerItemAttribute(meta, i, GCONTAINER_ITEM_LENGTH_PROP_NAME) + // `length` is not always provided for the image item + hasImage = hasImage || MimeTypes.isImage(mime) + hasVideo = hasVideo || (MimeTypes.isVideo(mime) && length != null) + } + if (hasImage && hasVideo) return true + } + + return false + } catch (e: XMPException) { + if (e.errorCode != XMPError.BADSCHEMA) { + // `BADSCHEMA` code is reported when we check a property + // from a non standard namespace, and that namespace is not declared in the XMP + Log.w(LOG_TAG, "failed to check Google motion photo props from XMP", e) + } + } + return false + } + + private fun getContainerItemAttribute(meta: XMPMeta, i: Int, attribute: XMPPropName): String? { + // variant of `Container:Item` with `<rdf:li rdf:parseType="Resource">` + val mime = meta.getSafeStructField(listOf(GCONTAINER_DIRECTORY_PROP_NAME, i, GCONTAINER_ITEM_PROP_NAME, attribute))?.value + // variant of `Container:Item` with `<rdf:li>` + return mime ?: meta.getSafeStructField(listOf(GCONTAINER_DIRECTORY_PROP_NAME, i, attribute))?.value + } + + fun isPanorama(meta: XMPMeta): Boolean { + try { + if (gpanoRequiredProps.all { meta.doesPropExist(it) }) return true + } catch (e: XMPException) { + if (e.errorCode != XMPError.BADSCHEMA) { + // `BADSCHEMA` code is reported when we check a property + // from a non standard namespace, and that namespace is not declared in the XMP + Log.w(LOG_TAG, "failed to check Google panorama props from XMP", e) + } + } + return false + } + + fun getPanoramaInfo(meta: XMPMeta): FieldMap { + val fields: FieldMap = hashMapOf() + try { + meta.getSafeInt(GPANO_CROPPED_AREA_LEFT_PROP_NAME) { fields["croppedAreaLeft"] = it } + meta.getSafeInt(GPANO_CROPPED_AREA_TOP_PROP_NAME) { fields["croppedAreaTop"] = it } + meta.getSafeInt(GPANO_CROPPED_AREA_WIDTH_PROP_NAME) { fields["croppedAreaWidth"] = it } + meta.getSafeInt(GPANO_CROPPED_AREA_HEIGHT_PROP_NAME) { fields["croppedAreaHeight"] = it } + meta.getSafeInt(GPANO_FULL_PANO_WIDTH_PROP_NAME) { fields["fullPanoWidth"] = it } + meta.getSafeInt(GPANO_FULL_PANO_HEIGHT_PROP_NAME) { fields["fullPanoHeight"] = it } + meta.getSafeString(GPANO_PROJECTION_TYPE_PROP_NAME) { fields["projectionType"] = it } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to read XMP directory", e) + } + return fields + } + + fun getTrailingVideoOffsetFromEnd(meta: XMPMeta): Long? { + var offsetFromEnd: Long? = null + if (meta.doesPropExist(GCAMERA_VIDEO_OFFSET_PROP_NAME)) { + // `GCamera` motion photo + meta.getSafeLong(GCAMERA_VIDEO_OFFSET_PROP_NAME) { offsetFromEnd = it } + } else if (meta.doesPropExist(GCONTAINER_DIRECTORY_PROP_NAME)) { + // `Container` motion photo + val count = meta.countPropArrayItems(GCONTAINER_DIRECTORY_PROP_NAME) + for (i in 1 until count + 1) { + val mime = getContainerItemAttribute(meta, i, GCONTAINER_ITEM_MIME_PROP_NAME) + if (MimeTypes.isVideo(mime)) { + getContainerItemAttribute(meta, i, GCONTAINER_ITEM_LENGTH_PROP_NAME)?.let { offsetFromEnd = it.toLong() } + } + } + } + return offsetFromEnd + } + + fun updateTrailingVideoOffset(xmp: String, oldOffset: Number, newOffset: Number): String { + return xmp.replace( + // GCamera motion photo + "${GCAMERA_VIDEO_OFFSET_PROP_NAME}=\"$oldOffset\"", + "${GCAMERA_VIDEO_OFFSET_PROP_NAME}=\"$newOffset\"", + ).replace( + // Container motion photo + "${GCONTAINER_ITEM_LENGTH_PROP_NAME}=\"$oldOffset\"", + "${GCONTAINER_ITEM_LENGTH_PROP_NAME}=\"$newOffset\"", + ) + } + + fun getDeviceContainer(meta: XMPMeta): GoogleDeviceContainer? { + return if (meta.doesPropPathExist(listOf(GDEVICE_CONTAINER_PROP_NAME, GDEVICE_CONTAINER_DIRECTORY_PROP_NAME))) { + GoogleDeviceContainer().apply { findItems(meta) } + } else { + null + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/XMP.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/XMP.kt new file mode 100644 index 0000000..20e6a7a --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/XMP.kt @@ -0,0 +1,317 @@ +package deckers.thibault.aves.metadata.xmp + +import android.content.Context +import android.net.Uri +import android.os.Build +import android.provider.MediaStore +import android.util.Log +import com.adobe.internal.xmp.XMPError +import com.adobe.internal.xmp.XMPException +import com.adobe.internal.xmp.XMPMeta +import com.adobe.internal.xmp.XMPMetaFactory +import com.adobe.internal.xmp.properties.XMPProperty +import com.drew.metadata.Directory +import deckers.thibault.aves.metadata.Mp4ParserHelper +import deckers.thibault.aves.metadata.Mp4ParserHelper.processBoxes +import deckers.thibault.aves.metadata.Mp4ParserHelper.toBytes +import deckers.thibault.aves.metadata.metadataextractor.SafeMp4UuidBoxHandler +import deckers.thibault.aves.metadata.metadataextractor.SafeXmpReader +import deckers.thibault.aves.utils.ContextUtils.queryContentPropValue +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MemoryUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.isIsoBMFFImage +import deckers.thibault.aves.utils.StorageUtils +import org.mp4parser.IsoFile +import org.mp4parser.boxes.UserBox +import java.io.FileInputStream +import java.util.TimeZone + +object XMP { + private val LOG_TAG = LogUtils.createTag<XMP>() + + // BE7ACFCB 97A942E8 9C719994 91E3AFAC / BE7ACFCB-97A9-42E8-9C71-999491E3AFAC + val mp4Uuid = byteArrayOf(0xbe.toByte(), 0x7a, 0xcf.toByte(), 0xcb.toByte(), 0x97.toByte(), 0xa9.toByte(), 0x42, 0xe8.toByte(), 0x9c.toByte(), 0x71, 0x99.toByte(), 0x94.toByte(), 0x91.toByte(), 0xe3.toByte(), 0xaf.toByte(), 0xac.toByte()) + + // standard namespaces + // cf com.adobe.internal.xmp.XMPConst + private const val DC_NS_URI = "http://purl.org/dc/elements/1.1/" + private const val MICROSOFTPHOTO_NS_URI = "http://ns.microsoft.com/photo/1.0/" + private const val PHOTOSHOP_NS_URI = "http://ns.adobe.com/photoshop/1.0/" + private const val XMP_NS_URI = "http://ns.adobe.com/xap/1.0/" + + // other namespaces + private const val APPLE_HDRGM_NS_URI = "http://ns.apple.com/HDRGainMap/1.0/" + private const val HDRGM_NS_URI = "http://ns.adobe.com/hdr-gain-map/1.0/" + private const val PMTM_NS_URI = "http://www.hdrsoft.com/photomatix_settings01" + + val DC_SUBJECT_PROP_NAME = XMPPropName(DC_NS_URI, "subject") + val DC_DESCRIPTION_PROP_NAME = XMPPropName(DC_NS_URI, "description") + val DC_TITLE_PROP_NAME = XMPPropName(DC_NS_URI, "title") + val MS_RATING_PROP_NAME = XMPPropName(MICROSOFTPHOTO_NS_URI, "Rating") + val PS_DATE_CREATED_PROP_NAME = XMPPropName(PHOTOSHOP_NS_URI, "DateCreated") + val XMP_CREATE_DATE_PROP_NAME = XMPPropName(XMP_NS_URI, "CreateDate") + val XMP_RATING_PROP_NAME = XMPPropName(XMP_NS_URI, "Rating") + + private const val GENERIC_LANG = "" + private const val SPECIFIC_LANG = "en-US" + + fun isDataPath(path: String) = GoogleXMP.isDataPath(path) + + // HDR gain map + + private val HDRGM_VERSION_PROP_NAME = XMPPropName(HDRGM_NS_URI, "Version") + private val APPLE_HDRGM_VERSION_PROP_NAME = XMPPropName(APPLE_HDRGM_NS_URI, "HDRGainMapVersion") + + // panorama + + private val PMTM_IS_PANO360_PROP_NAME = XMPPropName(PMTM_NS_URI, "IsPano360") + + // as of `metadata-extractor` v2.18.0, XMP is not discovered in AVIF/HEIC images, + // so we fall back to the native content resolver, if possible + fun checkIsoBMFFImage( + context: Context, + mimeType: String, + uri: Uri, + foundXmp: Boolean, + processXmp: (xmpMeta: XMPMeta) -> Unit, + ) { + if (!foundXmp && isIsoBMFFImage(mimeType) && StorageUtils.isMediaStoreContentUri(uri) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + try { + val xmpBytes = context.queryContentPropValue(uri, mimeType, MediaStore.MediaColumns.XMP) + if (xmpBytes is ByteArray && xmpBytes.isNotEmpty()) { + val xmpMeta = XMPMetaFactory.parseFromBuffer(xmpBytes, SafeXmpReader.PARSE_OPTIONS) + processXmp(xmpMeta) + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get XMP by content resolver for mimeType=$mimeType uri=$uri", e) + } + } + } + + // as of `metadata-extractor` v2.18.0, processing large MP4 files may crash, + // so we fall back to parsing with `mp4parser` + fun checkMp4( + context: Context, + mimeType: String, + uri: Uri, + processDirs: (dirs: List<Directory>) -> Unit, + ) { + if (mimeType != MimeTypes.MP4) return + try { + // we can skip uninteresting boxes with a seekable data source + val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri") + pfd.use { + FileInputStream(it.fileDescriptor).use { stream -> + stream.channel.use { channel -> + // creating `IsoFile` with a `File` or a `File.inputStream()` yields `No such device` + IsoFile(channel, Mp4ParserHelper.metadataBoxParser()).use { isoFile -> + isoFile.processBoxes(UserBox::class.java, true) { box, _ -> + val boxSize = box.size + if (MemoryUtils.canAllocate(boxSize)) { + val bytes = box.toBytes() + val payload = bytes.copyOfRange(8, bytes.size) + + val metadata = com.drew.metadata.Metadata() + SafeMp4UuidBoxHandler(metadata).processBox("", payload, -1, null) + processDirs(metadata.directories.filter { dir -> dir.tagCount > 0 }.toList()) + } else { + Log.w(LOG_TAG, "MP4 box too large at $boxSize bytes, for mimeType=$mimeType uri=$uri") + } + } + } + } + } + } + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to parse MP4 for mimeType=$mimeType uri=$uri", e) + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get XMP by MP4 parser for mimeType=$mimeType uri=$uri", e) + } + } + + // extensions + + fun XMPMeta.hasHdrGainMap(): Boolean { + try { + // standard HDR gain map + if (doesPropExist(HDRGM_VERSION_PROP_NAME)) return true + + // `Ultra HDR` + if (GoogleXMP.isUltraHdPhoto(this)) return true + + // Apple HDR gain map + if (doesPropExist(APPLE_HDRGM_VERSION_PROP_NAME)) return true + + return false + } catch (e: XMPException) { + if (e.errorCode != XMPError.BADSCHEMA) { + // `BADSCHEMA` code is reported when we check a property + // from a non standard namespace, and that namespace is not declared in the XMP + Log.w(LOG_TAG, "failed to check HDR props from XMP", e) + } + } + return false + } + + fun XMPMeta.isMotionPhoto() = GoogleXMP.isMotionPhoto(this) + + fun XMPMeta.isPanorama(): Boolean { + // Google + if (GoogleXMP.isPanorama(this)) return true + + // Photomatix + try { + if (getPropertyString(PMTM_IS_PANO360_PROP_NAME.nsUri, PMTM_IS_PANO360_PROP_NAME.toString()) == "Yes") return true + } catch (e: XMPException) { + if (e.errorCode != XMPError.BADSCHEMA) { + // `BADSCHEMA` code is reported when we check a property + // from a non standard namespace, and that namespace is not declared in the XMP + Log.w(LOG_TAG, "failed to check Photomatix panorama props from XMP", e) + } + } + + return false + } + + fun XMPMeta.doesPropExist(prop: XMPPropName): Boolean { + return doesPropertyExist(prop.nsUri, prop.toString()) + } + + fun XMPMeta.doesPropPathExist(props: List<XMPPropName>): Boolean { + return doesPropertyExist(props.first().nsUri, props.joinToString("/")) + } + + fun XMPMeta.countPropArrayItems(prop: XMPPropName): Int { + return countArrayItems(prop.nsUri, prop.toString()) + } + + fun XMPMeta.countPropPathArrayItems(props: List<XMPPropName>): Int { + return countArrayItems(props.first().nsUri, props.joinToString("/")) + } + + fun XMPMeta.getPropArrayItemValues(prop: XMPPropName): List<String> { + val schema = prop.nsUri + val propName = prop.toString() + val count = countArrayItems(schema, propName) + return (1 until count + 1).map { getArrayItem(schema, propName, it).value } + } + + fun XMPMeta.getSafeInt(prop: XMPPropName, save: (value: Int) -> Unit) { + val schema = prop.nsUri + val propName = prop.toString() + try { + if (doesPropertyExist(schema, propName)) { + val item = getPropertyInteger(schema, propName) + // double check retrieved items as the property sometimes is reported to exist but it is actually null + if (item != null) { + save(item) + } + } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to get int for XMP schema=$schema, propName=$propName", e) + } + } + + fun XMPMeta.getSafeLong(prop: XMPPropName, save: (value: Long) -> Unit) { + val schema = prop.nsUri + val propName = prop.toString() + try { + if (doesPropertyExist(schema, propName)) { + val item = getPropertyLong(schema, propName) + // double check retrieved items as the property sometimes is reported to exist but it is actually null + if (item != null) { + save(item) + } + } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to get long for XMP schema=$schema, propName=$propName", e) + } + } + + fun XMPMeta.getSafeString(prop: XMPPropName, save: (value: String) -> Unit) { + val schema = prop.nsUri + val propName = prop.toString() + try { + if (doesPropertyExist(schema, propName)) { + val item = getPropertyString(schema, propName) + // double check retrieved items as the property sometimes is reported to exist but it is actually null + if (item != null) { + save(item) + } + } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to get int for XMP schema=$schema, propName=$propName", e) + } + } + + fun XMPMeta.getSafeLocalizedText(prop: XMPPropName, acceptBlank: Boolean = true, save: (value: String) -> Unit) { + val schema = prop.nsUri + val propName = prop.toString() + try { + if (doesPropertyExist(schema, propName)) { + val item = getLocalizedText(schema, propName, GENERIC_LANG, SPECIFIC_LANG) + // double check retrieved items as the property sometimes is reported to exist but it is actually null + if (item != null && (acceptBlank || item.value.isNotBlank())) { + save(item.value) + } + } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to get text for XMP schema=$schema, propName=$propName", e) + } + } + + fun XMPMeta.getSafeDateMillis(prop: XMPPropName, save: (value: Long) -> Unit) { + val schema = prop.nsUri + val propName = prop.toString() + try { + if (doesPropertyExist(schema, propName)) { + val item = getPropertyDate(schema, propName) + // double check retrieved items as the property sometimes is reported to exist but it is actually null + if (item != null) { + // strip time zone from XMP dates so that we show date/times as local ones + // this aligns with Exif date/times, which are specified without time zones + item.timeZone = TimeZone.getDefault() + save(item.calendar.timeInMillis) + } + } + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to get date for XMP schema=$schema, propName=$propName", e) + } + } + + // e.g. path 'Container:Directory[42]/Container:Item/Item:Mime' matches: + // - structNs: "http://ns.google.com/photos/1.0/container/" + // - structName: "Container:Directory[42]/Container:Item" + // - fieldNs: "http://ns.google.com/photos/1.0/container/item/" + // - fieldName: "Item:Mime" + fun XMPMeta.getSafeStructField(props: List<Any>): XMPProperty? { + if (props.size >= 2) { + val structFirst = props.first() + val field = props.last() + if (structFirst is XMPPropName && field is XMPPropName) { + val structName = props.take(props.size - 1).mapIndexed { index, prop -> + when (prop) { + is XMPPropName -> "${if (index == 0) "" else "/"}$prop" + is Int -> "[$prop]" + else -> null + } + }.filterNotNull().joinToString("") + val fieldName = field.toString() + + try { + return getStructField(structFirst.nsUri, structName, field.nsUri, fieldName) + } catch (e: XMPException) { + Log.w(LOG_TAG, "failed to get XMP struct field for props=$props", e) + } + } + } + return null + } +} + +class XMPPropName(val nsUri: String, private val prop: String) { + private fun resolve(): String = "${XMPMetaFactory.getSchemaRegistry().getNamespacePrefix(nsUri)}$prop" + + override fun toString(): String = resolve() +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/AvesEntry.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/AvesEntry.kt new file mode 100644 index 0000000..00017e8 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/AvesEntry.kt @@ -0,0 +1,37 @@ +package deckers.thibault.aves.model + +import android.net.Uri +import androidx.core.net.toUri + +class AvesEntry(map: FieldMap) { + val uri: Uri = (map[EntryFields.URI] as String).toUri() // content or file URI + val path = map[EntryFields.PATH] as String? // best effort to get local path + val pageId = map[EntryFields.PAGE_ID] as Int? // null means the main entry + val mimeType = map[EntryFields.MIME_TYPE] as String + val width = map[EntryFields.WIDTH] as Int + val height = map[EntryFields.HEIGHT] as Int + val rotationDegrees = map[EntryFields.ROTATION_DEGREES] as Int + val isFlipped = map[EntryFields.IS_FLIPPED] as Boolean + val sizeBytes = toLong(map[EntryFields.SIZE_BYTES]) + val trashed = map[EntryFields.TRASHED] as Boolean + val trashPath = map[EntryFields.TRASH_PATH] as String? + + private val isRotated: Boolean + get() = rotationDegrees % 180 == 90 + + val displayWidth: Int + get() = if (isRotated) height else width + + val displayHeight: Int + get() = if (isRotated) width else height + + override fun toString(): String = "AvesEntry#${hashCode()}{uri=$uri path=$path pageId=$pageId mimeType=$mimeType width=$width height=$height rotationDegrees=$rotationDegrees isFlipped=$isFlipped sizeBytes=$sizeBytes trashed=$trashed trashPath=$trashPath}" + + companion object { + // convenience method + private fun toLong(o: Any?): Long? = when (o) { + is Int -> o.toLong() + else -> o as? Long + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/EntryFields.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/EntryFields.kt new file mode 100644 index 0000000..1dab12b --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/EntryFields.kt @@ -0,0 +1,29 @@ +package deckers.thibault.aves.model + +// entry fields exported and imported from/to the platform side +// should match `EntryFields` on Dart side +object EntryFields { + const val ORIGIN = "origin" // int + const val URI = "uri" // string + const val CONTENT_ID = "contentId" // long + const val PATH = "path" // string + const val PAGE_ID = "pageId" // int + const val SOURCE_MIME_TYPE = "sourceMimeType" // string + const val MIME_TYPE = "mimeType" // string + + const val WIDTH = "width" // int + const val HEIGHT = "height" // int + const val SOURCE_ROTATION_DEGREES = "sourceRotationDegrees" // int + const val ROTATION_DEGREES = "rotationDegrees" // int + const val IS_FLIPPED = "isFlipped" // boolean + + const val DATE_ADDED_SECS = "dateAddedSecs" // long + const val DATE_MODIFIED_MILLIS = "dateModifiedMillis" // long + const val SOURCE_DATE_TAKEN_MILLIS = "sourceDateTakenMillis" // long + const val DURATION_MILLIS = "durationMillis" // long + + const val SIZE_BYTES = "sizeBytes" // long + const val TRASHED = "trashed" // boolean + const val TRASH_PATH = "trashPath" // string + const val TITLE = "title" // string +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/ExifOrientationOp.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/ExifOrientationOp.kt new file mode 100644 index 0000000..7b7737c --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/ExifOrientationOp.kt @@ -0,0 +1,5 @@ +package deckers.thibault.aves.model + +enum class ExifOrientationOp { + ROTATE_CW, ROTATE_CCW, FLIP +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/FieldMap.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/FieldMap.kt new file mode 100644 index 0000000..78592a2 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/FieldMap.kt @@ -0,0 +1,3 @@ +package deckers.thibault.aves.model + +typealias FieldMap = MutableMap<String, Any?> diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/NameConflictStrategy.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/NameConflictStrategy.kt new file mode 100644 index 0000000..21f59a7 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/NameConflictStrategy.kt @@ -0,0 +1,16 @@ +package deckers.thibault.aves.model + +import java.io.File + +enum class NameConflictStrategy { + RENAME, REPLACE, SKIP; + + companion object { + fun get(name: String?): NameConflictStrategy? { + name ?: return null + return valueOf(name.uppercase()) + } + } +} + +class NameConflictResolution(var nameWithoutExtension: String?, var replacementFile: File?)
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/SourceEntry.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/SourceEntry.kt new file mode 100644 index 0000000..39fccd8 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/SourceEntry.kt @@ -0,0 +1,280 @@ +package deckers.thibault.aves.model + +import android.content.ContentResolver +import android.content.Context +import android.graphics.BitmapFactory +import android.media.MediaMetadataRetriever +import android.net.Uri +import androidx.core.net.toUri +import com.drew.metadata.avi.AviDirectory +import com.drew.metadata.exif.ExifIFD0Directory +import com.drew.metadata.jpeg.JpegDirectory +import com.drew.metadata.mp4.Mp4Directory +import com.drew.metadata.mp4.media.Mp4VideoDirectory +import com.drew.metadata.photoshop.PsdHeaderDirectory +import deckers.thibault.aves.glide.TiffFetcher +import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeDateMillis +import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeInt +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeDateMillis +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeInt +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeLong +import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeString +import deckers.thibault.aves.metadata.Metadata +import deckers.thibault.aves.metadata.Metadata.getRotationDegreesForExifCode +import deckers.thibault.aves.metadata.metadataextractor.Helper +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeDateMillis +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeInt +import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeLong +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.UriUtils.tryParseId +import org.beyka.tiffbitmapfactory.TiffBitmapFactory +import java.io.IOException +import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface + +class SourceEntry { + private val origin: Int + val uri: Uri // content or file URI + var path: String? = null // best effort to get local path + private val sourceMimeType: String + private var title: String? = null + var width: Int? = null + var height: Int? = null + private var sourceRotationDegrees: Int? = null + private var sizeBytes: Long? = null + private var dateAddedSecs: Long? = null + private var dateModifiedMillis: Long? = null + private var sourceDateTakenMillis: Long? = null + private var durationMillis: Long? = null + + private var foundExif: Boolean = false + + constructor(origin: Int, uri: Uri, sourceMimeType: String) { + this.origin = origin + this.uri = uri + this.sourceMimeType = sourceMimeType + } + + constructor(map: FieldMap) { + origin = map[EntryFields.ORIGIN] as Int + uri = (map[EntryFields.URI] as String).toUri() + path = map[EntryFields.PATH] as String? + sourceMimeType = map[EntryFields.SOURCE_MIME_TYPE] as String + width = map[EntryFields.WIDTH] as Int? + height = map[EntryFields.HEIGHT] as Int? + sourceRotationDegrees = map[EntryFields.SOURCE_ROTATION_DEGREES] as Int? + sizeBytes = toLong(map[EntryFields.SIZE_BYTES]) + title = map[EntryFields.TITLE] as String? + dateAddedSecs = toLong(map[EntryFields.DATE_ADDED_SECS]) + dateModifiedMillis = toLong(map[EntryFields.DATE_MODIFIED_MILLIS]) + sourceDateTakenMillis = toLong(map[EntryFields.SOURCE_DATE_TAKEN_MILLIS]) + durationMillis = toLong(map[EntryFields.DURATION_MILLIS]) + } + + fun initFromFile(path: String, title: String, sizeBytes: Long, dateModifiedMillis: Long) { + this.path = path + this.title = title + this.sizeBytes = sizeBytes + this.dateModifiedMillis = dateModifiedMillis + } + + fun toMap(): FieldMap { + return hashMapOf( + EntryFields.ORIGIN to origin, + EntryFields.URI to uri.toString(), + EntryFields.PATH to path, + EntryFields.SOURCE_MIME_TYPE to sourceMimeType, + EntryFields.WIDTH to width, + EntryFields.HEIGHT to height, + EntryFields.SOURCE_ROTATION_DEGREES to (sourceRotationDegrees ?: 0), + EntryFields.SIZE_BYTES to sizeBytes, + EntryFields.TITLE to title, + EntryFields.DATE_ADDED_SECS to dateAddedSecs, + EntryFields.DATE_MODIFIED_MILLIS to dateModifiedMillis, + EntryFields.SOURCE_DATE_TAKEN_MILLIS to sourceDateTakenMillis, + EntryFields.DURATION_MILLIS to durationMillis, + // only for map export + EntryFields.CONTENT_ID to contentId, + ) + } + + // ignore when the ID is not a number + // e.g. content://com.sec.android.app.myfiles.FileProvider/device_storage/20200109_162621.jpg + private val contentId: Long? + get() = if (uri.scheme == ContentResolver.SCHEME_CONTENT) uri.tryParseId() else null + + val isSized: Boolean + get() = (width ?: 0) > 0 && (height ?: 0) > 0 + + private val hasDuration: Boolean + get() = (durationMillis ?: 0) > 0 + + val isVideo: Boolean + get() = MimeTypes.isVideo(sourceMimeType) + + val isSvg: Boolean + get() = sourceMimeType == MimeTypes.SVG + + // metadata retrieval + // expects entry with: uri, mimeType + // finds: width, height, orientation/rotation, date, title, duration + fun fillPreCatalogMetadata(context: Context): SourceEntry { + if (isSvg) return this + if (isVideo) { + fillVideoByMediaMetadataRetriever(context) + if (isSized && hasDuration) return this + fillByMetadataExtractor(context) + } else { + fillByMetadataExtractor(context) + if (isSized && foundExif) return this + fillByExifInterface(context) + } + if (!isSized) { + when (sourceMimeType) { + MimeTypes.TIFF -> fillByTiffDecode(context) + else -> fillByBitmapDecode(context) + } + } + return this + } + + // finds: width, height, orientation, date, duration, title + private fun fillVideoByMediaMetadataRetriever(context: Context) { + val retriever = StorageUtils.openMetadataRetriever(context, uri) ?: return + try { + retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH) { width = it } + retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT) { height = it } + retriever.getSafeLong(MediaMetadataRetriever.METADATA_KEY_DURATION) { durationMillis = it } + retriever.getSafeDateMillis(MediaMetadataRetriever.METADATA_KEY_DATE) { sourceDateTakenMillis = it } + retriever.getSafeString(MediaMetadataRetriever.METADATA_KEY_TITLE) { title = it } + retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION) { sourceRotationDegrees = it } + } catch (_: Exception) { + // ignore + } finally { + // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs + retriever.release() + } + } + + // finds: width, height, orientation, date, duration + private fun fillByMetadataExtractor(context: Context) { + // skip raw images because `metadata-extractor` reports the decoded dimensions instead of the raw dimensions + if (!MimeTypes.canReadWithMetadataExtractor(sourceMimeType) + || MimeTypes.isRaw(sourceMimeType) + ) return + + try { + Metadata.openSafeInputStream(context, uri, sourceMimeType, sizeBytes)?.use { input -> + val metadata = Helper.safeRead(input, sizeBytes) + + // do not switch on specific MIME types, as the reported MIME type could be wrong + // (e.g. PNG registered as JPG) + if (isVideo) { + for (dir in metadata.getDirectoriesOfType(AviDirectory::class.java)) { + dir.getSafeInt(AviDirectory.TAG_WIDTH) { width = it } + dir.getSafeInt(AviDirectory.TAG_HEIGHT) { height = it } + dir.getSafeLong(AviDirectory.TAG_DURATION) { durationMillis = it } + } + for (dir in metadata.getDirectoriesOfType(Mp4VideoDirectory::class.java)) { + dir.getSafeInt(Mp4VideoDirectory.TAG_WIDTH) { width = it } + dir.getSafeInt(Mp4VideoDirectory.TAG_HEIGHT) { height = it } + } + for (dir in metadata.getDirectoriesOfType(Mp4Directory::class.java)) { + dir.getSafeInt(Mp4Directory.TAG_ROTATION) { sourceRotationDegrees = it } + dir.getSafeLong(Mp4Directory.TAG_DURATION) { durationMillis = it } + } + } else { + for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) { + foundExif = true + dir.getSafeInt(ExifIFD0Directory.TAG_IMAGE_WIDTH) { width = it } + dir.getSafeInt(ExifIFD0Directory.TAG_IMAGE_HEIGHT) { height = it } + dir.getSafeInt(ExifIFD0Directory.TAG_ORIENTATION) { sourceRotationDegrees = getRotationDegreesForExifCode(it) } + dir.getSafeDateMillis(ExifIFD0Directory.TAG_DATETIME, null)?.let { sourceDateTakenMillis = it } + } + + // dimensions reported in EXIF do not always match the image + // so we fetch them from the format directory if available + for (dir in metadata.getDirectoriesOfType(JpegDirectory::class.java)) { + dir.getSafeInt(JpegDirectory.TAG_IMAGE_WIDTH) { width = it } + dir.getSafeInt(JpegDirectory.TAG_IMAGE_HEIGHT) { height = it } + } + for (dir in metadata.getDirectoriesOfType(PsdHeaderDirectory::class.java)) { + dir.getSafeInt(PsdHeaderDirectory.TAG_IMAGE_WIDTH) { width = it } + dir.getSafeInt(PsdHeaderDirectory.TAG_IMAGE_HEIGHT) { height = it } + } + } + } + } catch (_: Exception) { + // ignore + } catch (_: NoClassDefFoundError) { + // ignore + } catch (_: AssertionError) { + // ignore + } + } + + // finds: width, height, orientation, date + private fun fillByExifInterface(context: Context) { + if (!MimeTypes.canReadWithExifInterface(sourceMimeType)) return + + try { + Metadata.openSafeInputStream(context, uri, sourceMimeType, sizeBytes)?.use { input -> + val exif = ExifInterface(input) + foundExif = true + exif.getSafeInt(ExifInterface.TAG_IMAGE_WIDTH, acceptZero = false) { width = it } + exif.getSafeInt(ExifInterface.TAG_IMAGE_LENGTH, acceptZero = false) { height = it } + exif.getSafeInt(ExifInterface.TAG_ORIENTATION, acceptZero = false) { sourceRotationDegrees = exif.rotationDegrees } + exif.getSafeDateMillis(ExifInterface.TAG_DATETIME, ExifInterface.TAG_SUBSEC_TIME) { sourceDateTakenMillis = it } + } + } catch (_: Exception) { + // ExifInterface initialization can fail with a RuntimeException + // caused by an internal MediaMetadataRetriever failure + } + } + + // finds: width, height + private fun fillByBitmapDecode(context: Context) { + try { + StorageUtils.openInputStream(context, uri)?.use { input -> + val options = BitmapFactory.Options().apply { + inJustDecodeBounds = true + } + BitmapFactory.decodeStream(input, null, options) + width = options.outWidth + height = options.outHeight + } + } catch (_: IOException) { + // ignore + } + } + + private fun fillByTiffDecode(context: Context) { + try { + context.contentResolver.openFileDescriptor(uri, "r")?.use { pfd -> + val fd = pfd.detachFd() + val options = TiffFetcher.buildOptions().apply { + inJustDecodeBounds = true + } + TiffBitmapFactory.decodeFileDescriptor(fd, options) + width = options.outWidth + height = options.outHeight + } + } catch (_: Exception) { + // ignore + } + } + + companion object { + // convenience method + private fun toLong(o: Any?): Long? = when (o) { + is Int -> o.toLong() + else -> o as? Long + } + + // should match `EntryOrigins` on the Dart side + const val ORIGIN_MEDIA_STORE_CONTENT = 0 + const val ORIGIN_UNKNOWN_CONTENT = 1 + const val ORIGIN_FILE = 2 + const val ORIGIN_VAULT = 3 + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/AvesEmbeddedMediaProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/AvesEmbeddedMediaProvider.kt new file mode 100644 index 0000000..49f0a88 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/AvesEmbeddedMediaProvider.kt @@ -0,0 +1,18 @@ +package deckers.thibault.aves.model.provider + +import android.content.ContentResolver +import android.content.Context +import android.net.Uri +import java.util.Locale + +class AvesEmbeddedMediaProvider : UnknownContentProvider() { + override val reliableProviderMimeType: Boolean + get() = true + + companion object { + fun provides(context: Context, uri: Uri): Boolean { + if (uri.scheme?.lowercase(Locale.ROOT) != ContentResolver.SCHEME_CONTENT) return false + return uri.authority == "${context.applicationContext.packageName}.file_provider" + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/FileImageProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/FileImageProvider.kt new file mode 100644 index 0000000..ce9dabf --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/FileImageProvider.kt @@ -0,0 +1,126 @@ +package deckers.thibault.aves.model.provider + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.net.Uri +import android.util.Log +import android.webkit.MimeTypeMap +import deckers.thibault.aves.model.EntryFields +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.SourceEntry +import deckers.thibault.aves.utils.LogUtils +import java.io.File + +internal class FileImageProvider : ImageProvider() { + override fun fetchSingle(context: Context, uri: Uri, sourceMimeType: String?, allowUnsized: Boolean, callback: ImageOpCallback) { + var mimeType = sourceMimeType + val path = uri.path + + if (mimeType == null) { + // try to guess by file extension + var extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString()) + if (extension.isEmpty() && path != null) { + val lastDotIndex = path.lastIndexOf('.') + if (lastDotIndex >= 0) { + extension = path.substring(lastDotIndex + 1) + } + } + if (extension.isNotEmpty()) { + mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) + } + } + + if (mimeType == null) { + // try to guess by file preview read + var sizeBytes: Long? = null + try { + path?.let { sizeBytes = File(it).length() } + } catch (e: SecurityException) { + callback.onFailure(e) + return + } + mimeType = detectMimeType(context, uri, mimeType = null, sizeBytes) + } + + if (mimeType == null) { + callback.onFailure(Exception("MIME type was not provided and cannot be guessed from extension or preview of uri=$uri")) + return + } + + val entry = SourceEntry(SourceEntry.ORIGIN_FILE, uri, mimeType) + + if (path != null) { + try { + val file = File(path) + if (file.exists()) { + entry.initFromFile( + path = path, + title = file.name, + sizeBytes = file.length(), + dateModifiedMillis = file.lastModified(), + ) + } + } catch (e: SecurityException) { + callback.onFailure(e) + return + } + } + entry.fillPreCatalogMetadata(context) + + if (allowUnsized || entry.isSized || entry.isSvg || entry.isVideo) { + callback.onSuccess(entry.toMap()) + } else { + callback.onFailure(Exception("entry has no size")) + } + } + + override fun delete(contextWrapper: ContextWrapper, uri: Uri, path: String?, mimeType: String) { + path ?: throw Exception("failed to delete file because path is null") + + val file = File(path) + if (file.exists()) { + Log.d(LOG_TAG, "delete file at path=$path") + if (!file.delete()) { + throw Exception("failed to delete entry with uri=$uri path=$path") + } + } + } + + override suspend fun renameSingle( + activity: Activity, + mimeType: String, + oldMediaUri: Uri, + oldPath: String, + newFile: File, + ): FieldMap { + Log.d(LOG_TAG, "rename file at path=$oldPath") + val renamed = File(oldPath).renameTo(newFile) + if (!renamed) { + throw Exception("failed to rename file at path=$oldPath") + } + + return hashMapOf( + EntryFields.URI to Uri.fromFile(newFile).toString(), + EntryFields.PATH to newFile.path, + EntryFields.DATE_MODIFIED_MILLIS to newFile.lastModified(), + ) + } + + override fun scanPostMetadataEdit(context: Context, path: String, uri: Uri, mimeType: String, newFields: FieldMap, callback: ImageOpCallback) { + try { + val file = File(path) + if (file.exists()) { + newFields[EntryFields.DATE_MODIFIED_MILLIS] = file.lastModified() + newFields[EntryFields.SIZE_BYTES] = file.length() + } + callback.onSuccess(newFields) + } catch (e: SecurityException) { + callback.onFailure(e) + } + } + + companion object { + private val LOG_TAG = LogUtils.createTag<MediaStoreImageProvider>() + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProvider.kt new file mode 100644 index 0000000..284238f --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProvider.kt @@ -0,0 +1,1443 @@ +package deckers.thibault.aves.model.provider + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.pm.PackageManager +import android.graphics.Bitmap +import android.graphics.ImageDecoder +import android.net.Uri +import android.os.Binder +import android.os.Build +import android.util.Log +import androidx.core.net.toUri +import com.bumptech.glide.Glide +import com.bumptech.glide.request.FutureTarget +import com.commonsware.cwac.document.DocumentFileCompat +import deckers.thibault.aves.glide.AvesAppGlideModule +import deckers.thibault.aves.metadata.ExifInterfaceHelper +import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeDateMillis +import deckers.thibault.aves.metadata.Metadata +import deckers.thibault.aves.metadata.Metadata.TYPE_EXIF +import deckers.thibault.aves.metadata.Metadata.TYPE_IPTC +import deckers.thibault.aves.metadata.Metadata.TYPE_MP4 +import deckers.thibault.aves.metadata.Metadata.TYPE_XMP +import deckers.thibault.aves.metadata.Mp4ParserHelper +import deckers.thibault.aves.metadata.Mp4ParserHelper.updateLocation +import deckers.thibault.aves.metadata.Mp4ParserHelper.updateRotation +import deckers.thibault.aves.metadata.Mp4ParserHelper.updateXmp +import deckers.thibault.aves.metadata.MultiPage +import deckers.thibault.aves.metadata.PixyMetaHelper +import deckers.thibault.aves.metadata.PixyMetaHelper.extendedXmpDocString +import deckers.thibault.aves.metadata.PixyMetaHelper.xmpDocString +import deckers.thibault.aves.metadata.metadataextractor.Helper +import deckers.thibault.aves.metadata.xmp.GoogleXMP +import deckers.thibault.aves.model.AvesEntry +import deckers.thibault.aves.model.EntryFields +import deckers.thibault.aves.model.ExifOrientationOp +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.NameConflictResolution +import deckers.thibault.aves.model.NameConflictStrategy +import deckers.thibault.aves.model.SourceEntry +import deckers.thibault.aves.utils.BitmapUtils +import deckers.thibault.aves.utils.BmpWriter +import deckers.thibault.aves.utils.FileUtils.transferFrom +import deckers.thibault.aves.utils.FileUtils.transferTo +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.canEditExif +import deckers.thibault.aves.utils.MimeTypes.canEditIptc +import deckers.thibault.aves.utils.MimeTypes.canEditXmp +import deckers.thibault.aves.utils.MimeTypes.canReadWithExifInterface +import deckers.thibault.aves.utils.MimeTypes.canRemoveMetadata +import deckers.thibault.aves.utils.MimeTypes.extensionFor +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.StorageUtils +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.ByteArrayInputStream +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.OutputStream +import java.nio.channels.Channels +import java.util.Date +import java.util.TimeZone +import kotlin.math.absoluteValue +import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface + +abstract class ImageProvider { + open fun fetchSingle(context: Context, uri: Uri, sourceMimeType: String?, allowUnsized: Boolean, callback: ImageOpCallback) { + callback.onFailure(UnsupportedOperationException("`fetchSingle` is not supported by this image provider")) + } + + suspend fun scanNewPath(context: Context, path: String, mimeType: String): FieldMap { + return if (StorageUtils.isInVault(context, path)) { + val uri = Uri.fromFile(File(path)) + hashMapOf( + EntryFields.ORIGIN to SourceEntry.ORIGIN_VAULT, + EntryFields.URI to uri.toString(), + EntryFields.CONTENT_ID to null, + EntryFields.PATH to path, + ) + } else { + MediaStoreImageProvider().scanNewPathByMediaStore(context, path, mimeType) + } + } + + private fun deletePath(contextWrapper: ContextWrapper, path: String, mimeType: String) { + if (StorageUtils.isInVault(contextWrapper, path)) { + FileImageProvider().apply { + val uri = Uri.fromFile(File(path)) + delete(contextWrapper, uri, path, mimeType) + } + } else { + MediaStoreImageProvider().apply { + val uri = getContentUriForPath(contextWrapper, path) + uri ?: throw Exception("failed to find content URI for path=$path") + delete(contextWrapper, uri, path, mimeType) + } + } + } + + open fun delete(contextWrapper: ContextWrapper, uri: Uri, path: String?, mimeType: String) { + throw UnsupportedOperationException("`delete` is not supported by this image provider") + } + + open suspend fun moveMultiple( + activity: Activity, + copy: Boolean, + nameConflictStrategy: NameConflictStrategy, + entriesByTargetDir: Map<String, List<AvesEntry>>, + isCancelledOp: CancelCheck, + callback: ImageOpCallback, + ) { + callback.onFailure(UnsupportedOperationException("`moveMultiple` is not supported by this image provider")) + } + + suspend fun renameMultiple( + activity: Activity, + entriesToNewName: Map<AvesEntry, String>, + isCancelledOp: CancelCheck, + callback: ImageOpCallback, + ) { + for (kv in entriesToNewName) { + val entry = kv.key + val desiredName = kv.value + + val sourceUri = entry.uri + val sourcePath = entry.path + val mimeType = entry.mimeType + + val result: FieldMap = hashMapOf( + "uri" to sourceUri.toString(), + "success" to false, + ) + + if (sourcePath != null) { + try { + var newFields: FieldMap = skippedFieldMap + if (!isCancelledOp()) { + val desiredNameWithoutExtension = desiredName.substringBeforeLast(".") + + val oldFile = File(sourcePath) + if (oldFile.nameWithoutExtension != desiredNameWithoutExtension) { + val defaultExtension = oldFile.extension + oldFile.parent?.let { dir -> + val resolution = resolveTargetFileNameWithoutExtension( + contextWrapper = activity, + dir = dir, + desiredNameWithoutExtension = desiredNameWithoutExtension, + mimeType = mimeType, + defaultExtension = defaultExtension, + conflictStrategy = NameConflictStrategy.RENAME, + ) + resolution.nameWithoutExtension?.let { targetNameWithoutExtension -> + val targetFileName = "$targetNameWithoutExtension${extensionFor(mimeType, defaultExtension)}" + val newFile = File(dir, targetFileName) + if (oldFile != newFile) { + newFields = renameSingle( + activity = activity, + mimeType = mimeType, + oldMediaUri = sourceUri, + oldPath = sourcePath, + newFile = newFile, + ) + } + } + } + } + } + result["newFields"] = newFields + result["success"] = true + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to rename to newFileName=$desiredName entry with sourcePath=$sourcePath", e) + } + } + callback.onSuccess(result) + } + } + + open suspend fun renameSingle( + activity: Activity, + mimeType: String, + oldMediaUri: Uri, + oldPath: String, + newFile: File, + ): FieldMap { + throw UnsupportedOperationException("`renameSingle` is not supported by this image provider") + } + + open fun scanPostMetadataEdit(context: Context, path: String, uri: Uri, mimeType: String, newFields: FieldMap, callback: ImageOpCallback) { + throw UnsupportedOperationException("`scanPostMetadataEdit` is not supported by this image provider") + } + + suspend fun convertMultiple( + activity: Activity, + imageExportMimeType: String, + targetDir: String, + entries: List<AvesEntry>, + quality: Int, + lengthUnit: String, + width: Int, + height: Int, + writeMetadata: Boolean, + nameConflictStrategy: NameConflictStrategy, + callback: ImageOpCallback, + ) { + if (!supportedExportMimeTypes.contains(imageExportMimeType)) { + callback.onFailure(Exception("unsupported export MIME type=$imageExportMimeType")) + return + } + + val targetDirDocFile = StorageUtils.createDirectoryDocIfAbsent(activity, targetDir) + if (!File(targetDir).exists()) { + callback.onFailure(Exception("failed to create directory at path=$targetDir")) + return + } + + for (entry in entries) { + val sourceUri = entry.uri + val sourcePath = entry.path + val pageId = entry.pageId + + val result: FieldMap = hashMapOf( + "uri" to sourceUri.toString(), + "pageId" to pageId, + "success" to false, + ) + + val sourceMimeType = entry.mimeType + val exportMimeType = if (isVideo(sourceMimeType)) sourceMimeType else imageExportMimeType + try { + val newFields = convertSingle( + activity = activity, + sourceEntry = entry, + targetDir = targetDir, + targetDirDocFile = targetDirDocFile, + quality = quality, + lengthUnit = lengthUnit, + width = width, + height = height, + writeMetadata = writeMetadata, + nameConflictStrategy = nameConflictStrategy, + exportMimeType = exportMimeType, + ) + result["newFields"] = newFields + result["success"] = true + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to convert to targetDir=$targetDir entry with sourcePath=$sourcePath pageId=$pageId", e) + } + callback.onSuccess(result) + } + } + + private suspend fun convertSingle( + activity: Activity, + sourceEntry: AvesEntry, + targetDir: String, + targetDirDocFile: DocumentFileCompat?, + quality: Int, + lengthUnit: String, + width: Int, + height: Int, + writeMetadata: Boolean, + nameConflictStrategy: NameConflictStrategy, + exportMimeType: String, + ): FieldMap { + val sourceMimeType = sourceEntry.mimeType + var sourceUri = sourceEntry.uri + val pageId = sourceEntry.pageId + + var desiredNameWithoutExtension = if (sourceEntry.path != null) { + val sourceFileName = File(sourceEntry.path).name + sourceFileName.substringBeforeLast(".") + } else { + sourceUri.lastPathSegment!! + } + if (pageId != null) { + val page = if (sourceMimeType == MimeTypes.TIFF) pageId + 1 else pageId + desiredNameWithoutExtension += "_${page.toString().padStart(3, '0')}" + } + + // there is no benefit providing input extension + // for known output MIME type + val defaultExtension = null + + val resolution = resolveTargetFileNameWithoutExtension( + contextWrapper = activity, + dir = targetDir, + desiredNameWithoutExtension = desiredNameWithoutExtension, + mimeType = exportMimeType, + defaultExtension = defaultExtension, + conflictStrategy = nameConflictStrategy, + ) + val targetNameWithoutExtension = resolution.nameWithoutExtension ?: return skippedFieldMap + resolution.replacementFile?.let { file -> + sourceUri = Uri.fromFile(file) + } + + val targetMimeType: String + val write: (OutputStream) -> Unit + var target: FutureTarget<Bitmap>? = null + try { + if (isVideo(sourceMimeType)) { + targetMimeType = sourceMimeType + write = { output -> + val sourceDocFile = DocumentFileCompat.fromSingleUri(activity, sourceUri) + sourceDocFile.copyTo(output) + } + } else { + var targetWidthPx: Int + var targetHeightPx: Int + when (lengthUnit) { + LENGTH_UNIT_PERCENT -> { + targetWidthPx = sourceEntry.displayWidth * width / 100 + targetHeightPx = sourceEntry.displayHeight * height / 100 + } + + else -> { + targetWidthPx = width + targetHeightPx = height + } + } + + val rotationDegrees = sourceEntry.rotationDegrees + val needRotationAfterGlide = MimeTypes.needRotationAfterGlide(sourceMimeType, pageId) + if (rotationDegrees != 0 && needRotationAfterGlide) { + targetWidthPx = targetHeightPx.also { targetHeightPx = targetWidthPx } + } + + target = Glide.with(activity.applicationContext) + .asBitmap() + .apply(AvesAppGlideModule.uncachedFullImageOptions) + .load(AvesAppGlideModule.getModel(activity, sourceUri, sourceMimeType, pageId, sourceEntry.sizeBytes)) + .submit(targetWidthPx, targetHeightPx) + + var bitmap = withContext(Dispatchers.IO) { target.get() } + if (needRotationAfterGlide) { + bitmap = BitmapUtils.applyExifOrientation(activity, bitmap, rotationDegrees, sourceEntry.isFlipped) + } + bitmap ?: throw Exception("failed to get image for mimeType=$sourceMimeType uri=$sourceUri page=$pageId") + + targetMimeType = exportMimeType + write = { output -> + if (exportMimeType == MimeTypes.BMP) { + BmpWriter.writeRGB24(bitmap, output) + } else { + val format = when (exportMimeType) { + MimeTypes.JPEG -> Bitmap.CompressFormat.JPEG + MimeTypes.PNG -> Bitmap.CompressFormat.PNG + MimeTypes.WEBP -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + if (quality == 100) { + Bitmap.CompressFormat.WEBP_LOSSLESS + } else { + Bitmap.CompressFormat.WEBP_LOSSY + } + } else { + @Suppress("deprecation") + Bitmap.CompressFormat.WEBP + } + + else -> throw Exception("unsupported export MIME type=$exportMimeType") + } + bitmap.compress(format, quality, output) + } + } + } + + val targetPath = MediaStoreImageProvider().createSingle( + activity = activity, + mimeType = targetMimeType, + targetDir = targetDir, + targetDirDocFile = targetDirDocFile, + targetNameWithoutExtension = targetNameWithoutExtension, + defaultExtension = defaultExtension, + write = write, + ) + + val newFields = scanNewPath(activity, targetPath, exportMimeType) + val targetUri = (newFields[EntryFields.URI] as String).toUri() + if (writeMetadata) { + copyMetadata( + context = activity, + sourceMimeType = sourceMimeType, + sourceUri = sourceUri, + targetMimeType = targetMimeType, + targetUri = targetUri, + targetPath = targetPath, + ) + } + + return newFields + } finally { + // clearing Glide target should happen after effectively writing the bitmap + Glide.with(activity.applicationContext).clear(target) + + resolution.replacementFile?.delete() + } + } + + private fun copyMetadata( + context: Context, + sourceMimeType: String, + sourceUri: Uri, + targetMimeType: String, + targetUri: Uri, + targetPath: String, + ) { + val editableFile = StorageUtils.createTempFile(context).apply { + // copy original file to a temporary file for editing + val inputStream = StorageUtils.openInputStream(context, targetUri) + transferFrom(inputStream, File(targetPath).length()) + } + + // copy IPTC / XMP via PixyMeta + PixyMetaHelper.copyIptcXmp(context, sourceMimeType, sourceUri, targetMimeType, targetUri, editableFile) + + // copy Exif via ExifInterface + + val exif = HashMap<String, String?>() + val skippedTags = listOf( + ExifInterface.TAG_IMAGE_LENGTH, + ExifInterface.TAG_IMAGE_WIDTH, + ExifInterface.TAG_ORIENTATION, + // Thumbnail Offset / Length + ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT, + ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, + // Exif Image Width / Height + ExifInterface.TAG_PIXEL_X_DIMENSION, + ExifInterface.TAG_PIXEL_Y_DIMENSION, + ) + if (canReadWithExifInterface(sourceMimeType) && canEditExif(targetMimeType)) { + StorageUtils.openInputStream(context, sourceUri)?.use { input -> + ExifInterface(input).apply { + ExifInterfaceHelper.allTags.keys.filterNot { skippedTags.contains(it) }.filter { hasAttribute(it) }.forEach { tag -> + exif[tag] = getAttribute(tag) + } + } + } + } + if (exif.isNotEmpty()) { + ExifInterface(editableFile).apply { + exif.entries.forEach { (tag, value) -> + setAttribute(tag, value) + } + saveAttributes() + } + } + + // copy the edited temporary file back to the original + editableFile.transferTo(outputStream(context, targetMimeType, targetUri, targetPath)) + editableFile.delete() + } + + suspend fun captureFrame( + contextWrapper: ContextWrapper, + desiredNameWithoutExtension: String, + exifFields: FieldMap, + bytes: ByteArray, + targetDir: String, + nameConflictStrategy: NameConflictStrategy, + callback: ImageOpCallback, + ) { + val targetDirDocFile = StorageUtils.createDirectoryDocIfAbsent(contextWrapper, targetDir) + if (!File(targetDir).exists()) { + callback.onFailure(Exception("failed to create directory at path=$targetDir")) + return + } + + // TODO TLAD [storage] allow inserting by Media Store + if (targetDirDocFile == null) { + callback.onFailure(Exception("failed to get tree doc for directory at path=$targetDir")) + return + } + + val captureMimeType = MimeTypes.JPEG + val resolution = try { + resolveTargetFileNameWithoutExtension( + contextWrapper = contextWrapper, + dir = targetDir, + desiredNameWithoutExtension = desiredNameWithoutExtension, + mimeType = captureMimeType, + defaultExtension = null, + conflictStrategy = nameConflictStrategy, + ) + } catch (e: Exception) { + callback.onFailure(e) + return + } + + val targetNameWithoutExtension = resolution.nameWithoutExtension + if (targetNameWithoutExtension == null) { + // skip it + callback.onSuccess(skippedFieldMap) + return + } + + // the file created from a `TreeDocumentFile` is also a `TreeDocumentFile` + // but in order to open an output stream to it, we need to use a `SingleDocumentFile` + // through a document URI, not a tree URI + // note that `DocumentFile.getParentFile()` returns null if we did not pick a tree first + val targetTreeFile = targetDirDocFile.createFile(captureMimeType, targetNameWithoutExtension) + val targetDocFile = DocumentFileCompat.fromSingleUri(contextWrapper, targetTreeFile.uri) + + try { + if (exifFields.isEmpty()) { + targetDocFile.openOutputStream().use { output -> + output.write(bytes) + } + } else { + val editableFile = withContext(Dispatchers.IO) { StorageUtils.createTempFile(contextWrapper) }.apply { + transferFrom(ByteArrayInputStream(bytes), bytes.size.toLong()) + } + + val exif = ExifInterface(editableFile) + + val rotationDegrees = exifFields["rotationDegrees"] as Int? + if (rotationDegrees != null) { + // when the orientation is not defined, it returns `undefined (0)` instead of the orientation default value `normal (1)` + // in that case we explicitly set it to `normal` first + // because ExifInterface fails to rotate an image with undefined orientation + // as of androidx.exifinterface:exifinterface:1.3.0 + val currentOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) + if (currentOrientation == ExifInterface.ORIENTATION_UNDEFINED) { + exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL.toString()) + } + exif.rotate(rotationDegrees) + } + + val dateTimeMillis = (exifFields["dateTimeMillis"] as Number?)?.toLong() + if (dateTimeMillis != null) { + val dateString = ExifInterfaceHelper.DATETIME_FORMAT.format(Date(dateTimeMillis)) + exif.setAttribute(ExifInterface.TAG_DATETIME, dateString) + exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateString) + + val timeZoneString = getTimeZoneString(TimeZone.getDefault(), dateTimeMillis) + exif.setAttribute(ExifInterface.TAG_OFFSET_TIME, timeZoneString) + exif.setAttribute(ExifInterface.TAG_OFFSET_TIME_ORIGINAL, timeZoneString) + + val sub = dateTimeMillis % 1000 + if (sub > 0) { + val subString = sub.toString() + exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME, subString) + exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, subString) + } + } + + val latitude = (exifFields["latitude"] as Number?)?.toDouble() + val longitude = (exifFields["longitude"] as Number?)?.toDouble() + if (latitude != null && longitude != null) { + exif.setLatLong(latitude, longitude) + } + + exif.saveAttributes() + + // copy the edited temporary file back to the original + DocumentFileCompat.fromFile(editableFile).copyTo(targetDocFile) + editableFile.delete() + } + + val fileName = targetDocFile.name + val targetFullPath = targetDir + fileName + val newFields = scanNewPath(contextWrapper, targetFullPath, captureMimeType) + callback.onSuccess(newFields) + } catch (e: Exception) { + callback.onFailure(e) + } + } + + fun createTimeStampFileName() = Date().time.toString() + + private fun sanitizeDesiredFileName(desiredName: String): String { + var name = desiredName + // prevent creating hidden files + while (name.isNotEmpty() && name.startsWith(".")) { + name = name.substring(1) + } + if (name.isEmpty()) { + name = createTimeStampFileName() + } + return name + } + + // returns available name to use, or `null` to skip it + fun resolveTargetFileNameWithoutExtension( + contextWrapper: ContextWrapper, + dir: String, + desiredNameWithoutExtension: String, + mimeType: String, + defaultExtension: String?, + conflictStrategy: NameConflictStrategy, + ): NameConflictResolution { + val sanitizedNameWithoutExtension = sanitizeDesiredFileName(desiredNameWithoutExtension) + var resolvedName: String? = sanitizedNameWithoutExtension + var replacementFile: File? = null + + val extension = extensionFor(mimeType, defaultExtension) + val targetFile = File(dir, "$sanitizedNameWithoutExtension$extension") + when (conflictStrategy) { + NameConflictStrategy.RENAME -> { + var nameWithoutExtension = sanitizedNameWithoutExtension + var i = 0 + while (File(dir, "$nameWithoutExtension$extension").exists()) { + i++ + nameWithoutExtension = "$sanitizedNameWithoutExtension ($i)" + } + resolvedName = nameWithoutExtension + } + + NameConflictStrategy.REPLACE -> { + if (targetFile.exists()) { + // move replaced file to temp storage + // so that it can be used as a source for conversion or metadata copy + replacementFile = StorageUtils.createTempFile(contextWrapper).apply { + targetFile.transferTo(outputStream()) + } + deletePath(contextWrapper, targetFile.path, mimeType) + } + } + + NameConflictStrategy.SKIP -> { + if (targetFile.exists()) { + resolvedName = null + } + } + } + + return NameConflictResolution(resolvedName, replacementFile) + } + + // cf `MetadataFetchHandler.getCatalogMetadataByMetadataExtractor()` for a more thorough check + fun detectMimeType(context: Context, uri: Uri, mimeType: String?, sizeBytes: Long?): String? { + var detectedMimeType: String? = null + if (MimeTypes.canReadWithMetadataExtractor(mimeType)) { + try { + Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input -> + detectedMimeType = Helper.readMimeType(input) + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e) + } + } + return detectedMimeType + } + + private fun editExif( + context: Context, + path: String, + uri: Uri, + mimeType: String, + callback: ImageOpCallback, + autoCorrectTrailerOffset: Boolean = true, + trailerDiff: Int = 0, + edit: (exif: ExifInterface) -> Unit, + ): Boolean { + if (!canEditExif(mimeType)) { + callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType")) + return false + } + + val originalFileSize = File(path).length() + var trailerVideoBytes: ByteArray? = null + val editableFile = StorageUtils.createTempFile(context).apply { + val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize)?.let { it + trailerDiff } + val isTrailerVideoValid = trailerVideoSize != null && MultiPage.getTrailerVideoInfo(context, uri, originalFileSize, trailerVideoSize) != null + try { + if (trailerVideoSize != null && isTrailerVideoValid) { + // handle motion photo and embedded video separately + val imageSize = (originalFileSize - trailerVideoSize).toInt() + val videoByteSize = trailerVideoSize.toInt() + trailerVideoBytes = ByteArray(videoByteSize) + + StorageUtils.openInputStream(context, uri)?.let { input -> + val imageBytes = ByteArray(imageSize) + input.read(imageBytes, 0, imageSize) + input.read(trailerVideoBytes, 0, videoByteSize) + + // copy only the image to a temporary file for editing + // video will be appended after metadata modification + transferFrom(ByteArrayInputStream(imageBytes), imageBytes.size.toLong()) + } + } else { + // copy original file to a temporary file for editing + val inputStream = StorageUtils.openInputStream(context, uri) + transferFrom(inputStream, originalFileSize) + } + } catch (e: Exception) { + callback.onFailure(e) + return false + } + } + + try { + edit(ExifInterface(editableFile)) + + val editableFileSizeBytes = editableFile.length() + if (editableFileSizeBytes == 0L) { + callback.onFailure(Exception("editing Exif yielded an empty file")) + return false + } + + val editedMimeType = detectMimeType(context, Uri.fromFile(editableFile), mimeType, editableFileSizeBytes) + if (editedMimeType != mimeType) { + throw Exception("editing Exif changes mimeType=$mimeType -> $editedMimeType for uri=$uri path=$path") + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + // editing may corrupt the file for various reasons, + // so we check whether decoding it throws an exception + ImageDecoder.decodeBitmap(ImageDecoder.createSource(editableFile)) + } + + if (trailerVideoBytes != null) { + // append trailer video, if any + editableFile.appendBytes(trailerVideoBytes) + } + + // copy the edited temporary file back to the original + editableFile.transferTo(outputStream(context, mimeType, uri, path)) + + if (autoCorrectTrailerOffset && !checkTrailerOffset(context, path, uri, mimeType, trailerVideoBytes?.size, editableFile, callback)) { + return false + } + editableFile.delete() + } catch (e: IOException) { + callback.onFailure(e) + return false + } + + return true + } + + private fun editIptc( + context: Context, + path: String, + uri: Uri, + mimeType: String, + callback: ImageOpCallback, + autoCorrectTrailerOffset: Boolean = true, + trailerDiff: Int = 0, + iptc: List<FieldMap>?, + ): Boolean { + if (!canEditIptc(mimeType)) { + callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType")) + return false + } + + val originalFileSize = File(path).length() + var trailerVideoBytes: ByteArray? = null + val editableFile = StorageUtils.createTempFile(context).apply { + val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize)?.let { it + trailerDiff } + val isTrailerVideoValid = trailerVideoSize != null && MultiPage.getTrailerVideoInfo(context, uri, originalFileSize, trailerVideoSize) != null + try { + if (trailerVideoSize != null && isTrailerVideoValid) { + // handle motion photo and embedded video separately + val imageSize = (originalFileSize - trailerVideoSize).toInt() + val videoByteSize = trailerVideoSize.toInt() + trailerVideoBytes = ByteArray(videoByteSize) + + StorageUtils.openInputStream(context, uri)?.let { input -> + val imageBytes = ByteArray(imageSize) + input.read(imageBytes, 0, imageSize) + input.read(trailerVideoBytes, 0, videoByteSize) + + // copy only the image to a temporary file for editing + // video will be appended after metadata modification + transferFrom(ByteArrayInputStream(imageBytes), imageBytes.size.toLong()) + } + } else { + // copy original file to a temporary file for editing + val inputStream = StorageUtils.openInputStream(context, uri) + transferFrom(inputStream, originalFileSize) + } + } catch (e: Exception) { + callback.onFailure(e) + return false + } + } + + try { + editableFile.outputStream().use { output -> + // reopen input to read from start + StorageUtils.openInputStream(context, uri)?.use { input -> + when { + iptc != null -> + PixyMetaHelper.setIptc(input, output, iptc) + + canRemoveMetadata(mimeType) -> + PixyMetaHelper.removeMetadata(input, output, setOf(TYPE_IPTC)) + + else -> { + Log.w(LOG_TAG, "setting empty IPTC for mimeType=$mimeType") + PixyMetaHelper.setIptc(input, output, null) + } + } + } + } + + if (editableFile.length() == 0L) { + callback.onFailure(Exception("editing IPTC yielded an empty file")) + return false + } + + if (trailerVideoBytes != null) { + // append trailer video, if any + editableFile.appendBytes(trailerVideoBytes) + } + + // copy the edited temporary file back to the original + editableFile.transferTo(outputStream(context, mimeType, uri, path)) + + if (autoCorrectTrailerOffset && !checkTrailerOffset(context, path, uri, mimeType, trailerVideoBytes?.size, editableFile, callback)) { + return false + } + editableFile.delete() + } catch (e: IOException) { + callback.onFailure(e) + return false + } + + return true + } + + private fun editMp4Metadata( + context: Context, + path: String, + uri: Uri, + mimeType: String, + callback: ImageOpCallback, + fieldsToEdit: Map<*, *>, + newFields: FieldMap? = null, + ): Boolean { + if (mimeType != MimeTypes.MP4) { + callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType")) + return false + } + + try { + val edits = Mp4ParserHelper.computeEdits(context, uri) { isoFile -> + fieldsToEdit.forEach { kv -> + val tag = kv.key as String + val value = kv.value as String? + when (tag) { + "gpsCoordinates" -> isoFile.updateLocation(value) + "rotationDegrees" -> { + val degrees = value?.toIntOrNull() ?: throw Exception("failed because of invalid rotation=$value") + if (isoFile.updateRotation(degrees) && newFields != null) { + newFields["rotationDegrees"] = degrees + } + } + + "xmp" -> isoFile.updateXmp(value) + } + } + } + + val pfd = StorageUtils.openOutputFileDescriptor( + context = context, + mimeType = mimeType, + uri = uri, + path = path, + // do not truncate with "t" + // "w" is enough on API 29+, but it will yield an empty file on API <29 + // so "r" is necessary for backward compatibility + mode = "rw", + ) ?: throw Exception("failed to open file descriptor for uri=$uri path=$path") + pfd.use { + FileOutputStream(it.fileDescriptor).use { outputStream -> + outputStream.channel.use { outputChannel -> + edits.forEach { (offset, bytes) -> + bytes.inputStream().use { inputStream -> + Channels.newChannel(inputStream).use { inputChannel -> + outputChannel.transferFrom(inputChannel, offset, bytes.size.toLong()) + } + } + } + } + } + } + } catch (e: NoClassDefFoundError) { + callback.onFailure(e) + return false + } catch (e: Exception) { + callback.onFailure(e) + return false + } + + return true + } + + // provide `editCoreXmp` to modify existing core XMP, + // or provide `coreXmp` and `extendedXmp` to set them + private fun editXmp( + context: Context, + path: String, + uri: Uri, + mimeType: String, + callback: ImageOpCallback, + autoCorrectTrailerOffset: Boolean = true, + trailerDiff: Int = 0, + coreXmp: String? = null, + extendedXmp: String? = null, + editCoreXmp: ((xmp: String) -> String)? = null, + ): Boolean { + if (!canEditXmp(mimeType)) { + callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType")) + return false + } + + if (mimeType == MimeTypes.MP4) { + return editMp4Metadata( + context = context, + path = path, + uri = uri, + mimeType = mimeType, + callback = callback, + fieldsToEdit = mapOf("xmp" to coreXmp), + ) + } + + val originalFileSize = File(path).length() + val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize)?.let { it.toInt() + trailerDiff } + val editableFile = StorageUtils.createTempFile(context).apply { + try { + editXmpWithPixy( + context = context, + uri = uri, + mimeType = mimeType, + coreXmp = coreXmp, + extendedXmp = extendedXmp, + editCoreXmp = editCoreXmp, + editableFile = this + ) + } catch (e: Exception) { + callback.onFailure(e) + return false + } + } + + if (editableFile.length() == 0L) { + callback.onFailure(Exception("editing XMP yielded an empty file")) + return false + } + + try { + // copy the edited temporary file back to the original + editableFile.transferTo(outputStream(context, mimeType, uri, path)) + + if (autoCorrectTrailerOffset && !checkTrailerOffset(context, path, uri, mimeType, trailerVideoSize, editableFile, callback)) { + return false + } + editableFile.delete() + } catch (e: IOException) { + callback.onFailure(e) + return false + } + + return true + } + + private fun editXmpWithPixy( + context: Context, + uri: Uri, + mimeType: String, + coreXmp: String?, + extendedXmp: String?, + editCoreXmp: ((xmp: String) -> String)?, + editableFile: File + ) { + var editedXmpString = coreXmp + var editedExtendedXmp = extendedXmp + if (editCoreXmp != null) { + val pixyXmp = StorageUtils.openInputStream(context, uri)?.use { input -> PixyMetaHelper.getXmp(input) } + if (pixyXmp != null) { + editedXmpString = editCoreXmp(pixyXmp.xmpDocString()) + if (pixyXmp.hasExtendedXmp()) { + editedExtendedXmp = pixyXmp.extendedXmpDocString() + } + } + } + + editableFile.outputStream().use { output -> + // reopen input to read from start + StorageUtils.openInputStream(context, uri)?.use { input -> + if (editedXmpString != null) { + if (editedExtendedXmp != null && mimeType != MimeTypes.JPEG) { + Log.w(LOG_TAG, "extended XMP is not supported by mimeType=$mimeType") + PixyMetaHelper.setXmp(input, output, editedXmpString, null) + } else { + PixyMetaHelper.setXmp(input, output, editedXmpString, editedExtendedXmp) + } + } else if (canRemoveMetadata(mimeType)) { + PixyMetaHelper.removeMetadata(input, output, setOf(TYPE_XMP)) + } else { + Log.w(LOG_TAG, "setting empty XMP for mimeType=$mimeType") + PixyMetaHelper.setXmp(input, output, null, null) + } + } + } + } + + // A few bytes are sometimes appended when writing to a document output stream. + // In that case, we need to adjust the trailer video offset accordingly and rewrite the file. + // returns whether the file at `path` is fine + private fun checkTrailerOffset( + context: Context, + path: String, + uri: Uri, + mimeType: String, + trailerOffset: Number?, + editedFile: File, + callback: ImageOpCallback, + ): Boolean { + if (trailerOffset == null) return true + + val expectedLength = editedFile.length() + val actualLength = File(path).length() + val diff = (actualLength - expectedLength).toInt() + if (diff == 0) return true + + Log.w( + LOG_TAG, "Edited file length=$expectedLength does not match final document file length=$actualLength. " + + "We need to edit XMP to adjust trailer video offset by $diff bytes." + ) + val newTrailerOffset = trailerOffset.toLong() + diff + return editXmp(context, path, uri, mimeType, callback, trailerDiff = diff, editCoreXmp = { xmp -> + GoogleXMP.updateTrailingVideoOffset(xmp, trailerOffset, newTrailerOffset) + }) + } + + fun editOrientation( + context: Context, + path: String, + uri: Uri, + mimeType: String, + op: ExifOrientationOp, + callback: ImageOpCallback, + ) { + val newFields: FieldMap = hashMapOf() + + val success = editExif(context, path, uri, mimeType, callback) { exif -> + // when the orientation is not defined, it returns `undefined (0)` instead of the orientation default value `normal (1)` + // in that case we explicitly set it to `normal` first + // because ExifInterface fails to rotate an image with undefined orientation + // as of androidx.exifinterface:exifinterface:1.3.0 + val currentOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) + if (currentOrientation == ExifInterface.ORIENTATION_UNDEFINED) { + exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL.toString()) + } + when (op) { + ExifOrientationOp.ROTATE_CW -> exif.rotate(90) + ExifOrientationOp.ROTATE_CCW -> exif.rotate(-90) + ExifOrientationOp.FLIP -> exif.flipHorizontally() + } + exif.saveAttributes() + newFields["rotationDegrees"] = exif.rotationDegrees + newFields["isFlipped"] = exif.isFlipped + } + + if (success) { + scanPostMetadataEdit(context, path, uri, mimeType, newFields, callback) + } + } + + fun editDate( + context: Context, + path: String, + uri: Uri, + mimeType: String, + dateMillis: Long?, + shiftSeconds: Long?, + fields: List<String>, + callback: ImageOpCallback, + ) { + val success = editExif(context, path, uri, mimeType, callback) { exif -> + when { + dateMillis != null -> { + // set + val date = Date(dateMillis) + val dateString = ExifInterfaceHelper.DATETIME_FORMAT.format(date) + val subSec = dateMillis % 1000 + val subSecString = if (subSec > 0) subSec.toString().padStart(3, '0') else null + + if (fields.contains(ExifInterface.TAG_DATETIME)) { + exif.setAttribute(ExifInterface.TAG_DATETIME, dateString) + exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME, subSecString) + } + if (fields.contains(ExifInterface.TAG_DATETIME_ORIGINAL)) { + exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateString) + exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, subSecString) + } + if (fields.contains(ExifInterface.TAG_DATETIME_DIGITIZED)) { + exif.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, dateString) + exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, subSecString) + } + if (fields.contains(ExifInterface.TAG_GPS_DATESTAMP)) { + exif.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, ExifInterfaceHelper.GPS_DATE_FORMAT.format(date)) + exif.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, ExifInterfaceHelper.GPS_TIME_FORMAT.format(date)) + } + } + + shiftSeconds != null -> { + // shift + val shiftMillis = shiftSeconds * 1000 + listOf( + ExifInterface.TAG_DATETIME, + ExifInterface.TAG_DATETIME_ORIGINAL, + ExifInterface.TAG_DATETIME_DIGITIZED, + ).forEach { field -> + if (fields.contains(field)) { + val subSecTag = when (field) { + ExifInterface.TAG_DATETIME -> ExifInterface.TAG_SUBSEC_TIME + ExifInterface.TAG_DATETIME_DIGITIZED -> ExifInterface.TAG_SUBSEC_TIME_DIGITIZED + ExifInterface.TAG_DATETIME_ORIGINAL -> ExifInterface.TAG_SUBSEC_TIME_ORIGINAL + else -> null + } + exif.getSafeDateMillis(field, subSecTag) { date -> + exif.setAttribute(field, ExifInterfaceHelper.DATETIME_FORMAT.format(date + shiftMillis)) + } + } + } + if (fields.contains(ExifInterface.TAG_GPS_DATESTAMP)) { + exif.gpsDateTime?.let { date -> + val shifted = date + shiftMillis - TimeZone.getDefault().rawOffset + exif.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, ExifInterfaceHelper.GPS_DATE_FORMAT.format(shifted)) + exif.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, ExifInterfaceHelper.GPS_TIME_FORMAT.format(shifted)) + } + } + } + + else -> { + // clear + if (fields.contains(ExifInterface.TAG_DATETIME)) { + exif.setAttribute(ExifInterface.TAG_DATETIME, null) + exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME, null) + exif.setAttribute(ExifInterface.TAG_OFFSET_TIME, null) + } + if (fields.contains(ExifInterface.TAG_DATETIME_ORIGINAL)) { + exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, null) + exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, null) + exif.setAttribute(ExifInterface.TAG_OFFSET_TIME_ORIGINAL, null) + } + if (fields.contains(ExifInterface.TAG_DATETIME_DIGITIZED)) { + exif.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, null) + exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, null) + exif.setAttribute(ExifInterface.TAG_OFFSET_TIME_DIGITIZED, null) + } + if (fields.contains(ExifInterface.TAG_GPS_DATESTAMP)) { + exif.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, null) + exif.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, null) + } + } + } + exif.saveAttributes() + } + + if (success) { + scanPostMetadataEdit(context, path, uri, mimeType, HashMap(), callback) + } + } + + fun editMetadata( + context: Context, + path: String, + uri: Uri, + mimeType: String, + modifier: FieldMap, + autoCorrectTrailerOffset: Boolean, + callback: ImageOpCallback, + ) { + val newFields: FieldMap = hashMapOf() + if (modifier.containsKey(TYPE_EXIF)) { + val fields = modifier[TYPE_EXIF] as Map<*, *>? + if (fields != null && fields.isNotEmpty()) { + if (!editExif( + context = context, + path = path, + uri = uri, + mimeType = mimeType, + callback = callback, + autoCorrectTrailerOffset = autoCorrectTrailerOffset, + ) { exif -> + var setLocation = false + fields.forEach { kv -> + val tag = kv.key as String? + if (tag != null) { + val value = kv.value + if (value == null) { + // remove attribute + exif.setAttribute(tag, null) + } else { + when (tag) { + ExifInterface.TAG_GPS_LATITUDE, + ExifInterface.TAG_GPS_LATITUDE_REF, + ExifInterface.TAG_GPS_LONGITUDE, + ExifInterface.TAG_GPS_LONGITUDE_REF -> { + setLocation = true + } + + else -> { + if (value is String) { + exif.setAttribute(tag, value) + } else { + Log.w(LOG_TAG, "failed to set Exif attribute $tag because value=$value is not a string") + } + } + } + } + } + } + if (setLocation) { + val latAbs = (fields[ExifInterface.TAG_GPS_LATITUDE] as Number?)?.toDouble() + val latRef = fields[ExifInterface.TAG_GPS_LATITUDE_REF] as String? + val lngAbs = (fields[ExifInterface.TAG_GPS_LONGITUDE] as Number?)?.toDouble() + val lngRef = fields[ExifInterface.TAG_GPS_LONGITUDE_REF] as String? + if (latAbs != null && latRef != null && lngAbs != null && lngRef != null) { + val latitude = if (latRef == ExifInterface.LATITUDE_SOUTH) -latAbs else latAbs + val longitude = if (lngRef == ExifInterface.LONGITUDE_WEST) -lngAbs else lngAbs + exif.setLatLong(latitude, longitude) + } else { + Log.w(LOG_TAG, "failed to set Exif location with latAbs=$latAbs, latRef=$latRef, lngAbs=$lngAbs, lngRef=$lngRef") + } + } + exif.saveAttributes() + } + ) return + } + } + + if (modifier.containsKey(TYPE_IPTC)) { + val iptc = (modifier[TYPE_IPTC] as List<*>?)?.filterIsInstance<FieldMap>() + if (!editIptc( + context = context, + path = path, + uri = uri, + mimeType = mimeType, + callback = callback, + autoCorrectTrailerOffset = autoCorrectTrailerOffset, + iptc = iptc, + ) + ) return + } + + if (modifier.containsKey(TYPE_MP4)) { + val fieldsToEdit = modifier[TYPE_MP4] as Map<*, *>? + if (fieldsToEdit != null && fieldsToEdit.isNotEmpty()) { + if (!editMp4Metadata( + context = context, + path = path, + uri = uri, + mimeType = mimeType, + callback = callback, + fieldsToEdit = fieldsToEdit, + newFields = newFields, + ) + ) return + } + } + + if (modifier.containsKey(TYPE_XMP)) { + val xmp = modifier[TYPE_XMP] as Map<*, *>? + if (xmp != null) { + val coreXmp = xmp["xmp"] as String? + val extendedXmp = xmp["extendedXmp"] as String? + if (!editXmp( + context = context, + path = path, + uri = uri, + mimeType = mimeType, + callback = callback, + autoCorrectTrailerOffset = autoCorrectTrailerOffset, + coreXmp = coreXmp, + extendedXmp = extendedXmp, + ) + ) return + } + } + + scanPostMetadataEdit(context, path, uri, mimeType, newFields, callback) + } + + fun removeTrailerVideo( + context: Context, + path: String, + uri: Uri, + mimeType: String, + callback: ImageOpCallback, + ) { + val originalFileSize = File(path).length() + val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize) + if (trailerVideoSize == null) { + callback.onFailure(Exception("failed to get trailer video size")) + return + } + + val isTrailerVideoValid = MultiPage.getTrailerVideoInfo(context, uri, fileSize = originalFileSize, videoSize = trailerVideoSize) != null + if (!isTrailerVideoValid) { + callback.onFailure(Exception("failed to open trailer video with size=$trailerVideoSize")) + return + } + + val editableFile = StorageUtils.createTempFile(context).apply { + try { + val inputStream = StorageUtils.openInputStream(context, uri) + // partial copy + transferFrom(inputStream, originalFileSize - trailerVideoSize) + } catch (e: Exception) { + Log.d(LOG_TAG, "failed to remove trailer video", e) + callback.onFailure(e) + return + } + } + + try { + // copy the edited temporary file back to the original + editableFile.transferTo(outputStream(context, mimeType, uri, path)) + editableFile.delete() + } catch (e: IOException) { + callback.onFailure(e) + return + } + + val newFields: FieldMap = hashMapOf() + scanPostMetadataEdit(context, path, uri, mimeType, newFields, callback) + } + + fun removeMetadataTypes( + context: Context, + path: String, + uri: Uri, + mimeType: String, + types: Set<String>, + callback: ImageOpCallback, + ) { + if (!canRemoveMetadata(mimeType)) { + callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType")) + return + } + + val originalFileSize = File(path).length() + val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize) + val isTrailerVideoValid = trailerVideoSize != null && MultiPage.getTrailerVideoInfo(context, uri, originalFileSize, trailerVideoSize) != null + val editableFile = StorageUtils.createTempFile(context).apply { + try { + outputStream().use { output -> + // reopen input to read from start + StorageUtils.openInputStream(context, uri)?.use { input -> + PixyMetaHelper.removeMetadata(input, output, types) + } + } + } catch (e: Exception) { + Log.d(LOG_TAG, "failed to remove metadata", e) + callback.onFailure(e) + return + } + } + + if (editableFile.length() == 0L) { + callback.onFailure(Exception("removing metadata yielded an empty file")) + return + } + + try { + // copy the edited temporary file back to the original + editableFile.transferTo(outputStream(context, mimeType, uri, path)) + + if (!types.contains(TYPE_XMP) && isTrailerVideoValid && !checkTrailerOffset(context, path, uri, mimeType, trailerVideoSize, editableFile, callback)) { + return + } + editableFile.delete() + } catch (e: IOException) { + callback.onFailure(e) + return + } + + val newFields: FieldMap = hashMapOf() + scanPostMetadataEdit(context, path, uri, mimeType, newFields, callback) + } + + private fun outputStream( + context: Context, + mimeType: String, + uri: Uri, + path: String + ): OutputStream { + // truncate is necessary when overwriting a longer file + val mode = "wt" + return if (isMediaUriPermissionGranted(context, uri, mimeType)) { + StorageUtils.openOutputStream(context, mimeType, uri, mode) ?: throw Exception("failed to open output stream for uri=$uri") + } else { + val documentUri = StorageUtils.getDocumentFile(context, path, uri)?.uri ?: throw Exception("failed to get document file for path=$path, uri=$uri") + context.contentResolver.openOutputStream(documentUri, mode) ?: throw Exception("failed to open output stream from documentUri=$documentUri for path=$path, uri=$uri") + } + } + + interface ImageOpCallback { + fun onSuccess(fields: FieldMap) + fun onFailure(throwable: Throwable) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<ImageProvider>() + + private const val LENGTH_UNIT_PERCENT = "percent" + + val supportedExportMimeTypes = listOf(MimeTypes.BMP, MimeTypes.JPEG, MimeTypes.PNG, MimeTypes.WEBP) + + // used when skipping a move/creation op because the target file already exists + val skippedFieldMap: HashMap<String, Any?> = hashMapOf("skipped" to true) + + // used when deleting instead of moving to bin because the target file no longer exists + val deletedFieldMap: HashMap<String, Any?> = hashMapOf("deleted" to true) + + fun isMediaUriPermissionGranted(context: Context, uri: Uri, mimeType: String): Boolean { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val safeUri = StorageUtils.getMediaStoreScopedStorageSafeUri(uri, mimeType) + + val pid = Binder.getCallingPid() + val uid = Binder.getCallingUid() + val flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION + context.checkUriPermission(safeUri, pid, uid, flags) == PackageManager.PERMISSION_GRANTED + } else { + false + } + } + + fun getTimeZoneString(timeZone: TimeZone, dateTimeMillis: Long): String { + val offset = timeZone.getOffset(dateTimeMillis) + val offsetInMinutes = offset.absoluteValue / 60000 + val offsetSign = if (offset < 0) "-" else "+" + val offsetHours = "${offsetInMinutes / 60}".padStart(2, '0') + val offsetMinutes = "${offsetInMinutes % 60}".padStart(2, '0') + return "$offsetSign$offsetHours:$offsetMinutes" + } + } +} + +typealias CancelCheck = () -> Boolean diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProviderFactory.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProviderFactory.kt new file mode 100644 index 0000000..1807206 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProviderFactory.kt @@ -0,0 +1,26 @@ +package deckers.thibault.aves.model.provider + +import android.content.ContentResolver +import android.content.Context +import android.net.Uri +import deckers.thibault.aves.utils.StorageUtils +import java.util.Locale + +object ImageProviderFactory { + fun getProvider(context: Context, uri: Uri): ImageProvider? { + return when (uri.scheme?.lowercase(Locale.ROOT)) { + ContentResolver.SCHEME_CONTENT -> { + if (StorageUtils.isMediaStoreContentUri(uri)) { + MediaStoreImageProvider() + } else if (AvesEmbeddedMediaProvider.provides(context, uri)) { + AvesEmbeddedMediaProvider() + } else { + UnknownContentProvider() + } + } + + ContentResolver.SCHEME_FILE -> FileImageProvider() + else -> null + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/MediaStoreImageProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/MediaStoreImageProvider.kt new file mode 100644 index 0000000..a9e19a8 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/MediaStoreImageProvider.kt @@ -0,0 +1,1079 @@ +package deckers.thibault.aves.model.provider + +import android.annotation.SuppressLint +import android.app.Activity +import android.app.RecoverableSecurityException +import android.content.ContentResolver +import android.content.ContentUris +import android.content.ContentValues +import android.content.Context +import android.content.ContextWrapper +import android.graphics.BitmapFactory +import android.media.MediaScannerConnection +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import android.util.Log +import androidx.annotation.RequiresApi +import com.commonsware.cwac.document.DocumentFileCompat +import deckers.thibault.aves.MainActivity +import deckers.thibault.aves.MainActivity.Companion.DELETE_SINGLE_PERMISSION_REQUEST +import deckers.thibault.aves.model.AvesEntry +import deckers.thibault.aves.model.EntryFields +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.NameConflictStrategy +import deckers.thibault.aves.model.SourceEntry +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.MimeTypes.extensionFor +import deckers.thibault.aves.utils.MimeTypes.isHeic +import deckers.thibault.aves.utils.MimeTypes.isImage +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.StorageUtils +import deckers.thibault.aves.utils.StorageUtils.PathSegments +import deckers.thibault.aves.utils.StorageUtils.ensureTrailingSeparator +import deckers.thibault.aves.utils.StorageUtils.removeTrailingSeparator +import deckers.thibault.aves.utils.UriUtils.tryParseId +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.OutputStream +import java.io.SyncFailedException +import java.util.Locale +import java.util.concurrent.CompletableFuture +import kotlin.coroutines.Continuation +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlin.coroutines.suspendCoroutine + +class MediaStoreImageProvider : ImageProvider() { + fun fetchAll( + context: Context, + knownEntries: Map<Long?, Long?>, + directory: String?, + handleNewEntry: NewEntryHandler, + ) { + Log.d(LOG_TAG, "fetching all media store items for ${knownEntries.size} known entries, directory=$directory") + val isModified = fun(contentId: Long, dateModifiedMillis: Long): Boolean { + val knownDate = knownEntries[contentId] + return knownDate == null || knownDate < dateModifiedMillis + } + val handleNew: NewEntryHandler + var selection: String? = null + var selectionArgs: Array<String>? = null + if (directory != null) { + val relativePathDirectory = ensureTrailingSeparator(directory) + val relativePath = PathSegments(context, relativePathDirectory).relativeDir + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && relativePath != null) { + selection = "${MediaStore.MediaColumns.RELATIVE_PATH} = ? AND ${MediaStore.MediaColumns.DATA} LIKE ?" + selectionArgs = arrayOf(relativePath, "$relativePathDirectory%") + } else { + selection = "${MediaStore.MediaColumns.DATA} LIKE ?" + selectionArgs = arrayOf("$relativePathDirectory%") + } + + val parentCheckDirectory = removeTrailingSeparator(directory) + handleNew = { entry -> + // skip entries in subfolders + val path = entry[EntryFields.PATH] as String? + if (path != null && File(path).parent == parentCheckDirectory) { + handleNewEntry(entry) + } + } + } else { + handleNew = handleNewEntry + } + fetchFrom(context, isModified, handleNew, IMAGE_CONTENT_URI, IMAGE_PROJECTION, selection, selectionArgs) + fetchFrom(context, isModified, handleNew, VIDEO_CONTENT_URI, VIDEO_PROJECTION, selection, selectionArgs) + } + + // the provided URI can point to the wrong media collection, + // e.g. a GIF image with the URI `content://media/external/video/media/[ID]` + // so the effective entry URI may not match the provided URI + override fun fetchSingle(context: Context, uri: Uri, sourceMimeType: String?, allowUnsized: Boolean, callback: ImageOpCallback) { + var found = false + val fetched = arrayListOf<FieldMap>() + val id = uri.tryParseId() + val alwaysValid: NewEntryChecker = fun(_: Long, _: Long): Boolean = true + val onSuccess: NewEntryHandler = fun(entry: FieldMap) { fetched.add(entry) } + if (id != null) { + if (sourceMimeType == null || isImage(sourceMimeType)) { + val contentUri = ContentUris.withAppendedId(IMAGE_CONTENT_URI, id) + found = fetchFrom(context, alwaysValid, onSuccess, contentUri, IMAGE_PROJECTION) + } + if (!found && (sourceMimeType == null || isVideo(sourceMimeType))) { + val contentUri = ContentUris.withAppendedId(VIDEO_CONTENT_URI, id) + found = fetchFrom(context, alwaysValid, onSuccess, contentUri, VIDEO_PROJECTION) + } + } + if (!found) { + // the uri can be a file media URI (e.g. "content://0@media/external/file/30050") + // without an equivalent image/video if it is shared from a file browser + // but the file is not publicly visible + found = fetchFrom(context, alwaysValid, onSuccess, uri, BASE_PROJECTION, fileMimeType = sourceMimeType) + } + + if (found && fetched.isNotEmpty()) { + if (fetched.size == 1) { + callback.onSuccess(fetched.first()) + } else { + callback.onFailure(Exception("found ${fetched.size} entries at uri=$uri")) + } + } else { + callback.onFailure(Exception("failed to fetch entry at uri=$uri")) + } + } + + fun checkObsoleteContentIds(context: Context, knownContentIds: List<Long?>): List<Long> { + val foundContentIds = HashSet<Long>() + fun check(context: Context, contentUri: Uri) { + val projection = arrayOf(MediaStore.MediaColumns._ID) + try { + val cursor = context.contentResolver.query(contentUri, projection, null, null, null) + if (cursor != null) { + val idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID) + while (cursor.moveToNext()) { + foundContentIds.add(cursor.getLong(idColumn)) + } + cursor.close() + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get content IDs for contentUri=$contentUri", e) + } + } + check(context, IMAGE_CONTENT_URI) + check(context, VIDEO_CONTENT_URI) + return knownContentIds.subtract(foundContentIds).filterNotNull().toList() + } + + fun checkObsoletePaths(context: Context, knownPathById: Map<Long?, String?>): List<Long> { + val obsoleteIds = ArrayList<Long>() + fun check(context: Context, contentUri: Uri) { + val projection = arrayOf(MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DATA) + try { + val cursor = context.contentResolver.query(contentUri, projection, null, null, null) + if (cursor != null) { + val idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID) + val pathColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA) + while (cursor.moveToNext()) { + val id = cursor.getLong(idColumn) + val path = cursor.getString(pathColumn) + if (knownPathById.containsKey(id) && knownPathById[id] != path) { + obsoleteIds.add(id) + } + } + cursor.close() + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get content IDs for contentUri=$contentUri", e) + } + } + check(context, IMAGE_CONTENT_URI) + check(context, VIDEO_CONTENT_URI) + return obsoleteIds + } + + fun getChangedUris(context: Context, sinceGeneration: Int): List<String> { + val changedUris = ArrayList<String>() + fun check(context: Context, contentUri: Uri) { + val projection = arrayOf(MediaStore.MediaColumns._ID) + val selection = "${MediaStore.MediaColumns.GENERATION_MODIFIED} > ?" + val selectionArgs = arrayOf(sinceGeneration.toString()) + try { + val cursor = context.contentResolver.query(contentUri, projection, selection, selectionArgs, null) + if (cursor != null) { + val idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID) + while (cursor.moveToNext()) { + val id = cursor.getLong(idColumn) + changedUris.add(ContentUris.withAppendedId(contentUri, id).toString()) + } + cursor.close() + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get content IDs for contentUri=$contentUri", e) + } + } + check(context, IMAGE_CONTENT_URI) + check(context, VIDEO_CONTENT_URI) + return changedUris + } + + private fun fetchFrom( + context: Context, + isValidEntry: NewEntryChecker, + handleNewEntry: NewEntryHandler, + contentUri: Uri, + projection: Array<String>, + selection: String? = null, + selectionArgs: Array<String>? = null, + fileMimeType: String? = null, + ): Boolean { + var found = false + val orderBy = "${MediaStore.MediaColumns.DATE_MODIFIED} DESC" + try { + val cursor = context.contentResolver.query(contentUri, projection, selection, selectionArgs, orderBy) + if (cursor != null) { + val contentUriContainsId = when (contentUri) { + IMAGE_CONTENT_URI, VIDEO_CONTENT_URI -> false + else -> true + } + + // image & video + val idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID) + val pathColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA) + val mimeTypeColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE) + val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.SIZE) + val widthColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.WIDTH) + val heightColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.HEIGHT) + val dateAddedSecsColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_ADDED) + val dateModifiedSecsColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED) + val dateTakenColumn = cursor.getColumnIndex(MediaColumns.DATE_TAKEN) + + // image & video for API >=29, only for images for API <29 + val orientationColumn = cursor.getColumnIndex(MediaColumns.ORIENTATION) + + // video only + val durationColumn = cursor.getColumnIndex(MediaColumns.DURATION) + val needDuration = projection.contentEquals(VIDEO_PROJECTION) + + while (cursor.moveToNext()) { + val id = cursor.getLong(idColumn) + val dateModifiedMillis = cursor.getInt(dateModifiedSecsColumn) * 1000L + if (isValidEntry(id, dateModifiedMillis)) { + // for multiple items, `contentUri` is the root without ID, + // but for single items, `contentUri` already contains the ID + val itemUri = if (contentUriContainsId) contentUri else ContentUris.withAppendedId(contentUri, id) + // `mimeType` can be registered as null for file media URIs with unsupported media types (e.g. TIFF on old devices) + // in that case we try to use the MIME type provided along the URI + val mimeType: String? = cursor.getString(mimeTypeColumn) ?: fileMimeType + var width = cursor.getInt(widthColumn) + var height = cursor.getInt(heightColumn) + val durationMillis = if (durationColumn != -1) cursor.getLong(durationColumn) else 0L + + if (mimeType == null) { + Log.w(LOG_TAG, "failed to make entry from uri=$itemUri because of null MIME type") + } else { + val path = cursor.getString(pathColumn) + + val isDir = path != null && File(path).isDirectory + if (isDir) { + // some directories are wrongly registered as media (e.g. `.../Android/media/is.xyz.mpv`) + Log.w(LOG_TAG, "failed to make entry from uri=$itemUri because path=$path refers to a directory") + } else { + var entryFields: FieldMap = hashMapOf( + EntryFields.ORIGIN to SourceEntry.ORIGIN_MEDIA_STORE_CONTENT, + EntryFields.URI to itemUri.toString(), + EntryFields.PATH to path, + EntryFields.SOURCE_MIME_TYPE to mimeType, + EntryFields.WIDTH to width, + EntryFields.HEIGHT to height, + EntryFields.SOURCE_ROTATION_DEGREES to if (orientationColumn != -1) cursor.getInt(orientationColumn) else 0, + EntryFields.SIZE_BYTES to cursor.getLong(sizeColumn), + EntryFields.DATE_ADDED_SECS to cursor.getInt(dateAddedSecsColumn), + EntryFields.DATE_MODIFIED_MILLIS to dateModifiedMillis, + EntryFields.SOURCE_DATE_TAKEN_MILLIS to if (dateTakenColumn != -1) cursor.getLong(dateTakenColumn) else null, + EntryFields.DURATION_MILLIS to durationMillis, + // only for map export + EntryFields.CONTENT_ID to id, + ) + + if (isHeic(mimeType)) { + // The reported size for some HEIC images is simply incorrect. + try { + StorageUtils.openInputStream(context, itemUri)?.use { input -> + val options = BitmapFactory.Options().apply { + inJustDecodeBounds = true + } + BitmapFactory.decodeStream(input, null, options) + val outWidth = options.outWidth + val outHeight = options.outHeight + if (outWidth > 0 && outHeight > 0) { + width = outWidth + height = outHeight + entryFields[EntryFields.WIDTH] = width + entryFields[EntryFields.HEIGHT] = height + } + } + } catch (_: IOException) { + // ignore + } + } + + if (MimeTypes.isRaw(mimeType) + || (width <= 0 || height <= 0) && needSize(mimeType) + || durationMillis == 0L && needDuration + ) { + // Some images are incorrectly registered in the Media Store, + // missing some attributes such as width, height, orientation. + // Also, the reported size of raw images is inconsistent across devices + // and Android versions (sometimes the raw size, sometimes the decoded size). + val entry = SourceEntry(entryFields).fillPreCatalogMetadata(context) + entryFields = entry.toMap() + } + + getFileModifiedDateMillis(path)?.let { entryFields[EntryFields.DATE_MODIFIED_MILLIS] = it } + + handleNewEntry(entryFields) + found = true + } + } + } + } + cursor.close() + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get entries", e) + } + return found + } + + private fun hasEntry(context: Context, contentUri: Uri): Boolean { + var found = false + val projection = arrayOf(MediaStore.MediaColumns._ID) + try { + val cursor = context.contentResolver.query(contentUri, projection, null, null, null) + if (cursor != null) { + while (cursor.moveToNext()) { + found = true + } + cursor.close() + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get entry at contentUri=$contentUri", e) + } + return found + } + + private fun needSize(mimeType: String) = MimeTypes.SVG != mimeType + + // `uri` is a media URI, not a document URI + override fun delete(contextWrapper: ContextWrapper, uri: Uri, path: String?, mimeType: String) { + path ?: throw Exception("failed to delete file because path is null") + + // the following situations are possible: + // - there is an entry in the Media Store and there is a file on storage + // - there is an entry in the Media Store but there is no longer a file on storage + // - there is no entry in the Media Store but there is a file on storage + val file = File(path) + val fileExists = file.exists() + + if (fileExists) { + if (StorageUtils.canEditByFile(contextWrapper, path)) { + if (hasEntry(contextWrapper, uri)) { + Log.d(LOG_TAG, "delete [permission:file, file exists, content exists] content at uri=$uri path=$path") + contextWrapper.contentResolver.delete(uri, null, null) + } + // in theory, deleting via content resolver should remove the file on storage + // in practice, the file may still be there afterwards + if (file.exists()) { + Log.d(LOG_TAG, "delete [permission:file, file exists after content delete] file at uri=$uri path=$path") + if (file.delete()) { + // in theory, scanning an obsolete path should remove the entry from the Media Store + // in practice, the entry may still be there afterwards + scanObsoletePath(contextWrapper, uri, path, mimeType) + return + } + } else { + return + } + } else if (!isMediaUriPermissionGranted(contextWrapper, uri, mimeType) + && StorageUtils.requireAccessPermission(contextWrapper, path) + ) { + // the delete request may yield a `RecoverableSecurityException` when using scoped storage, + // even if we have permissions on the tree document via SAF + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q && hasEntry(contextWrapper, uri)) { + Log.d(LOG_TAG, "delete [permission:doc, file exists, content exists] content at uri=$uri path=$path") + contextWrapper.contentResolver.delete(uri, null, null) + } + + // in theory, deleting via content resolver should remove the file on storage + // in practice, the file may still be there afterwards + if (file.exists()) { + Log.d(LOG_TAG, "delete [permission:doc, file exists after content delete] document at uri=$uri path=$path") + val df = StorageUtils.getDocumentFile(contextWrapper, path, uri) + + if (df != null && df.delete()) { + scanObsoletePath(contextWrapper, uri, path, mimeType) + return + } + throw Exception("failed to delete document with df=$df") + } else { + return + } + } + } else if (uri.scheme?.lowercase(Locale.ROOT) == ContentResolver.SCHEME_FILE) { + val uriFilePath = File(uri.path!!).path + // URI and path both point to the same non existent path + if (uriFilePath == path) return + } + + try { + Log.d(LOG_TAG, "delete [file exists=$fileExists] content at uri=$uri path=$path") + if (contextWrapper.contentResolver.delete(uri, null, null) > 0) return + + if (hasEntry(contextWrapper, uri) || file.exists()) { + throw Exception("failed to delete row from content provider") + } + } catch (securityException: SecurityException) { + // even if the app has access permission granted on the containing directory, + // the delete request may yield a `RecoverableSecurityException` on API >=29 + // when the underlying file no longer exists and this is an orphaned entry in the Media Store + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && contextWrapper is Activity) { + Log.w(LOG_TAG, "caught a security exception when attempting to delete uri=$uri", securityException) + val rse = securityException as? RecoverableSecurityException ?: throw securityException + val intentSender = rse.userAction.actionIntent.intentSender + + // request user permission for this item + MainActivity.pendingScopedStoragePermissionCompleter = CompletableFuture<Boolean>() + contextWrapper.startIntentSenderForResult(intentSender, DELETE_SINGLE_PERMISSION_REQUEST, null, 0, 0, 0, null) + val granted = MainActivity.pendingScopedStoragePermissionCompleter!!.join() + + MainActivity.pendingScopedStoragePermissionCompleter = null + if (granted) { + delete(contextWrapper, uri, path, mimeType) + } else { + throw Exception("failed to get delete permission") + } + } else { + throw securityException + } + } + } + + override suspend fun moveMultiple( + activity: Activity, + copy: Boolean, + nameConflictStrategy: NameConflictStrategy, + entriesByTargetDir: Map<String, List<AvesEntry>>, + isCancelledOp: CancelCheck, + callback: ImageOpCallback, + ) { + entriesByTargetDir.forEach { kv -> + val targetDir = kv.key + val entries = kv.value + + val toBin = targetDir == StorageUtils.TRASH_PATH_PLACEHOLDER + val toVault = StorageUtils.isInVault(activity, targetDir) + val toAppDir = toBin || toVault + + var effectiveTargetDir: String? = null + var targetDirDocFile: DocumentFileCompat? = null + if (!toAppDir) { + effectiveTargetDir = targetDir + targetDirDocFile = StorageUtils.createDirectoryDocIfAbsent(activity, targetDir) + if (!File(targetDir).exists()) { + // download subdirectories can be created later by Media Store insertion + if (!isDownloadSubdir(activity, targetDir)) { + callback.onFailure(Exception("failed to create directory at path=$targetDir")) + return + } + } + } + + for (entry in entries) { + val mimeType = entry.mimeType + val trashed = entry.trashed + + val sourceUri = entry.uri + val sourcePath = if (trashed) entry.trashPath else entry.path + + var desiredName: String? = null + if (trashed) { + entry.path?.let { desiredName = File(it).name } + } + + val result: FieldMap = hashMapOf( + "uri" to sourceUri.toString(), + "success" to false, + ) + + // on API 30 we cannot get access granted directly to a volume root from its document tree, + // but it is still less constraining to use tree document files than to rely on the Media Store + // + // Relying on `DocumentFile`, we can create an item via `DocumentFile.createFile()`, but: + // - we need to scan the file to get the Media Store content URI + // - the underlying document provider controls the new file name + // + // Relying on the Media Store, we can create an item via `ContentResolver.insert()` + // with a path, and retrieve its content URI, but: + // - the Media Store isolates content by storage volume (e.g. `MediaStore.Images.Media.getContentUri(volumeName)`) + // - the volume name should be lower case, not exactly as the `StorageVolume` UUID + // cf new method in API 30 `StorageVolume.getMediaStoreVolumeName()` + // - inserting on a removable volume works on API 29, but not on API 25 nor 26 (on which API/devices does it work?) + // - there is no documentation regarding support for usage with removable storage + // - the Media Store only allows inserting in specific primary directories ("DCIM", "Pictures") when using scoped storage + try { + val appDir = when { + toBin -> StorageUtils.trashDirFor(activity, sourcePath ?: StorageUtils.getPrimaryVolumePath(activity)) + toVault -> File(targetDir) + else -> null + } + if (appDir != null) { + effectiveTargetDir = ensureTrailingSeparator(appDir.path) + targetDirDocFile = DocumentFileCompat.fromFile(appDir) + + if (toVault) { + appDir.mkdirs() + } + } + + if (effectiveTargetDir != null) { + val newFields = if (isCancelledOp()) skippedFieldMap else { + val sourceFile = if (sourcePath != null) File(sourcePath) else null + if (sourceFile != null && !sourceFile.exists() && toBin) { + delete(activity, sourceUri, sourcePath, mimeType = mimeType) + deletedFieldMap + } else { + moveSingle( + activity = activity, + sourceFile = sourceFile, + sourceUri = sourceUri, + targetDir = effectiveTargetDir, + targetDirDocFile = targetDirDocFile, + desiredName = desiredName ?: sourceFile?.name ?: sourceUri.lastPathSegment ?: createTimeStampFileName(), + nameConflictStrategy = nameConflictStrategy, + mimeType = mimeType, + copy = copy, + toBin = toBin, + ) + } + } + result["newFields"] = newFields + result["success"] = true + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to move to targetDir=$targetDir entry with sourcePath=$sourcePath", e) + } + callback.onSuccess(result) + } + } + } + + private suspend fun moveSingle( + activity: Activity, + sourceFile: File?, + sourceUri: Uri, + targetDir: String, + targetDirDocFile: DocumentFileCompat?, + desiredName: String, + nameConflictStrategy: NameConflictStrategy, + mimeType: String, + copy: Boolean, + toBin: Boolean, + ): FieldMap { + val sourcePath = sourceFile?.path + val sourceExtension = sourceFile?.extension + val sourceDir = sourceFile?.parent?.let { ensureTrailingSeparator(it) } + if (sourceDir == targetDir && !(copy && nameConflictStrategy == NameConflictStrategy.RENAME)) { + // nothing to do unless it's a renamed copy + return skippedFieldMap + } + + val desiredNameWithoutExtension = desiredName.substringBeforeLast(".") + val resolution = resolveTargetFileNameWithoutExtension( + contextWrapper = activity, + dir = targetDir, + desiredNameWithoutExtension = desiredNameWithoutExtension, + mimeType = mimeType, + defaultExtension = sourceExtension, + conflictStrategy = nameConflictStrategy, + ) + val targetNameWithoutExtension = resolution.nameWithoutExtension ?: return skippedFieldMap + + val sourceDocFile = DocumentFileCompat.fromSingleUri(activity, sourceUri) + val targetPath = createSingle( + activity = activity, + mimeType = mimeType, + targetDir = targetDir, + targetDirDocFile = targetDirDocFile, + targetNameWithoutExtension = targetNameWithoutExtension, + defaultExtension = sourceExtension, + ) { output: OutputStream -> + try { + sourceDocFile.copyTo(output) + } catch (e: SyncFailedException) { + // The copied file is synced after writing, but it consistently fails in some cases + // (e.g. copying to SD card on Xiaomi 2201117PG with Android 11). + // It seems this failure can be safely ignored, as the new file is complete. + Log.w(LOG_TAG, "sync failure after copying from uri=$sourceUri, path=$sourcePath to targetDir=$targetDir", e) + } + } + + if (!copy) { + // delete original entry + try { + delete(activity, sourceUri, sourcePath, mimeType) + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to delete entry with path=$sourcePath", e) + } + } + return if (toBin) { + hashMapOf( + EntryFields.TRASHED to true, + EntryFields.TRASH_PATH to targetPath, + ) + } else { + scanNewPath(activity, targetPath, mimeType) + } + } + + fun createSingle( + activity: Activity, + mimeType: String, + targetDir: String, + targetDirDocFile: DocumentFileCompat?, + targetNameWithoutExtension: String, + defaultExtension: String?, + write: (OutputStream) -> Unit, + ): String { + if (StorageUtils.isInVault(activity, targetDir)) { + return insertByFile( + targetDir = targetDir, + targetFileName = "$targetNameWithoutExtension${extensionFor(mimeType, defaultExtension)}", + write = write, + ) + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + if (isDownloadSubdir(activity, targetDir)) { + return insertByMediaStore( + activity = activity, + targetDir = targetDir, + targetFileName = "$targetNameWithoutExtension${extensionFor(mimeType, defaultExtension)}", + write = write, + ) + } + } + + return insertByTreeDoc( + activity = activity, + mimeType = mimeType, + targetDir = targetDir, + targetDirDocFile = targetDirDocFile, + targetNameWithoutExtension = targetNameWithoutExtension, + defaultExtension = defaultExtension, + write = write, + ) + } + + private fun isDownloadSubdir(context: Context, dir: String): Boolean { + val volumePath = StorageUtils.getVolumePath(context, dir) ?: return false + val downloadDirPath = ensureTrailingSeparator(File(volumePath, Environment.DIRECTORY_DOWNLOADS).path) + // effective download path may have a different case + return dir.lowercase().startsWith(downloadDirPath.lowercase()) + } + + private fun insertByFile( + targetDir: String, + targetFileName: String, + write: (OutputStream) -> Unit, + ): String { + val file = File(targetDir, targetFileName) + FileOutputStream(file).use(write) + return file.path + } + + @RequiresApi(Build.VERSION_CODES.Q) + private fun insertByMediaStore( + activity: Activity, + targetDir: String, + targetFileName: String, + write: (OutputStream) -> Unit, + ): String { + val volumePath = StorageUtils.getVolumePath(activity, targetDir) + val relativePath = targetDir.substring(volumePath?.length ?: 0) + + val values = ContentValues().apply { + put(MediaStore.MediaColumns.DISPLAY_NAME, targetFileName) + put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath) + put(MediaStore.MediaColumns.IS_PENDING, 1) + } + val resolver = activity.contentResolver + val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) + + uri?.let { + resolver.openOutputStream(uri)?.use(write) + values.clear() + values.put(MediaStore.MediaColumns.IS_PENDING, 0) + resolver.update(uri, values, null, null) + } ?: throw Exception("MediaStore failed for some reason") + + return File(targetDir, targetFileName).path + } + + // `DocumentsContract.moveDocument()` needs `sourceParentDocumentUri`, which could be different for each entry + // `DocumentsContract.copyDocument()` yields "Unsupported call: android:copyDocument" + // when used with entry URI as `sourceDocumentUri`, and targetDirDocFile URI as `targetParentDocumentUri` + private fun insertByTreeDoc( + activity: Activity, + mimeType: String, + targetDir: String, + targetDirDocFile: DocumentFileCompat?, + targetNameWithoutExtension: String, + defaultExtension: String?, + write: (OutputStream) -> Unit, + ): String { + targetDirDocFile ?: throw Exception("failed to get tree doc for directory at path=$targetDir") + + // the file created from a `TreeDocumentFile` is also a `TreeDocumentFile` + // but in order to open an output stream to it, we need to use a `SingleDocumentFile` + // through a document URI, not a tree URI + // note that `DocumentFile.getParentFile()` returns null if we did not pick a tree first + var targetTreeFile = targetDirDocFile.createFile(mimeType, targetNameWithoutExtension) + var targetDocFile = DocumentFileCompat.fromSingleUri(activity, targetTreeFile.uri) + + // providing a display name and a MIME type does not guarantee + // that the created document will be backed by a file with a valid media extension, + // but having an extension is essential for media detection by Android, + // so we retry with a display name that includes the extension + if ((targetDocFile.extension == null || targetDocFile.extension.isEmpty() || targetDocFile.extension == "bin") && defaultExtension != null) { + if (targetDocFile.exists()) { + targetDocFile.delete() + } + + val extension = if (defaultExtension.startsWith(".")) defaultExtension else ".$defaultExtension" + targetTreeFile = targetDirDocFile.createFile(mimeType, "$targetNameWithoutExtension$extension") + targetDocFile = DocumentFileCompat.fromSingleUri(activity, targetTreeFile.uri) + } + + try { + targetDocFile.openOutputStream().use(write) + } catch (e: Exception) { + // remove empty file + if (targetDocFile.exists()) { + targetDocFile.delete() + } + throw e + } + + // the source file name and the created document file name can be different when: + // - a file with the same name already exists, some implementations give a suffix like ` (1)`, some *do not* + // - the original extension does not match the extension added by the underlying provider + val fileName = targetDocFile.name + return targetDir + fileName + } + + override suspend fun renameSingle( + activity: Activity, + mimeType: String, + oldMediaUri: Uri, + oldPath: String, + newFile: File, + ): FieldMap = when { + StorageUtils.canEditByFile(activity, oldPath) -> renameSingleByFile(activity, mimeType, oldMediaUri, oldPath, newFile) + isMediaUriPermissionGranted(activity, oldMediaUri, mimeType) -> renameSingleByMediaStore(activity, mimeType, oldMediaUri, newFile) + else -> renameSingleByTreeDoc(activity, mimeType, oldMediaUri, oldPath, newFile) + } + + private suspend fun renameSingleByMediaStore( + activity: Activity, + mimeType: String, + mediaUri: Uri, + newFile: File + ): FieldMap { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + throw Exception("unsupported Android version") + } + + Log.d(LOG_TAG, "rename content at uri=$mediaUri") + val uri = StorageUtils.getMediaStoreScopedStorageSafeUri(mediaUri, mimeType) + + // `IS_PENDING` is necessary for `TITLE`, not for `DISPLAY_NAME` + val tempValues = ContentValues().apply { + put(MediaStore.MediaColumns.IS_PENDING, 1) + } + if (activity.contentResolver.update(uri, tempValues, null, null) == 0) { + throw Exception("failed to update fields for uri=$uri") + } + + val finalValues = ContentValues().apply { + put(MediaStore.MediaColumns.DISPLAY_NAME, newFile.name) + // scanning the new file will not automatically update `TITLE` + put(MediaStore.MediaColumns.TITLE, newFile.nameWithoutExtension) + put(MediaStore.MediaColumns.IS_PENDING, 0) + } + if (activity.contentResolver.update(uri, finalValues, null, null) == 0) { + throw Exception("failed to update fields for uri=$uri") + } + + // URI should not change + return scanNewPathByMediaStore(activity, newFile.path, mimeType) + } + + private suspend fun renameSingleByTreeDoc( + activity: Activity, + mimeType: String, + oldMediaUri: Uri, + oldPath: String, + newFile: File + ): FieldMap { + Log.d(LOG_TAG, "rename document at uri=$oldMediaUri path=$oldPath") + val df = StorageUtils.getDocumentFile(activity, oldPath, oldMediaUri) + df ?: throw Exception("failed to get document at path=$oldPath") + + val requestedName = newFile.name + val renamed = df.renameTo(newFile.name) + if (!renamed) { + throw Exception("failed to rename document at path=$oldPath") + } + val effectiveName = df.name + if (requestedName != effectiveName) { + Log.w(LOG_TAG, "requested renaming document at uri=$oldMediaUri path=$oldPath with name=${requestedName} but got name=$effectiveName") + } + val newPath = File(newFile.parentFile, df.name).path + + scanObsoletePath(activity, oldMediaUri, oldPath, mimeType) + return scanNewPathByMediaStore(activity, newPath, mimeType) + } + + private suspend fun renameSingleByFile( + activity: Activity, + mimeType: String, + oldMediaUri: Uri, + oldPath: String, + newFile: File + ): FieldMap { + Log.d(LOG_TAG, "rename file at path=$oldPath") + val renamed = File(oldPath).renameTo(newFile) + if (!renamed) { + throw Exception("failed to rename file at path=$oldPath") + } + scanObsoletePath(activity, oldMediaUri, oldPath, mimeType) + return scanNewPathByMediaStore(activity, newFile.path, mimeType) + } + + override fun scanPostMetadataEdit(context: Context, path: String, uri: Uri, mimeType: String, newFields: FieldMap, callback: ImageOpCallback) { + MediaScannerConnection.scanFile(context, arrayOf(path), arrayOf(mimeType)) { _, _ -> + val projection = arrayOf( + MediaStore.MediaColumns.DATE_MODIFIED, + MediaStore.MediaColumns.SIZE, + ) + try { + val cursor = context.contentResolver.query(uri, projection, null, null, null) + if (cursor != null && cursor.moveToFirst()) { + cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED).let { if (it != -1) newFields[EntryFields.DATE_MODIFIED_MILLIS] = cursor.getInt(it) * 1000 } + cursor.getColumnIndex(MediaStore.MediaColumns.SIZE).let { if (it != -1) newFields[EntryFields.SIZE_BYTES] = cursor.getLong(it) } + cursor.close() + } + } catch (e: Exception) { + callback.onFailure(e) + return@scanFile + } + getFileModifiedDateMillis(path)?.let { newFields[EntryFields.DATE_MODIFIED_MILLIS] = it } + callback.onSuccess(newFields) + } + } + + // try to fetch the modified date from the file, + // as it is more precise than the one from the Media Store + private fun getFileModifiedDateMillis(path: String?): Long? { + if (path != null) { + try { + return File(path).lastModified() + } catch (_: SecurityException) { + // ignore + } + } + return null + } + + private fun scanObsoletePath(context: Context, uri: Uri, path: String, mimeType: String) { + val file = File(path) + val delayMillis = 500L + val maxDelayMillis = 10000L + var totalDelayMillis = 0L + while (file.exists()) { + if (!hasEntry(context, uri)) return + if (totalDelayMillis < maxDelayMillis) { + Log.d(LOG_TAG, "Trying to scan obsolete path but file exists at path=$path. Will retry in $delayMillis ms (total: $totalDelayMillis ms)") + runBlocking { delay(delayMillis) } + totalDelayMillis += delayMillis + } else { + throw Exception("Timeout ($maxDelayMillis ms) to clear MediaStore entry for file at path=$path") + } + } + + if (hasEntry(context, uri)) { + MediaScannerConnection.scanFile(context, arrayOf(path), arrayOf(mimeType)) { _, newUri: Uri? -> + if (newUri != null && hasEntry(context, newUri)) { + Log.w(LOG_TAG, "Failed to clear Media Store entry at uri=$newUri path=$path") + } else { + Log.w(LOG_TAG, "Cleared Media Store entry at uri=$newUri path=$path") + } + } + } + } + + suspend fun scanNewPathByMediaStore(context: Context, path: String, mimeType: String): FieldMap = + suspendCoroutine { cont -> + tryScanNewPathByMediaStore( + context = context, + path = path, + mimeType = mimeType, + cont = cont, + ) + } + + private fun tryScanNewPathByMediaStore( + context: Context, + path: String, + mimeType: String, + cont: Continuation<FieldMap>, + iteration: Int = 0, + ) { + // `scanFile` may (e.g. when copying to SD card on Android 10 (API 29)): + // 1) yield no URI, + // 2) yield a temporary URI that fails when queried, + // 3) yield a temporary URI that succeeds when queried right away, but the Media Store actually won't have an entry for it until device reboot. + if (iteration > 5) { + // give up + cont.resumeWithException(Exception("failed to scan new path=$path after $iteration iterations")) + return + } else if (iteration > 0) { + // waiting and retrying just once usually works out for cases 1) and 2) + Thread.sleep(iteration * 100L) + } else if (iteration == 0 && Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + // waiting before the first scan usually works out for case 3) + StorageUtils.getVolumePath(context, path)?.let { volumePath -> + if (volumePath != StorageUtils.getPrimaryVolumePath(context)) { + Thread.sleep(100L) + } + } + } + + MediaScannerConnection.scanFile(context, arrayOf(path), arrayOf(mimeType)) { _, newUri: Uri? -> + fun scanUri(uri: Uri?): FieldMap? { + uri ?: return null + + // we retrieve updated fields as the renamed/moved file became a new entry in the Media Store + val projection = arrayOf( + MediaStore.MediaColumns.DATE_ADDED, + MediaStore.MediaColumns.DATE_MODIFIED, + ) + try { + val cursor = context.contentResolver.query(uri, projection, null, null, null) + if (cursor != null && cursor.moveToFirst()) { + val newFields = hashMapOf<String, Any?>( + EntryFields.ORIGIN to SourceEntry.ORIGIN_MEDIA_STORE_CONTENT, + EntryFields.URI to uri.toString(), + EntryFields.CONTENT_ID to uri.tryParseId(), + EntryFields.PATH to path, + ) + cursor.getColumnIndex(MediaStore.MediaColumns.DATE_ADDED).let { if (it != -1) newFields[EntryFields.DATE_ADDED_SECS] = cursor.getInt(it) } + cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED).let { if (it != -1) newFields[EntryFields.DATE_MODIFIED_MILLIS] = cursor.getInt(it) * 1000 } + cursor.close() + getFileModifiedDateMillis(path)?.let { newFields[EntryFields.DATE_MODIFIED_MILLIS] = it } + return newFields + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to scan uri=$uri", e) + } + return null + } + + if (newUri != null) { + var contentUri: Uri? = null + // `newURI` is possibly a file media URI (e.g. "content://media/12a9-8b42/file/62872") + // but we need an image/video media URI (e.g. "content://media/external/images/media/62872") + val contentId = newUri.tryParseId() + if (contentId != null) { + if (isImage(mimeType)) { + contentUri = ContentUris.withAppendedId(IMAGE_CONTENT_URI, contentId) + } else if (isVideo(mimeType)) { + contentUri = ContentUris.withAppendedId(VIDEO_CONTENT_URI, contentId) + } + } + + // prefer image/video content URI, fallback to original URI (possibly a file content URI) + val newFields = scanUri(contentUri) ?: scanUri(newUri) + + if (newFields != null) { + cont.resume(newFields) + return@scanFile + } + } + + tryScanNewPathByMediaStore(context, path = path, mimeType = mimeType, cont, iteration + 1) + } + } + + fun getContentUriForPath(context: Context, path: String): Uri? { + val projection = arrayOf(MediaStore.MediaColumns._ID) + val selection = "${MediaStore.MediaColumns.DATA} = ?" + val selectionArgs = arrayOf(path) + + fun check(context: Context, contentUri: Uri): Uri? { + var mediaContentUri: Uri? = null + try { + val cursor = context.contentResolver.query(contentUri, projection, selection, selectionArgs, null) + if (cursor != null && cursor.moveToFirst()) { + val idColumn = cursor.getColumnIndex(MediaStore.MediaColumns._ID) + if (idColumn != -1) { + val id = cursor.getLong(idColumn) + mediaContentUri = ContentUris.withAppendedId(contentUri, id) + } + cursor.close() + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get URI for contentUri=$contentUri path=$path", e) + } + return mediaContentUri + } + return check(context, IMAGE_CONTENT_URI) ?: check(context, VIDEO_CONTENT_URI) + } + + companion object { + private val LOG_TAG = LogUtils.createTag<MediaStoreImageProvider>() + + private val IMAGE_CONTENT_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI + private val VIDEO_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI + + private val BASE_PROJECTION = arrayOf( + MediaStore.MediaColumns._ID, + MediaStore.MediaColumns.DATA, + MediaStore.MediaColumns.MIME_TYPE, + MediaStore.MediaColumns.SIZE, + MediaStore.MediaColumns.WIDTH, + MediaStore.MediaColumns.HEIGHT, + MediaStore.MediaColumns.DATE_ADDED, + MediaStore.MediaColumns.DATE_MODIFIED, + MediaColumns.DATE_TAKEN, + ) + + private val IMAGE_PROJECTION = arrayOf( + *BASE_PROJECTION, + MediaColumns.ORIENTATION, + ) + + private val VIDEO_PROJECTION = arrayOf( + *BASE_PROJECTION, + MediaColumns.DURATION, + // `ORIENTATION` was only available for images before Android 10 (API 29) + *if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) arrayOf( + MediaStore.MediaColumns.ORIENTATION, + ) else emptyArray() + ) + } +} + +object MediaColumns { + // `DATE_TAKEN`, `ORIENTATION`, `DURATION` used to be in `MediaStore.[Images,Video].Media` + // but were moved to `MediaStore.MediaColumns` for API 29 + // it is safe to use them because they are static strings that have not changed + + @SuppressLint("InlinedApi") + const val DATE_TAKEN = MediaStore.MediaColumns.DATE_TAKEN + + @SuppressLint("InlinedApi") + const val ORIENTATION = MediaStore.MediaColumns.ORIENTATION + + @SuppressLint("InlinedApi") + const val DURATION = MediaStore.MediaColumns.DURATION +} + +typealias NewEntryHandler = (entry: FieldMap) -> Unit + +private typealias NewEntryChecker = (contentId: Long, dateModifiedMillis: Long) -> Boolean
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/UnknownContentProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/UnknownContentProvider.kt new file mode 100644 index 0000000..db2b583 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/UnknownContentProvider.kt @@ -0,0 +1,85 @@ +package deckers.thibault.aves.model.provider + +import android.content.Context +import android.net.Uri +import android.provider.MediaStore +import android.provider.OpenableColumns +import android.util.Log +import deckers.thibault.aves.metadata.Metadata +import deckers.thibault.aves.metadata.metadataextractor.Helper +import deckers.thibault.aves.model.EntryFields +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.model.SourceEntry +import deckers.thibault.aves.utils.LogUtils +import deckers.thibault.aves.utils.MimeTypes +import deckers.thibault.aves.utils.StorageUtils + +open class UnknownContentProvider : ImageProvider() { + open val reliableProviderMimeType: Boolean + get() = false + + override fun fetchSingle(context: Context, uri: Uri, sourceMimeType: String?, allowUnsized: Boolean, callback: ImageOpCallback) { + var mimeType = sourceMimeType + if (sourceMimeType == null || !reliableProviderMimeType) { + // source MIME type may be incorrect, so we get a second opinion if possible + try { + val safeUri = Uri.fromFile(Metadata.createPreviewFile(context, uri)) + StorageUtils.openInputStream(context, safeUri)?.use { input -> + // `metadata-extractor` is the most reliable, except for `tiff` (false positives, false negatives) + // cf https://github.com/drewnoakes/metadata-extractor/issues/296 + Helper.readMimeType(input)?.takeIf { it != MimeTypes.TIFF }?.let { + if (it != sourceMimeType) { + Log.d(LOG_TAG, "source MIME type is $sourceMimeType but extracted MIME type is $it for uri=$uri") + mimeType = it + } + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get MIME type by metadata-extractor for uri=$uri", e) + } catch (e: NoClassDefFoundError) { + Log.w(LOG_TAG, "failed to get MIME type by metadata-extractor for uri=$uri", e) + } catch (e: AssertionError) { + Log.w(LOG_TAG, "failed to get MIME type by metadata-extractor for uri=$uri", e) + } + } + + val fields: FieldMap = hashMapOf( + EntryFields.ORIGIN to SourceEntry.ORIGIN_UNKNOWN_CONTENT, + EntryFields.URI to uri.toString(), + EntryFields.SOURCE_MIME_TYPE to mimeType, + ) + try { + // some providers do not provide the mandatory `OpenableColumns` + // and the query fails when compiling a projection specifying them + // e.g. `content://mms/part/[id]` on Android KitKat + val cursor = context.contentResolver.query(uri, null, null, null, null) + if (cursor != null && cursor.moveToFirst()) { + cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME).let { if (it != -1) fields[EntryFields.TITLE] = cursor.getString(it) } + cursor.getColumnIndex(OpenableColumns.SIZE).let { if (it != -1) fields[EntryFields.SIZE_BYTES] = cursor.getLong(it) } + cursor.getColumnIndex(MediaStore.MediaColumns.DATA).let { if (it != -1) fields[EntryFields.PATH] = cursor.getString(it) } + // mime type fallback if it was not provided and not found via `metadata-extractor` + cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE).let { if (it != -1 && mimeType == null) fields[EntryFields.SOURCE_MIME_TYPE] = cursor.getString(it) } + cursor.close() + } + } catch (e: Exception) { + callback.onFailure(Exception("Failed to query content, error=${e.message}")) + return + } + + if (fields[EntryFields.SOURCE_MIME_TYPE] == null) { + callback.onFailure(Exception("Failed to find MIME type for uri=$uri")) + return + } + + val entry = SourceEntry(fields).fillPreCatalogMetadata(context) + if (allowUnsized || entry.isSized || entry.isSvg || entry.isVideo) { + callback.onSuccess(entry.toMap()) + } else { + callback.onFailure(Exception("entry has no size")) + } + } + + companion object { + private val LOG_TAG = LogUtils.createTag<UnknownContentProvider>() + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/BitmapUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/BitmapUtils.kt new file mode 100644 index 0000000..0029b65 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/BitmapUtils.kt @@ -0,0 +1,301 @@ +package deckers.thibault.aves.utils + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.ColorSpace +import android.os.Build +import android.util.Half +import android.util.Log +import androidx.annotation.RequiresApi +import com.bumptech.glide.Glide +import com.bumptech.glide.load.resource.bitmap.TransformationUtils +import deckers.thibault.aves.metadata.Metadata.getExifCode +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer + +object BitmapUtils { + private val LOG_TAG = LogUtils.createTag<BitmapUtils>() + private const val INITIAL_BUFFER_SIZE = 1 shl 18 // 256kB + + private val freeBaos = ArrayList<ByteArrayOutputStream>() + private val mutex = Mutex() + + private const val INT_BYTE_SIZE = 4 + private const val MAX_2_BITS_FLOAT = 0x3.toFloat() + private const val MAX_8_BITS_FLOAT = 0xff.toFloat() + private const val MAX_10_BITS_FLOAT = 0x3ff.toFloat() + + private const val FORMAT_BYTE_ENCODED: Int = 0xCA + val FORMAT_BYTE_ENCODED_AS_BYTES: ByteArray = ByteArray(1) { _ -> FORMAT_BYTE_ENCODED.toByte() } + private const val FORMAT_BYTE_DECODED: Byte = 0xFE.toByte() + private const val RAW_BYTES_TRAILER_LENGTH = INT_BYTE_SIZE * 2 + 1 + + // bytes per pixel with different bitmap config + private const val BPP_ALPHA_8 = 1 + private const val BPP_RGB_565 = 2 + private const val BPP_ARGB_8888 = 4 + private const val BPP_RGBA_1010102 = 4 + private const val BPP_RGBA_F16 = 8 + + fun Bitmap.describe(): String { + return "{${ + arrayListOf( + "${width}x${height}", + "bytes=$byteCount", + "config=$config", + ).apply { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) add("cs=${colorSpace}") + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) add("hasGainmap=${hasGainmap()}") + }.joinToString(",") + }}" + } + + private fun getBytePerPixel(config: Bitmap.Config?): Int { + return when (config) { + Bitmap.Config.ALPHA_8 -> BPP_ALPHA_8 + Bitmap.Config.RGB_565 -> BPP_RGB_565 + Bitmap.Config.ARGB_8888 -> BPP_ARGB_8888 + else -> { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && config == Bitmap.Config.RGBA_F16) { + BPP_RGBA_F16 + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && config == Bitmap.Config.RGBA_1010102) { + BPP_RGBA_1010102 + } else { + // default + BPP_ARGB_8888 + } + } + } + } + + fun getExpectedImageSize(pixelCount: Long, config: Bitmap.Config?): Long { + return pixelCount * getBytePerPixel(config) + } + + suspend fun getBytes(bitmap: Bitmap?, recycle: Boolean, decoded: Boolean, mimeType: String?): ByteArray? { + return if (decoded) { + getRawBytes(bitmap, recycle = recycle) + } else { + getEncodedBytes(bitmap, canHaveAlpha = MimeTypes.canHaveAlpha(mimeType), recycle = recycle) + } + } + + private fun getRawBytes(bitmap: Bitmap?, recycle: Boolean): ByteArray? { + bitmap ?: return null + + val byteCount = bitmap.byteCount + val width = bitmap.width + val height = bitmap.height + val config = bitmap.config + val colorSpace = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) bitmap.colorSpace else null + + val byteBufferSize = byteCount + RAW_BYTES_TRAILER_LENGTH + if (!MemoryUtils.canAllocate(byteBufferSize)) { + throw Exception("bitmap buffer is $byteCount bytes, which cannot be allocated to a new byte array") + } + + try { + // `ByteBuffer` initial order is always `BIG_ENDIAN` + var bytes = ByteBuffer.allocate(byteBufferSize).apply { + bitmap.copyPixelsToBuffer(this) + }.array() + + // do not access bitmap after recycling + if (recycle) bitmap.recycle() + + // convert pixel format and color space, if necessary + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + colorSpace?.let { srcColorSpace -> + val dstColorSpace = ColorSpace.get(ColorSpace.Named.SRGB) + val connector = ColorSpace.connect(srcColorSpace, dstColorSpace) + if (config == Bitmap.Config.ARGB_8888) { + if (srcColorSpace != dstColorSpace) { + argb8888ToArgb8888(bytes, connector, end = byteCount) + } + } else if (config == Bitmap.Config.RGBA_F16) { + rgbaf16ToArgb8888(bytes, connector, end = byteCount) + val newConfigByteCount = byteCount / (BPP_RGBA_F16 / BPP_ARGB_8888) + bytes = bytes.sliceArray(0..<newConfigByteCount + RAW_BYTES_TRAILER_LENGTH) + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && config == Bitmap.Config.RGBA_1010102) { + rgba1010102ToArgb8888(bytes, connector, end = byteCount) + } + } + } + + // append bitmap size for use by the caller to interpret the raw bytes + val trailerOffset = bytes.size - RAW_BYTES_TRAILER_LENGTH + bytes = ByteBuffer.wrap(bytes).apply { + position(trailerOffset) + putInt(width) + putInt(height) + // trailer byte to indicate whether the returned bytes are decoded/encoded + put(FORMAT_BYTE_DECODED) + }.array() + + return bytes + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get bytes from bitmap", e) + } + return null + } + + private suspend fun getEncodedBytes(bitmap: Bitmap?, canHaveAlpha: Boolean = false, quality: Int = 100, recycle: Boolean): ByteArray? { + bitmap ?: return null + + val stream: ByteArrayOutputStream + mutex.withLock { + // this method is called a lot, so we try and reuse output streams + // to reduce inner array allocations, and make the GC run less frequently + stream = if (freeBaos.isNotEmpty()) { + freeBaos.removeAt(0) + } else { + ByteArrayOutputStream(INITIAL_BUFFER_SIZE) + } + } + try { + // `Bitmap.CompressFormat.PNG` is slower than `JPEG`, but it allows transparency + // the BMP format allows an alpha channel, but Android decoding seems to ignore it + if (canHaveAlpha && bitmap.hasAlpha()) { + bitmap.compress(Bitmap.CompressFormat.PNG, quality, stream) + } else { + bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream) + } + if (recycle) bitmap.recycle() + + // trailer byte to indicate whether the returned bytes are decoded/encoded + stream.write(FORMAT_BYTE_ENCODED) + + val bufferSize = stream.size() + if (!MemoryUtils.canAllocate(bufferSize)) { + throw Exception("bitmap compressed to $bufferSize bytes, which cannot be allocated to a new byte array") + } + + val byteArray = stream.toByteArray() + stream.reset() + mutex.withLock { + freeBaos.add(stream) + } + return byteArray + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to get bytes from bitmap", e) + } + return null + } + + // convert bytes, without reallocation: + // - from original color space to sRGB. + @RequiresApi(Build.VERSION_CODES.O) + private fun argb8888ToArgb8888(bytes: ByteArray, connector: ColorSpace.Connector, start: Int = 0, end: Int = bytes.size) { + // unpacking from ARGB_8888 and packing to ARGB_8888 + // stored as [3,2,1,0] -> [AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR] + for (i in start..<end step BPP_ARGB_8888) { + // mask with `0xff` to yield values in [0, 255], instead of [-128, 127] + val iB = bytes[i + 2].toInt() and 0xff + val iG = bytes[i + 1].toInt() and 0xff + val iR = bytes[i].toInt() and 0xff + + // components as floats in sRGB + val srgbFloats = connector.transform(iR / MAX_8_BITS_FLOAT, iG / MAX_8_BITS_FLOAT, iB / MAX_8_BITS_FLOAT) + val srgbR = (srgbFloats[0] * 255.0f + 0.5f).toInt() + val srgbG = (srgbFloats[1] * 255.0f + 0.5f).toInt() + val srgbB = (srgbFloats[2] * 255.0f + 0.5f).toInt() + + // keep alpha as it is, in `bytes[i + 3]` + bytes[i + 2] = srgbB.toByte() + bytes[i + 1] = srgbG.toByte() + bytes[i] = srgbR.toByte() + } + } + + // convert bytes, without reallocation: + // - from config RGBA_F16 to ARGB_8888, + // - from original color space to sRGB. + @RequiresApi(Build.VERSION_CODES.O) + private fun rgbaf16ToArgb8888(bytes: ByteArray, connector: ColorSpace.Connector, start: Int = 0, end: Int = bytes.size) { + val indexDivider = BPP_RGBA_F16 / BPP_ARGB_8888 + for (i in start..<end step BPP_RGBA_F16) { + // unpacking from RGBA_F16 + // stored as [7,6,5,4,3,2,1,0] -> [AAAAAAAA AAAAAAAA BBBBBBBB BBBBBBBB GGGGGGGG GGGGGGGG RRRRRRRR RRRRRRRR] + val i7 = bytes[i + 7].toInt() + val i6 = bytes[i + 6].toInt() + val i5 = bytes[i + 5].toInt() + val i4 = bytes[i + 4].toInt() + val i3 = bytes[i + 3].toInt() + val i2 = bytes[i + 2].toInt() + val i1 = bytes[i + 1].toInt() + val i0 = bytes[i].toInt() + + val hA = Half((((i7 and 0xff) shl 8) or (i6 and 0xff)).toShort()) + val hB = Half((((i5 and 0xff) shl 8) or (i4 and 0xff)).toShort()) + val hG = Half((((i3 and 0xff) shl 8) or (i2 and 0xff)).toShort()) + val hR = Half((((i1 and 0xff) shl 8) or (i0 and 0xff)).toShort()) + + // components as floats in sRGB + val srgbFloats = connector.transform(hR.toFloat(), hG.toFloat(), hB.toFloat()) + val srgbR = (srgbFloats[0] * 255.0f + 0.5f).toInt() + val srgbG = (srgbFloats[1] * 255.0f + 0.5f).toInt() + val srgbB = (srgbFloats[2] * 255.0f + 0.5f).toInt() + val alpha = (hA.toFloat() * 255.0f + 0.5f).toInt() + + // packing to ARGB_8888 + // stored as [3,2,1,0] -> [AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR] + val dstI = i / indexDivider + bytes[dstI + 3] = alpha.toByte() + bytes[dstI + 2] = srgbB.toByte() + bytes[dstI + 1] = srgbG.toByte() + bytes[dstI] = srgbR.toByte() + } + } + + // convert bytes, without reallocation: + // - from config RGBA_1010102 to ARGB_8888, + // - from original color space to sRGB. + @RequiresApi(Build.VERSION_CODES.O) + private fun rgba1010102ToArgb8888(bytes: ByteArray, connector: ColorSpace.Connector, start: Int = 0, end: Int = bytes.size) { + val alphaFactor = 255.0f / MAX_2_BITS_FLOAT + + for (i in start..<end step BPP_RGBA_1010102) { + // unpacking from RGBA_1010102 + // stored as [3,2,1,0] -> [AABBBBBB BBBBGGGG GGGGGGRR RRRRRRRR] + val i3 = bytes[i + 3].toInt() + val i2 = bytes[i + 2].toInt() + val i1 = bytes[i + 1].toInt() + val i0 = bytes[i].toInt() + + val iA = ((i3 and 0xc0) shr 6) + val iB = ((i3 and 0x3f) shl 4) or ((i2 and 0xf0) shr 4) + val iG = ((i2 and 0x0f) shl 6) or ((i1 and 0xfc) shr 2) + val iR = ((i1 and 0x03) shl 8) or ((i0 and 0xff) shr 0) + + // components as floats in sRGB + val srgbFloats = connector.transform(iR / MAX_10_BITS_FLOAT, iG / MAX_10_BITS_FLOAT, iB / MAX_10_BITS_FLOAT) + val srgbR = (srgbFloats[0] * 255.0f + 0.5f).toInt() + val srgbG = (srgbFloats[1] * 255.0f + 0.5f).toInt() + val srgbB = (srgbFloats[2] * 255.0f + 0.5f).toInt() + val alpha = (iA * alphaFactor + 0.5f).toInt() + + // packing to ARGB_8888 + // stored as [3,2,1,0] -> [AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR] + bytes[i + 3] = alpha.toByte() + bytes[i + 2] = srgbB.toByte() + bytes[i + 1] = srgbG.toByte() + bytes[i] = srgbR.toByte() + } + } + + fun applyExifOrientation(context: Context, bitmap: Bitmap?, rotationDegrees: Int?, isFlipped: Boolean?): Bitmap? { + if (bitmap == null || rotationDegrees == null || isFlipped == null) return bitmap + if (rotationDegrees == 0 && !isFlipped) return bitmap + val exifOrientation = getExifCode(rotationDegrees, isFlipped) + return TransformationUtils.rotateImageExif(getBitmapPool(context), bitmap, exifOrientation) + } + + fun centerSquareCrop(context: Context, bitmap: Bitmap?, size: Int): Bitmap? { + bitmap ?: return null + return TransformationUtils.centerCrop(getBitmapPool(context), bitmap, size, size) + } + + fun getBitmapPool(context: Context) = Glide.get(context).bitmapPool +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/BmpWriter.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/BmpWriter.kt new file mode 100644 index 0000000..bfd9947 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/BmpWriter.kt @@ -0,0 +1,110 @@ +package deckers.thibault.aves.utils + +import android.graphics.Bitmap +import java.io.OutputStream +import java.nio.ByteBuffer + +object BmpWriter { + private const val FILE_HEADER_SIZE = 14 + private const val INFO_HEADER_SIZE = 40 + private const val BYTE_PER_PIXEL = 3 + private val pad = ByteArray(3) + + // file header + private val bfType = byteArrayOf('B'.code.toByte(), 'M'.code.toByte()) + private val bfReserved1 = intToWord(0) + private val bfReserved2 = intToWord(0) + private val bfOffBits = intToDWord(FILE_HEADER_SIZE + INFO_HEADER_SIZE) + + // info header + private val biSize = intToDWord(INFO_HEADER_SIZE) + private val biPlanes = intToWord(1) + private val biBitCount = intToWord(BYTE_PER_PIXEL * 8) + private val biCompression = intToDWord(0) + private val biXPelsPerMeter = intToDWord(0) + private val biYPelsPerMeter = intToDWord(0) + private val biClrUsed = intToDWord(0) + private val biClrImportant = intToDWord(0) + + // converts an int to a word (2-byte array) + private fun intToWord(v: Int): ByteArray { + val retValue = ByteArray(2) + retValue[0] = (v and 0xFF).toByte() + retValue[1] = (v shr 8 and 0xFF).toByte() + return retValue + } + + // converts an int to a double word (4-byte array) + private fun intToDWord(v: Int): ByteArray { + val retValue = ByteArray(4) + retValue[0] = (v and 0xFF).toByte() + retValue[1] = (v shr 8 and 0xFF).toByte() + retValue[2] = (v shr 16 and 0xFF).toByte() + retValue[3] = (v shr 24 and 0xFF).toByte() + return retValue + } + + fun writeRGB24( + bitmap: Bitmap, + outputStream: OutputStream + ) { + // init + val biWidth = bitmap.width + val biHeight = bitmap.height + val padPerRow = (4 - (biWidth * BYTE_PER_PIXEL) % 4) % 4 + val biSizeImage = (biWidth * BYTE_PER_PIXEL + padPerRow) * biHeight + val bfSize = FILE_HEADER_SIZE + INFO_HEADER_SIZE + biSizeImage + + var buffer = ByteBuffer.allocate(FILE_HEADER_SIZE + INFO_HEADER_SIZE) + + // file header + buffer.put(bfType) + buffer.put(intToDWord(bfSize)) + buffer.put(bfReserved1) + buffer.put(bfReserved2) + buffer.put(bfOffBits) + + // info header + buffer.put(biSize) + buffer.put(intToDWord(biWidth)) + buffer.put(intToDWord(biHeight)) + buffer.put(biPlanes) + buffer.put(biBitCount) + buffer.put(biCompression) + buffer.put(intToDWord(biSizeImage)) + buffer.put(biXPelsPerMeter) + buffer.put(biYPelsPerMeter) + buffer.put(biClrUsed) + buffer.put(biClrImportant) + + outputStream.write(buffer.array()) + + // pixels + buffer = ByteBuffer.allocate(biWidth * BYTE_PER_PIXEL + padPerRow) + val pixels = IntArray(biWidth) + val rgb = ByteArray(BYTE_PER_PIXEL) + var value: Int + var row = biHeight - 1 + while (row >= 0) { + bitmap.getPixels(pixels, 0, biWidth, 0, row, biWidth, 1) + + var column = 0 + while (column < biWidth) { + // non-premultiplied ARGB values in the sRGB color space + value = pixels[column] + // blue: [0], green: [1], red: [2] + rgb[0] = (value and 0xFF).toByte() + rgb[1] = (value shr 8 and 0xFF).toByte() + rgb[2] = (value shr 16 and 0xFF).toByte() + buffer.put(rgb) + column++ + } + if (padPerRow > 0) { + buffer.put(pad, 0, padPerRow) + } + outputStream.write(buffer.array()) + buffer.clear() + row-- + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/ByteUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ByteUtils.kt new file mode 100644 index 0000000..a0e1e83 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ByteUtils.kt @@ -0,0 +1,15 @@ +package deckers.thibault.aves.utils + +import java.nio.ByteBuffer + +fun ByteBuffer.toByteArray(): ByteArray { + val bytes = ByteArray(remaining()) + get(bytes, 0, bytes.size) + return bytes +} + +fun Int.toHex(): String = "0x${byteArrayOf(shr(8).toByte(), toByte()).toHex()}" + +fun ByteArray.toHex(): String = joinToString(separator = "") { it.toHex() } + +fun Byte.toHex(): String = "%02x".format(this)
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/CollectionUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/CollectionUtils.kt new file mode 100644 index 0000000..a2af9f4 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/CollectionUtils.kt @@ -0,0 +1,44 @@ +package deckers.thibault.aves.utils + +import android.os.Build + +// compatibility extension for `removeIf` for API <24 +fun <E> MutableList<E>.compatRemoveIf(filter: (t: E) -> Boolean): Boolean { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + this.removeIf(filter) + } else { + var removed = false + val each = this.iterator() + while (each.hasNext()) { + if (filter(each.next())) { + each.remove() + removed = true + } + } + return removed + } +} + +// Boyer-Moore algorithm for pattern searching +// Returns: an index of the first occurrence of the pattern or -1 if none is found. +fun ByteArray.indexOfBytes(pattern: ByteArray, start: Int = 0): Int { + val n: Int = this.size + val m: Int = pattern.size + val badChar = Array(256) { 0 } + var i = 0 + while (i < m) { + badChar[pattern[i].toUByte().toInt()] = i + i += 1 + } + var j: Int = m - 1 + var s = start + while (s <= (n - m)) { + while (j >= 0 && pattern[j] == this[s + j]) { + j -= 1 + } + if (j < 0) return s + s += Integer.max(1, j - badChar[this[s + j].toUByte().toInt()]) + j = m - 1 + } + return -1 +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat.kt new file mode 100644 index 0000000..eea1b08 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat.kt @@ -0,0 +1,84 @@ +package deckers.thibault.aves.utils + +import android.app.Activity +import android.content.Intent +import android.content.pm.ApplicationInfo +import android.content.pm.PackageManager +import android.content.pm.ResolveInfo +import android.graphics.BitmapRegionDecoder +import android.location.Address +import android.location.Geocoder +import android.os.Build +import android.os.Parcelable +import android.view.Display +import java.io.IOException +import java.io.InputStream + +inline fun <reified T> Intent.getParcelableExtraCompat(name: String): T? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + getParcelableExtra(name, T::class.java) + } else { + @Suppress("deprecation") + getParcelableExtra<Parcelable>(name) as? T + } +} + +fun Activity.getDisplayCompat(): Display? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + display + } else { + @Suppress("deprecation") + windowManager.defaultDisplay + } +} + +fun PackageManager.getApplicationInfoCompat(packageName: String, flags: Int): ApplicationInfo { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(flags.toLong())) + } else { + getApplicationInfo(packageName, flags) + } +} + +fun PackageManager.queryIntentActivitiesCompat(intent: Intent, flags: Int): List<ResolveInfo> { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + queryIntentActivities(intent, PackageManager.ResolveInfoFlags.of(flags.toLong())) + } else { + queryIntentActivities(intent, flags) + } +} + +fun Geocoder.getFromLocationCompat( + latitude: Double, + longitude: Double, + maxResults: Int, + processAddresses: (addresses: List<Address>) -> Unit, + onError: (errorCode: String, errorMessage: String?, errorDetails: Any?) -> Unit, +) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + Compat33.geocoderGetFromLocation(this, latitude, longitude, maxResults, processAddresses, onError) + } else { + try { + @Suppress("deprecation") + val addresses = getFromLocation(latitude, longitude, maxResults) ?: ArrayList() + processAddresses(addresses) + } catch (e: IOException) { + // `grpc failed`, etc. + onError("getAddress-network", "failed to get address because of network issues", e.message) + } catch (e: Exception) { + onError("getAddress-exception", "failed to get address", e.message) + } + } +} + +object BitmapRegionDecoderCompat { + @Throws(IOException::class) + fun newInstance(input: InputStream): BitmapRegionDecoder? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + BitmapRegionDecoder.newInstance(input) + } else { + @Suppress("deprecation") + BitmapRegionDecoder.newInstance(input, false) + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat33.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat33.kt new file mode 100644 index 0000000..5377732 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat33.kt @@ -0,0 +1,30 @@ +package deckers.thibault.aves.utils + +import android.location.Address +import android.location.Geocoder +import android.os.Build +import androidx.annotation.RequiresApi + +/** + * Compatibility layer in a separate object to avoid class loading issues on older Android versions. + * e.g. `ClassNotFoundException` for `android.location.Geocoder$GeocodeListener` + */ +@RequiresApi(Build.VERSION_CODES.TIRAMISU) +object Compat33 { + fun geocoderGetFromLocation( + geocoder: Geocoder, + latitude: Double, + longitude: Double, + maxResults: Int, + processAddresses: (addresses: List<Address>) -> Unit, + onError: (errorCode: String, errorMessage: String?, errorDetails: Any?) -> Unit, + ) { + geocoder.getFromLocation(latitude, longitude, maxResults, object : Geocoder.GeocodeListener { + override fun onGeocode(addresses: List<Address?>) = processAddresses(addresses.filterNotNull()) + + override fun onError(errorMessage: String?) { + onError("getAddress-asyncerror", "failed to get address", errorMessage) + } + }) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/ContextUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ContextUtils.kt new file mode 100644 index 0000000..7a0b937 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ContextUtils.kt @@ -0,0 +1,61 @@ +package deckers.thibault.aves.utils + +import android.content.ContentResolver +import android.content.ContentUris +import android.content.Context +import android.database.Cursor +import android.net.Uri +import android.provider.MediaStore +import android.util.Log +import deckers.thibault.aves.utils.UriUtils.tryParseId + +object ContextUtils { + private val LOG_TAG = LogUtils.createTag<ContextUtils>() + + fun Context.devicePixelRatio(): Float = resources.displayMetrics.density + + fun Context.resourceUri(resourceId: Int): Uri = with(resources) { + Uri.Builder() + .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) + .authority(getResourcePackageName(resourceId)) + .appendPath(getResourceTypeName(resourceId)) + .appendPath(getResourceEntryName(resourceId)) + .build() + } + + fun Context.queryContentPropValue(uri: Uri, mimeType: String, column: String): Any? { + var contentUri: Uri = uri + if (StorageUtils.isMediaStoreContentUri(uri)) { + uri.tryParseId()?.let { id -> + contentUri = when { + MimeTypes.isImage(mimeType) -> ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) + MimeTypes.isVideo(mimeType) -> ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id) + else -> uri + } + contentUri = StorageUtils.getOriginalUri(this, contentUri) + } + } + + var value: Any? = null + try { + val cursor = contentResolver.query(contentUri, arrayOf(column), null, null, null) + if (cursor == null || !cursor.moveToFirst()) { + Log.w(LOG_TAG, "failed to get cursor for contentUri=$contentUri column=$column") + } else { + value = when (cursor.getType(0)) { + Cursor.FIELD_TYPE_NULL -> null + Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(0) + Cursor.FIELD_TYPE_FLOAT -> cursor.getFloat(0) + Cursor.FIELD_TYPE_STRING -> cursor.getString(0) + Cursor.FIELD_TYPE_BLOB -> cursor.getBlob(0) + else -> null + } + cursor.close() + } + } catch (e: Exception) { + // throws SQLiteException/IllegalArgumentException when the requested prop is not a known column + Log.w(LOG_TAG, "failed to get value for contentUri=$contentUri column=$column", e) + } + return value + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/ExceptionUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ExceptionUtils.kt new file mode 100644 index 0000000..f164c97 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ExceptionUtils.kt @@ -0,0 +1,10 @@ +package deckers.thibault.aves.utils + +inline fun <reified T : Throwable> Exception.anyCauseIs(): Boolean { + var cause: Throwable? = this + while (cause != null) { + if (cause is T) return true + cause = cause.cause + } + return false +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/FileUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/FileUtils.kt new file mode 100644 index 0000000..6b8a37e --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/FileUtils.kt @@ -0,0 +1,45 @@ +package deckers.thibault.aves.utils + +import android.os.Build +import java.io.File +import java.io.InputStream +import java.io.OutputStream +import java.nio.channels.Channels +import java.nio.channels.FileChannel +import java.nio.file.StandardOpenOption + +object FileUtils { + fun File.transferFrom(inputStream: InputStream?, streamLength: Long?) { + inputStream ?: return + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && streamLength != null) { + FileChannel.open(toPath(), StandardOpenOption.WRITE).use { fileOutput -> + Channels.newChannel(inputStream).use { input -> + fileOutput.transferFrom(input, 0, streamLength) + } + } + } else { + outputStream().use { fileOutput -> + inputStream.use { input -> + input.copyTo(fileOutput) + } + } + } + } + + fun File.transferTo(outputStream: OutputStream) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + FileChannel.open(toPath()).use { fileInput -> + Channels.newChannel(outputStream).use { output -> + fileInput.transferTo(0, fileInput.size(), output) + } + } + } else { + inputStream().use { fileInput -> + outputStream.use { output -> + fileInput.copyTo(output) + } + } + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/FlutterUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/FlutterUtils.kt new file mode 100644 index 0000000..e7b1792 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/FlutterUtils.kt @@ -0,0 +1,72 @@ +package deckers.thibault.aves.utils + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.util.Log +import io.flutter.FlutterInjector +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.embedding.engine.dart.DartExecutor +import io.flutter.embedding.engine.loader.FlutterLoader +import io.flutter.view.FlutterCallbackInformation +import kotlin.coroutines.Continuation +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine + +object FlutterUtils { + private val LOG_TAG = LogUtils.createTag<FlutterUtils>() + + suspend fun initFlutterEngine( + context: Context, + sharedPreferencesKey: String, + callbackHandleKey: String, + engineSetter: (engine: FlutterEngine) -> Unit, + ) { + val callbackHandle = context.getSharedPreferences(sharedPreferencesKey, Context.MODE_PRIVATE).getLong(callbackHandleKey, 0) + if (callbackHandle == 0L) { + Log.e(LOG_TAG, "failed to retrieve registered callback handle for sharedPreferencesKey=$sharedPreferencesKey callbackHandleKey=$callbackHandleKey") + return + } + + lateinit var flutterLoader: FlutterLoader + runOnUiThread { + // initialization must happen on the main thread + flutterLoader = FlutterInjector.instance().flutterLoader().apply { + startInitialization(context) + ensureInitializationComplete(context, null) + } + } + + val callbackInfo = FlutterCallbackInformation.lookupCallbackInformation(callbackHandle) + if (callbackInfo == null) { + Log.e(LOG_TAG, "failed to find callback information for sharedPreferencesKey=$sharedPreferencesKey callbackHandleKey=$callbackHandleKey") + return + } + + val args = DartExecutor.DartCallback( + context.assets, + flutterLoader.findAppBundlePath(), + callbackInfo + ) + runOnUiThread { + val engine = FlutterEngine(context).apply { + dartExecutor.executeDartCallback(args) + } + engineSetter(engine) + } + } + + suspend fun runOnUiThread(r: Runnable) { + val mainLooper = Looper.getMainLooper() + if (Looper.myLooper() != mainLooper) { + suspendCoroutine { cont: Continuation<Boolean> -> + Handler(mainLooper).post { + r.run() + cont.resume(true) + } + } + } else { + r.run() + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/HashUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/HashUtils.kt new file mode 100644 index 0000000..c90e317 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/HashUtils.kt @@ -0,0 +1,35 @@ +package deckers.thibault.aves.utils + +import java.io.InputStream +import java.math.BigInteger +import java.security.MessageDigest + +object HashUtils { + fun getHash(input: InputStream, algorithmKey: String): String { + val algorithm = toMessageDigestAlgorithm(algorithmKey) + val digest = MessageDigest.getInstance(algorithm) + val buffer = ByteArray(1 shl 14) + var read: Int + while ((input.read(buffer).also { read = it }) > 0) { + digest.update(buffer, 0, read) + } + val md5sum = digest.digest() + val output = BigInteger(1, md5sum).toString(16) + + return when (algorithm) { + "MD5" -> output.padStart(32, '0') // 128 bits = 32 hex digits + "SHA-1" -> output.padStart(40, '0') // 160 bits = 40 hex digits + "SHA-256" -> output.padStart(64, '0') // 256 bits = 64 hex digits + else -> throw IllegalArgumentException("unsupported hash algorithm: $algorithmKey") + } + } + + private fun toMessageDigestAlgorithm(algorithmKey: String): String { + return when (algorithmKey) { + "md5" -> "MD5" + "sha1" -> "SHA-1" + "sha256" -> "SHA-256" + else -> throw IllegalArgumentException("unsupported hash algorithm: $algorithmKey") + } + } +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/LogUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/LogUtils.kt new file mode 100644 index 0000000..e7fb5f7 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/LogUtils.kt @@ -0,0 +1,26 @@ +package deckers.thibault.aves.utils + +object LogUtils { + const val LOG_TAG_MAX_LENGTH = 23 + + val LOG_TAG_PACKAGE_PATTERN = Regex("(\\w)(\\w*)\\.") + val LOWER_CASE_PATTERN = Regex("[a-z]") + + // create an Android logger friendly log tag for the specified class + inline fun <reified T> createTag(): String { + val kClass = T::class + // shorten class name to "a.b.CccDdd" + var logTag = LOG_TAG_PACKAGE_PATTERN.replace(kClass.qualifiedName!!, "$1.") + if (logTag.length > LOG_TAG_MAX_LENGTH) { + // shorten class name to "a.b.CD" + val simpleName = kClass.simpleName!! + val shortSimpleName = simpleName.replace(LOWER_CASE_PATTERN, "") + logTag = logTag.replace(simpleName, shortSimpleName) + if (logTag.length > LOG_TAG_MAX_LENGTH) { + // shorten class name to "CD" + logTag = shortSimpleName + } + } + return logTag + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/MathUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MathUtils.kt new file mode 100644 index 0000000..7002c07 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MathUtils.kt @@ -0,0 +1,9 @@ +package deckers.thibault.aves.utils + +import kotlin.math.log2 +import kotlin.math.pow + +object MathUtils { + fun highestPowerOf2(x: Int): Int = highestPowerOf2(x.toDouble()) + fun highestPowerOf2(x: Double): Int = if (x < 1) 0 else 2.toDouble().pow(log2(x).toInt()).toInt() +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/MemoryUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MemoryUtils.kt new file mode 100644 index 0000000..fc91e2d --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MemoryUtils.kt @@ -0,0 +1,19 @@ +package deckers.thibault.aves.utils + +import android.util.Log + +object MemoryUtils { + private val LOG_TAG = LogUtils.createTag<MemoryUtils>() + + fun canAllocate(byteSize: Number?): Boolean { + byteSize ?: return true + val availableHeapSize = getAvailableHeapSize() + val danger = byteSize.toLong() > availableHeapSize + if (danger) { + Log.e(LOG_TAG, "trying to handle $byteSize bytes, with only $availableHeapSize free bytes") + } + return !danger + } + + fun getAvailableHeapSize() = Runtime.getRuntime().let { it.maxMemory() - (it.totalMemory() - it.freeMemory()) } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/MimeTypes.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MimeTypes.kt new file mode 100644 index 0000000..9996813 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MimeTypes.kt @@ -0,0 +1,192 @@ +package deckers.thibault.aves.utils + +import android.webkit.MimeTypeMap +import deckers.thibault.aves.glide.MultiPageImage +import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface + +object MimeTypes { + const val ANY = "*/*" + + // generic raster + private const val AVIF = "image/avif" + const val BMP = "image/bmp" + private const val DJVU = "image/vnd.djvu" + const val GIF = "image/gif" + const val HEIC = "image/heic" + const val HEIF = "image/heif" + private const val ICO = "image/x-icon" + const val JPEG = "image/jpeg" + const val PNG = "image/png" + const val PSD_VND = "image/vnd.adobe.photoshop" + const val PSD_X = "image/x-photoshop" + const val TIFF = "image/tiff" + private const val WBMP = "image/vnd.wap.wbmp" + const val WEBP = "image/webp" + + // raw raster + private const val ARW = "image/x-sony-arw" + private const val CR2 = "image/x-canon-cr2" + private const val CRW = "image/x-canon-crw" + private const val DCR = "image/x-kodak-dcr" + const val DNG = "image/dng" + const val DNG_ADOBE = "image/x-adobe-dng" + private const val ERF = "image/x-epson-erf" + private const val K25 = "image/x-kodak-k25" + private const val KDC = "image/x-kodak-kdc" + private const val MRW = "image/x-minolta-mrw" + private const val NEF = "image/x-nikon-nef" + private const val NRW = "image/x-nikon-nrw" + private const val ORF = "image/x-olympus-orf" + private const val PEF = "image/x-pentax-pef" + private const val RAF = "image/x-fuji-raf" + private const val RAW = "image/x-panasonic-raw" + private const val RW2 = "image/x-panasonic-rw2" + private const val SR2 = "image/x-sony-sr2" + private const val SRF = "image/x-sony-srf" + private const val SRW = "image/x-samsung-srw" + private const val X3F = "image/x-sigma-x3f" + + // vector + const val SVG = "image/svg+xml" + + // video + private const val AVI = "video/avi" + private const val AVI_VND = "video/vnd.avi" + const val DVD = "video/dvd" + private const val MKV = "video/x-matroska" + const val MOV = "video/quicktime" + private const val MP2T = "video/mp2t" + private const val MP2TS = "video/mp2ts" + const val MP4 = "video/mp4" + private const val OGV = "video/ogg" + private const val WEBM = "video/webm" + + // others + const val ZIP = "application/zip" + + fun isImage(mimeType: String?) = mimeType != null && mimeType.startsWith("image") + + fun isVideo(mimeType: String?) = mimeType != null && mimeType.startsWith("video") + + // assume that `HEIF` is a `HEIC` (using the default `HEVC` codec) + fun isHeic(mimeType: String?) = mimeType == HEIC || mimeType == HEIF + + // `AVIF` and `HEIC` both derive from `HEIF`, which derives from `ISOBMFF`. + // `MP4` also derives from `ISOBMFF` but is not an image format. + fun isIsoBMFFImage(mimeType: String?) = mimeType == AVIF || isHeic(mimeType) + + fun isRaw(mimeType: String): Boolean { + return when (mimeType) { + ARW, CR2, CRW, DCR, DNG, DNG_ADOBE, ERF, K25, KDC, MRW, NEF, NRW, ORF, PEF, RAF, RAW, RW2, SR2, SRF, SRW, X3F -> true + else -> false + } + } + + // returns whether the specified MIME type represents + // a raster image format that allows an alpha channel + fun canHaveAlpha(mimeType: String?) = when (mimeType) { + AVIF, BMP, GIF, ICO, PNG, SVG, TIFF, WEBP -> true + else -> false + } + + // as of Flutter v3.16.4, with additional custom handling for SVG in Dart + fun handleEncodedBytesInFlutter(mimeType: String) = when (mimeType) { + JPEG, PNG, GIF, WEBP, BMP, WBMP, ICO, SVG -> true + else -> false + } + + // as of `metadata-extractor` v2.14.0 + fun canReadWithMetadataExtractor(mimeType: String?) = when (mimeType) { + DJVU, SVG, WBMP -> false + MKV, MP2T, MP2TS, OGV, WEBM -> false + else -> true + } + + // as of `ExifInterface` v1.4.1, method `isSupportedMimeType` reports no support for AVIF, + // but documentation reports: + // * Supported for reading: JPEG, PNG, WebP, HEIC, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW, RAF, AVIF (on API 31+). + // * Supported for writing: JPEG, PNG, WebP. + fun canReadWithExifInterface(mimeType: String, strict: Boolean = true): Boolean { + if (!strict) return true + return ExifInterface.isSupportedMimeType(mimeType) || mimeType == AVIF + } + + // as of latest PixyMeta + fun canReadWithPixyMeta(mimeType: String) = when (mimeType) { + JPEG, TIFF, PNG, GIF, BMP -> true + else -> false + } + + fun canEditExif(mimeType: String) = when (mimeType) { + // as of androidx.exifinterface:exifinterface:1.3.4 + JPEG, PNG, WEBP -> true + else -> false + } + + fun canEditIptc(mimeType: String) = when (mimeType) { + // as of latest PixyMeta + JPEG, TIFF -> true + else -> false + } + + fun canEditXmp(mimeType: String) = when (mimeType) { + // as of latest PixyMeta + JPEG, TIFF, PNG, GIF -> true + // using `mp4parser` + MP4 -> true + else -> false + } + + fun canRemoveMetadata(mimeType: String) = when (mimeType) { + // as of latest PixyMeta + JPEG, TIFF -> true + else -> false + } + + // Glide automatically applies EXIF orientation when decoding images of known formats + // but we need to rotate the decoded bitmap for the other formats + // maybe related to ExifInterface version used by Glide: + // https://github.com/bumptech/glide/blob/master/gradle.properties#L21 + fun needRotationAfterGlide(mimeType: String, pageId: Int?): Boolean { + return if (pageId != null && MultiPageImage.isSupported(mimeType)) { + true + } else when (mimeType) { + AVIF, HEIC, HEIF, PNG, TIFF, WEBP -> true + else -> isRaw(mimeType) + } + } + + // Thumbnails obtained from the Media Store are automatically rotated + // according to EXIF orientation when decoding images of known formats + // but we need to rotate the decoded bitmap for the other formats + fun needRotationAfterContentResolverThumbnail(mimeType: String) = when (mimeType) { + DNG, DNG_ADOBE, PNG -> true + else -> false + } + + // extensions + + // among other refs: + // - https://android.googlesource.com/platform/external/mime-support/+/refs/heads/master/mime.types + fun extensionFor(mimeType: String, defaultExtension: String?): String = when (mimeType) { + AVI, AVI_VND -> ".avi" + DNG, DNG_ADOBE -> ".dng" + HEIC, HEIF -> ".heif" + MP2T, MP2TS -> ".m2ts" + PSD_VND, PSD_X -> ".psd" + else -> { + val ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType) ?: defaultExtension + if (ext != null) { + // fallback to provided extension when available, + // typically the original file extension when moving/renaming + if (ext.startsWith(".")) ext else ".$ext" + } else { + // fallback to generic extensions, + // as incorrect file extensions are better than none for media detection + if (isVideo(mimeType)) ".mp4" else ".jpg" + } + } + } + + val TIFF_EXTENSION_PATTERN = Regex(".*\\.tiff?", RegexOption.IGNORE_CASE) +} diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/PermissionManager.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/PermissionManager.kt new file mode 100644 index 0000000..a5a2352 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/PermissionManager.kt @@ -0,0 +1,243 @@ +package deckers.thibault.aves.utils + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Binder +import android.os.Build +import android.os.Environment +import android.provider.DocumentsContract +import android.provider.MediaStore +import android.util.Log +import androidx.annotation.RequiresApi +import deckers.thibault.aves.MainActivity +import deckers.thibault.aves.PendingStorageAccessResultHandler +import deckers.thibault.aves.model.FieldMap +import deckers.thibault.aves.utils.StorageUtils.PathSegments +import java.io.File +import java.util.Locale +import java.util.concurrent.CompletableFuture + +object PermissionManager { + private val LOG_TAG = LogUtils.createTag<PermissionManager>() + + private val MEDIA_STORE_INSERTION_PRIMARY_DIRS = listOf( + Environment.DIRECTORY_DCIM, + Environment.DIRECTORY_DOWNLOADS, + Environment.DIRECTORY_PICTURES, + ) + + fun requestDirectoryAccess(activity: Activity, path: String, onGranted: (uri: Uri) -> Unit, onDenied: () -> Unit) { + Log.i(LOG_TAG, "request user to select and grant access permission to path=$path") + + // `StorageVolume.createOpenDocumentTreeIntent` is an alternative, + // and it helps with initial volume, but not with initial directory + val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + // initial URI should not be a `tree document URI`, but a simple `document URI` + StorageUtils.convertDirPathToDocumentUri(activity, path)?.let { + intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, it) + } + } + + if (intent.resolveActivity(activity.packageManager) != null) { + MainActivity.pendingStorageAccessResultHandlers[MainActivity.DOCUMENT_TREE_ACCESS_REQUEST] = PendingStorageAccessResultHandler(path, onGranted, onDenied) + activity.startActivityForResult(intent, MainActivity.DOCUMENT_TREE_ACCESS_REQUEST) + } else { + MainActivity.notifyError("failed to resolve activity for intent=$intent extras=${intent.extras}") + onDenied() + } + } + + @RequiresApi(Build.VERSION_CODES.R) + fun requestMediaFileAccess(activity: Activity, uris: List<Uri>, mimeTypes: List<String>): Boolean { + val safeUris = uris.mapIndexed { index, uri -> StorageUtils.getMediaStoreScopedStorageSafeUri(uri, mimeTypes[index]) } + + val todoUris = ArrayList<Uri>() + val pid = Binder.getCallingPid() + val uid = Binder.getCallingUid() + val flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + activity.checkUriPermissions(safeUris, pid, uid, flags) + } else { + safeUris.map { activity.checkUriPermission(it, pid, uid, flags) }.toIntArray() + }.forEachIndexed { index, permission -> + if (permission != PackageManager.PERMISSION_GRANTED) { + todoUris.add(safeUris[index]) + } + } + if (todoUris.isEmpty()) return true + + Log.i(LOG_TAG, "request user to select and grant access permission to uris=$todoUris") + val intentSender = MediaStore.createWriteRequest(activity.contentResolver, safeUris).intentSender + MainActivity.pendingScopedStoragePermissionCompleter = CompletableFuture<Boolean>() + activity.startIntentSenderForResult(intentSender, MainActivity.MEDIA_WRITE_BULK_PERMISSION_REQUEST, null, 0, 0, 0, null) + val granted = MainActivity.pendingScopedStoragePermissionCompleter!!.join() + MainActivity.pendingScopedStoragePermissionCompleter = null + + return granted + } + + fun getGrantedDirForPath(context: Context, anyPath: String): String? { + return getAccessibleDirs(context).firstOrNull { anyPath.startsWith(it) } + } + + fun getInaccessibleDirectories(context: Context, dirPaths: List<String>): List<Map<String, String>> { + val concreteDirPaths = dirPaths.filter { it != StorageUtils.TRASH_PATH_PLACEHOLDER } + val accessibleDirs = getAccessibleDirs(context) + val restrictedPrimaryDirectoriesLower = getRestrictedPrimaryDirectories().map { it.lowercase(Locale.ROOT) } + + // find set of inaccessible directories for each volume + val dirsPerVolume = HashMap<String, MutableSet<String>>() + for (dirPath in concreteDirPaths.map { if (it.endsWith(File.separator)) it else it + File.separator }) { + if (accessibleDirs.none { dirPath.startsWith(it) }) { + // inaccessible dirs + val segments = PathSegments(context, dirPath) + segments.volumePath?.let { volumePath -> + val dirSet = dirsPerVolume[volumePath] ?: HashSet() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + // request primary directory on volume from Android 11 (API 30) + val relativeDir = segments.relativeDir + if (relativeDir != null) { + val dirSegments = relativeDir.split(File.separator).takeWhile { it.isNotEmpty() } + val primaryDir = dirSegments.firstOrNull() + if (dirSegments.size > 1 && restrictedPrimaryDirectoriesLower.contains(primaryDir?.lowercase(Locale.ROOT))) { + // request secondary directory (if any) for restricted primary directory + val dir = dirSegments.take(2).joinToString(File.separator) + // only register directories that exist on storage, so they can be selected for access grant + if (File(volumePath, dir).exists()) { + dirSet.add(dir) + } + } else { + primaryDir?.let { dirSet.add(it) } + } + } else { + // the requested path is the volume root itself + // which cannot be granted, due to Android 11 restrictions + dirSet.add("") + } + } else { + // request volume root until Android 10 (API 29) + dirSet.add("") + } + dirsPerVolume[volumePath] = dirSet + } + } + } + + // format for easier handling on Flutter + return ArrayList<Map<String, String>>().apply { + addAll(dirsPerVolume.flatMap { (volumePath, relativeDirs) -> + relativeDirs.map { relativeDir -> + hashMapOf( + "volumePath" to volumePath, + "relativeDir" to relativeDir, + ) + } + }) + } + } + + fun canInsertByMediaStore(directories: List<FieldMap>): Boolean { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val insertionDirsLower = MEDIA_STORE_INSERTION_PRIMARY_DIRS.map { it.lowercase(Locale.ROOT) } + directories.all { + val relativeDir = it["relativeDir"] as String + val segments = relativeDir.split(File.separator) + segments.isNotEmpty() && insertionDirsLower.contains(segments.first().lowercase(Locale.ROOT)) + } + } else { + true + } + } + + fun revokeDirectoryAccess(context: Context, path: String): Boolean { + return StorageUtils.convertDirPathToTreeDocumentUri(context, path)?.let { + releaseUriPermission(context, it) + true + } ?: false + } + + // returns paths matching directory URIs granted by the user + fun getGrantedDirs(context: Context): Set<String> { + val grantedDirs = HashSet<String>() + for (uriPermission in context.contentResolver.persistedUriPermissions) { + val dirPath = StorageUtils.convertTreeDocumentUriToDirPath(context, uriPermission.uri) + dirPath?.let { grantedDirs.add(it) } + } + return grantedDirs + } + + // returns paths accessible to the app (granted by the user or by default) + private fun getAccessibleDirs(context: Context): Set<String> { + val accessibleDirs = HashSet(getGrantedDirs(context)) + accessibleDirs.addAll(context.getExternalFilesDirs(null).filterNotNull().map { it.path }) + + // from API 21 / Android 5.0 / Lollipop, removable storage requires access permission, but directory access grant is possible + // from API 30 / Android 11 / R, any storage requires access permission + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) { + accessibleDirs.add(StorageUtils.getPrimaryVolumePath(context)) + } + return accessibleDirs + } + + private fun getRestrictedPrimaryDirectories(): List<String> { + val dirs = ArrayList<String>() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + // cf https://developer.android.com/about/versions/11/privacy/storage#directory-access + dirs.add(Environment.DIRECTORY_DOWNLOADS) + // depends on device, no documentation + dirs.add("Android") + } + return dirs + } + + // cf https://developer.android.com/about/versions/11/privacy/storage#directory-access + fun getRestrictedDirectories(context: Context): List<Map<String, String>> { + val dirs = ArrayList<Map<String, String>>() + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val volumePaths = StorageUtils.getVolumePaths(context) + dirs.addAll(volumePaths.map { + hashMapOf( + "volumePath" to it, + "relativeDir" to "", + ) + }) + for (relativeDir in getRestrictedPrimaryDirectories()) { + dirs.addAll(volumePaths.map { + hashMapOf( + "volumePath" to it, + "relativeDir" to relativeDir, + ) + }) + } + } + return dirs + } + + // As of Android 11, `MediaStore.getDocumentUri` fails if any of the persisted + // URI permissions we hold points to a folder that no longer exists, + // so we should remove these obsolete URIs before proceeding. + fun sanitizePersistedUriPermissions(context: Context) { + try { + for (uriPermission in context.contentResolver.persistedUriPermissions) { + val uri = uriPermission.uri + val path = StorageUtils.convertTreeDocumentUriToDirPath(context, uri) + if (path == null || !File(path).exists()) { + Log.d(LOG_TAG, "revoke URI permission for obsolete uri=$uri path=$path") + releaseUriPermission(context, uri) + } + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to sanitize persisted URI permissions", e) + } + } + + private fun releaseUriPermission(context: Context, it: Uri) { + val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + context.contentResolver.releasePersistableUriPermission(it, flags) + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt new file mode 100644 index 0000000..908d5a0 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt @@ -0,0 +1,788 @@ +package deckers.thibault.aves.utils + +import android.Manifest +import android.annotation.SuppressLint +import android.content.ContentResolver +import android.content.ContentUris +import android.content.Context +import android.content.pm.PackageManager +import android.media.MediaMetadataRetriever +import android.net.Uri +import android.os.Build +import android.os.ParcelFileDescriptor +import android.os.storage.StorageManager +import android.provider.DocumentsContract +import android.provider.MediaStore +import android.text.TextUtils +import android.util.Log +import androidx.core.net.toUri +import androidx.core.text.isDigitsOnly +import com.commonsware.cwac.document.DocumentFileCompat +import deckers.thibault.aves.model.provider.ImageProvider +import deckers.thibault.aves.utils.FileUtils.transferFrom +import deckers.thibault.aves.utils.MimeTypes.isImage +import deckers.thibault.aves.utils.MimeTypes.isVideo +import deckers.thibault.aves.utils.PermissionManager.getGrantedDirForPath +import deckers.thibault.aves.utils.UriUtils.tryParseId +import java.io.File +import java.io.FileInputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.util.Locale +import java.util.regex.Pattern + +object StorageUtils { + private val LOG_TAG = LogUtils.createTag<StorageUtils>() + + private const val SCHEME_CONTENT = ContentResolver.SCHEME_CONTENT + + // cf DocumentsContract.EXTERNAL_STORAGE_PROVIDER_AUTHORITY + private const val EXTERNAL_STORAGE_PROVIDER_AUTHORITY = "com.android.externalstorage.documents" + + // cf DocumentsContract.EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID + private const val EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID = "primary" + + private const val TREE_URI_ROOT = "$SCHEME_CONTENT://$EXTERNAL_STORAGE_PROVIDER_AUTHORITY/tree/" + + private val MEDIA_STORE_VOLUME_EXTERNAL = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) MediaStore.VOLUME_EXTERNAL else "external" + + // TODO TLAD get it from `MediaStore.Images.Media.EXTERNAL_CONTENT_URI`? + private val IMAGE_PATH_ROOT = "/$MEDIA_STORE_VOLUME_EXTERNAL/images/" + + // TODO TLAD get it from `MediaStore.Video.Media.EXTERNAL_CONTENT_URI`? + private val VIDEO_PATH_ROOT = "/$MEDIA_STORE_VOLUME_EXTERNAL/video/" + + private val UUID_PATTERN = Regex("[A-Fa-f\\d-]+") + private val TREE_URI_PATH_PATTERN = Pattern.compile("(.*?):(.*)") + + const val TRASH_PATH_PLACEHOLDER = "#trash" + + // whether the provided path is on one of this app specific directories: + // - /storage/{volume}/Android/data/{package_name}/files + // - /data/user/0/{package_name}/files + private fun isAppFile(context: Context, path: String): Boolean { + val dirs = listOf( + *context.getExternalFilesDirs(null).filterNotNull().toTypedArray(), + context.filesDir, + ) + return dirs.any { path.startsWith(it.path) } + } + + private fun appExternalFilesDirFor(context: Context, path: String): File? { + val dirs = context.getExternalFilesDirs(null).filterNotNull() + val volumePath = getVolumePath(context, path) + return volumePath?.let { dirs.firstOrNull { it.startsWith(volumePath) } } ?: dirs.firstOrNull() + } + + fun trashDirFor(context: Context, path: String): File? { + val externalFilesDir = appExternalFilesDirFor(context, path) + if (externalFilesDir == null) { + Log.e(LOG_TAG, "failed to find external files dir for path=$path") + return null + } + val trashDir = File(externalFilesDir, "trash") + trashDir.mkdirs() + if (!trashDir.exists()) { + Log.e(LOG_TAG, "failed to create directories at path=$trashDir") + return null + } + return trashDir + } + + fun getVaultRoot(context: Context) = ensureTrailingSeparator(File(context.filesDir, "vault").path) + + fun isInVault(context: Context, path: String) = path.startsWith(getVaultRoot(context)) + + /** + * Volume paths + */ + + // volume paths, with trailing "/" + private var mStorageVolumePaths: Array<String>? = null + + // primary volume path, with trailing "/" + private var mPrimaryVolumePath: String? = null + + fun getPrimaryVolumePath(context: Context): String { + if (mPrimaryVolumePath == null) { + mPrimaryVolumePath = findPrimaryVolumePath(context) + } + return mPrimaryVolumePath!! + } + + fun getVolumePaths(context: Context): Array<String> { + if (mStorageVolumePaths == null || mStorageVolumePaths!!.isEmpty()) { + mStorageVolumePaths = findVolumePaths(context) + } + return mStorageVolumePaths!! + } + + fun getVolumePath(context: Context, anyPath: String): String? { + return getVolumePaths(context).firstOrNull { anyPath.startsWith(it) } + } + + private fun getPathStepIterator(context: Context, anyPath: String, root: String?): Iterator<String?>? { + val rootLength = (root ?: getVolumePath(context, anyPath))?.length ?: return null + + var fileName: String? = null + var relativePath: String? = null + val lastSeparatorIndex = anyPath.lastIndexOf(File.separator) + 1 + if (lastSeparatorIndex > rootLength) { + fileName = anyPath.substring(lastSeparatorIndex) + relativePath = anyPath.substring(rootLength, lastSeparatorIndex) + } + relativePath ?: return null + + val pathSteps = relativePath.split(File.separator).filter { it.isNotEmpty() }.toMutableList() + if (fileName?.isNotEmpty() == true) { + pathSteps.add(fileName) + } + return pathSteps.iterator() + } + + private fun appSpecificVolumePath(file: File?): String? { + file ?: return null + val appSpecificPath = file.absolutePath + val relativePathStartIndex = appSpecificPath.indexOf("Android/data") + if (relativePathStartIndex < 0) return null + return appSpecificPath.substring(0, relativePathStartIndex) + } + + private fun findPrimaryVolumePath(context: Context): String? { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager + val path = sm?.primaryStorageVolume?.directory?.path + if (path != null) { + return ensureTrailingSeparator(path) + } + } + + // fallback + try { + // we want: + // /storage/emulated/0/ + // `Environment.getExternalStorageDirectory()` (deprecated) yields: + // /storage/emulated/0 + // `context.getExternalFilesDir(null)` yields: + // /storage/emulated/0/Android/data/{package_name}/files + return appSpecificVolumePath(context.getExternalFilesDir(null)) + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to find primary volume path", e) + } + return null + } + + private fun findVolumePaths(context: Context): Array<String> { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager + val paths = sm?.storageVolumes?.mapNotNull { it.directory?.path } + if (paths != null) { + return paths.map(::ensureTrailingSeparator).toTypedArray() + } + } + + // fallback + val paths = HashSet<String>() + try { + // Primary emulated SD-CARD + val rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET") ?: "" + if (TextUtils.isEmpty(rawEmulatedStorageTarget)) { + // fix of empty raw emulated storage on marshmallow + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + lateinit var files: List<File> + var validFiles: Boolean + val retryInterval = 100L + val maxDelay = 1000L + var totalDelay = 0L + do { + // `getExternalFilesDirs` sometimes include `null` when called right after getting read access + // (e.g. on API 30 emulator) so we retry until the file system is ready. + // It can also include `null` when there is a faulty SD card. + val externalFilesDirs = context.getExternalFilesDirs(null) + validFiles = !externalFilesDirs.contains(null) + if (validFiles) { + files = externalFilesDirs.filterNotNull() + } else { + Log.d(LOG_TAG, "External files dirs contain `null`. Retrying...") + totalDelay += retryInterval + try { + Thread.sleep(retryInterval) + } catch (e: InterruptedException) { + Log.e(LOG_TAG, "insomnia", e) + } + } + } while (!validFiles && totalDelay < maxDelay) + paths.addAll(files.mapNotNull(::appSpecificVolumePath)) + } else { + // Primary physical SD-CARD (not emulated) + val rawExternalStorage = System.getenv("EXTERNAL_STORAGE") ?: "" + + // Device has physical external storage; use plain paths. + if (TextUtils.isEmpty(rawExternalStorage)) { + // EXTERNAL_STORAGE undefined; falling back to default. + paths.addAll(physicalPaths) + } else { + paths.add(rawExternalStorage) + } + } + } else { + // Device has emulated storage; external storage paths should have userId burned into them. + // /storage/emulated/[0,1,2,...]/ + val path = getPrimaryVolumePath(context) + val rawUserId = path.split(File.separator).lastOrNull(String::isNotEmpty)?.takeIf { it.isDigitsOnly() } ?: "" + if (rawUserId.isEmpty()) { + paths.add(rawEmulatedStorageTarget) + } else { + paths.add(rawEmulatedStorageTarget + File.separator + rawUserId) + } + } + + // All Secondary SD-CARDs (all exclude primary) separated by ":" + System.getenv("SECONDARY_STORAGE")?.let { secondaryStorages -> + paths.addAll(secondaryStorages.split(File.pathSeparator).filter { it.isNotEmpty() }) + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to find volume paths", e) + } + + return paths.map { ensureTrailingSeparator(it) }.toTypedArray() + } + + // returns physicalPaths based on phone model + @SuppressLint("SdCardPath") + private val physicalPaths = arrayOf( + "/storage/sdcard0", + "/storage/sdcard1", //Motorola Xoom + "/storage/extsdcard", //Samsung SGS3 + "/storage/sdcard0/external_sdcard", //User request + "/mnt/extsdcard", + "/mnt/sdcard/external_sd", //Samsung galaxy family + "/mnt/external_sd", + "/mnt/media_rw/sdcard1", //4.4.2 on CyanogenMod S3 + "/removable/microsd", //Asus transformer prime + "/mnt/emmc", + "/storage/external_SD", //LG + "/storage/ext_sd", //HTC One Max + "/storage/removable/sdcard1", //Sony Xperia Z1 + "/data/sdext", + "/data/sdext2", + "/data/sdext3", + "/data/sdext4", + "/sdcard1", //Sony Xperia Z + "/sdcard2", //HTC One M8s + "/storage/microsd" //ASUS ZenFone 2 + ) + + /** + * Volume tree URIs + */ + + // e.g. + // /storage/emulated/0/ -> primary + // /storage/10F9-3F13/Pictures/ -> 10F9-3F13 + // /storage/extSdCard/ -> 1234-5678 [Android 5.1.1, Samsung Galaxy Core Prime] + private fun getVolumeUuidForDocumentUri(context: Context, anyPath: String): String? { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager + sm?.getStorageVolume(File(anyPath))?.let { volume -> + if (volume.isPrimary) { + return EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID + } + volume.uuid?.let { uuid -> + return uuid.uppercase(Locale.ROOT) + } + } + } + + // fallback for <N + getVolumePath(context, anyPath)?.let { volumePath -> + if (volumePath == getPrimaryVolumePath(context)) { + return EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID + } + volumePath.split(File.separator).lastOrNull { it.isNotEmpty() }?.let { uuid -> + if (uuid.matches(UUID_PATTERN)) { + return uuid.uppercase(Locale.ROOT) + } + } + + // fallback when UUID does not appear in the SD card volume path + context.contentResolver.persistedUriPermissions.firstOrNull { uriPermission -> + convertTreeDocumentUriToDirPath(context, uriPermission.uri)?.let { + getVolumePath(context, it)?.let { grantedVolumePath -> + grantedVolumePath == volumePath + } + } ?: false + }?.let { uriPermission -> + splitTreeDocumentUri(uriPermission.uri)?.let { (uuid, _) -> + return uuid + } + } + } + + Log.e(LOG_TAG, "failed to find volume UUID for anyPath=$anyPath") + return null + } + + // e.g. + // primary -> /storage/emulated/0/ + // 10F9-3F13 -> /storage/10F9-3F13/ + // 1234-5678 -> /storage/extSdCard/ [Android 5.1.1, Samsung Galaxy Core Prime] + private fun getVolumePathFromTreeDocumentUriUuid(context: Context, uuid: String): String? { + if (uuid == EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID) { + return getPrimaryVolumePath(context) + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager + if (sm != null) { + for (volumePath in getVolumePaths(context)) { + try { + val volume = sm.getStorageVolume(File(volumePath)) + if (volume != null && uuid.equals(volume.uuid, ignoreCase = true)) { + return volumePath + } + } catch (_: Exception) { + // ignore + } + } + } + } + + // fallback for <N + for (volumePath in getVolumePaths(context)) { + val volumeUuid = volumePath.split(File.separator).lastOrNull { it.isNotEmpty() } + if (uuid.equals(volumeUuid, ignoreCase = true)) { + return volumePath + } + } + + // fallback when UUID does not appear in the SD card volume path + val primaryVolumePath = getPrimaryVolumePath(context) + getVolumePaths(context).firstOrNull { volumePath -> + if (volumePath == primaryVolumePath) { + false + } else { + // exclude volumes that use regular naming scheme with UUID in them + // to prevent returning path with the UUID of a new volume + // when the argument is the UUID of an obsolete volume + val volumeUuid = volumePath.split(File.separator).lastOrNull { it.isNotEmpty() } + !(volumeUuid == null || volumeUuid.matches(UUID_PATTERN)) + } + }?.let { return it } + + Log.e(LOG_TAG, "failed to find volume path for UUID=$uuid") + return null + } + + // e.g. + // /storage/emulated/0/ -> content://com.android.externalstorage.documents/tree/primary%3A + // /storage/10F9-3F13/Pictures/ -> content://com.android.externalstorage.documents/tree/10F9-3F13%3APictures + fun convertDirPathToTreeDocumentUri(context: Context, dirPath: String): Uri? { + val uuid = getVolumeUuidForDocumentUri(context, dirPath) + if (uuid != null) { + val relativeDir = removeTrailingSeparator(PathSegments(context, dirPath).relativeDir ?: "") + return DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "$uuid:$relativeDir") + } + Log.e(LOG_TAG, "failed to convert dirPath=$dirPath to tree document URI") + return null + } + + // e.g. + // /storage/emulated/0/ -> content://com.android.externalstorage.documents/document/primary%3A + // /storage/10F9-3F13/Pictures/ -> content://com.android.externalstorage.documents/document/10F9-3F13%3APictures + fun convertDirPathToDocumentUri(context: Context, dirPath: String): Uri? { + val uuid = getVolumeUuidForDocumentUri(context, dirPath) + if (uuid != null) { + val relativeDir = removeTrailingSeparator(PathSegments(context, dirPath).relativeDir ?: "") + return DocumentsContract.buildDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "$uuid:$relativeDir") + } + Log.e(LOG_TAG, "failed to convert dirPath=$dirPath to document URI") + return null + } + + // e.g. + // content://com.android.externalstorage.documents/tree/primary%3A -> ("primary", "") + // content://com.android.externalstorage.documents/tree/10F9-3F13%3APictures -> ("10F9-3F13", "Pictures") + private fun splitTreeDocumentUri(treeDocumentUri: Uri): Pair<String, String>? { + val treeDocumentUriString = treeDocumentUri.toString() + if (treeDocumentUriString.length <= TREE_URI_ROOT.length) return null + val encoded = treeDocumentUriString.substring(TREE_URI_ROOT.length) + val matcher = TREE_URI_PATH_PATTERN.matcher(Uri.decode(encoded)) + with(matcher) { + if (find()) { + val uuid = group(1) + val relativePath = group(2) + if (uuid != null && relativePath != null) { + return Pair(uuid, relativePath) + } + } + } + Log.e(LOG_TAG, "failed to split treeDocumentUri=$treeDocumentUri to UUID and relative path") + return null + } + + // e.g. + // content://com.android.externalstorage.documents/tree/primary%3A -> /storage/emulated/0/ + // content://com.android.externalstorage.documents/tree/10F9-3F13%3APictures -> /storage/10F9-3F13/Pictures/ + fun convertTreeDocumentUriToDirPath(context: Context, treeDocumentUri: Uri): String? { + splitTreeDocumentUri(treeDocumentUri)?.let { (uuid, relativePath) -> + val volumePath = getVolumePathFromTreeDocumentUriUuid(context, uuid) + if (volumePath != null) { + return ensureTrailingSeparator(volumePath + relativePath) + } + } + Log.e(LOG_TAG, "failed to convert treeDocumentUri=$treeDocumentUri to path") + return null + } + + /** + * Document files + */ + + fun getDocumentFile(context: Context, anyPath: String, mediaUri: Uri): DocumentFileCompat? { + try { + if (requireAccessPermission(context, anyPath)) { + // need a document URI (not a media content URI) to open a `DocumentFile` output stream + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && isMediaStoreContentUri(mediaUri)) { + // cleanest API to get it + PermissionManager.sanitizePersistedUriPermissions(context) + try { + val docUri = MediaStore.getDocumentUri(context, mediaUri) + if (docUri != null) { + return DocumentFileCompat.fromSingleUri(context, docUri) + } + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to get document URI for mediaUri=$mediaUri", e) + } + } + + // fallback for older APIs + val df = getVolumePath(context, anyPath)?.let { convertDirPathToTreeDocumentUri(context, it) }?.let { getDocumentFileFromVolumeTree(context, it, anyPath) } + if (df != null) return df + + // try to strip user info, if any + if (mediaUri.userInfo != null) { + val genericMediaUri = stripMediaUriUserInfo(mediaUri) + Log.d(LOG_TAG, "retry getDocumentFile for mediaUri=$mediaUri without userInfo: $genericMediaUri") + return getDocumentFile(context, anyPath, genericMediaUri) + } + } + // good old `File` + return DocumentFileCompat.fromFile(File(anyPath)) + } catch (e: SecurityException) { + Log.w(LOG_TAG, "failed to get document file from mediaUri=$mediaUri", e) + } + return null + } + + // returns the directory `DocumentFile` (from tree URI when scoped storage is required, `File` otherwise) + // returns null if directory does not exist and could not be created + fun createDirectoryDocIfAbsent(context: Context, dirPath: String): DocumentFileCompat? { + try { + val targetDirPath = ensureTrailingSeparator(dirPath) + return if (requireAccessPermission(context, targetDirPath)) { + val grantedDir = getGrantedDirForPath(context, targetDirPath) ?: return null + val rootTreeDocumentUri = convertDirPathToTreeDocumentUri(context, grantedDir) ?: return null + var parentFile: DocumentFileCompat? = DocumentFileCompat.fromTreeUri(context, rootTreeDocumentUri) ?: return null + val pathIterator = getPathStepIterator(context, targetDirPath, grantedDir) + var currentDirPath = ensureTrailingSeparator(grantedDir) + while (pathIterator?.hasNext() == true) { + val dirName = pathIterator.next() + var treeDocFile = findDocumentFileIgnoreCase(parentFile, dirName) + currentDirPath = ensureTrailingSeparator(currentDirPath + dirName) + + if (treeDocFile == null && File(currentDirPath).exists()) { + // `DocumentsProvider` may be temporarily buggy and fail to list children directories. + // Better to fail fast and revoke directory access, so that the user is aware + // of the issue when trying again with `ACTION_OPEN_DOCUMENT_TREE`. + // Otherwise, we would try to recreate the existing (but unlisted) directory, + // and the document provider will create a new one with a "(1)" suffix. + Log.e(LOG_TAG, "failed to get document file for existing path=$currentDirPath from granted dir=$grantedDir. Revoking granted dir...") + PermissionManager.revokeDirectoryAccess(context, grantedDir) + throw Exception("failed to get document file for existing path=$currentDirPath from grantedDir=$grantedDir") + } + + if (treeDocFile == null || !treeDocFile.exists()) { + treeDocFile = parentFile?.createDirectory(dirName) + if (treeDocFile == null) { + Log.e(LOG_TAG, "failed to create directory with name=$dirName from parent=$parentFile") + return null + } + } + parentFile = treeDocFile + } + parentFile + } else { + val directory = File(targetDirPath) + directory.mkdirs() + if (!directory.exists()) { + Log.e(LOG_TAG, "failed to create directories at path=$targetDirPath") + return null + } + DocumentFileCompat.fromFile(directory) + } + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to create directory at path=$dirPath", e) + return null + } + } + + private fun getDocumentFileFromVolumeTree(context: Context, rootTreeDocumentUri: Uri, anyPath: String): DocumentFileCompat? { + var documentFile: DocumentFileCompat? = DocumentFileCompat.fromTreeUri(context, rootTreeDocumentUri) ?: return null + + // follow the entry path down the document tree + val pathIterator = getPathStepIterator(context, anyPath, null) + while (pathIterator?.hasNext() == true) { + documentFile = findDocumentFileIgnoreCase(documentFile, pathIterator.next()) ?: return null + } + return documentFile + } + + // variation on `DocumentFileCompat.findFile()` to allow case insensitive search + private fun findDocumentFileIgnoreCase(documentFile: DocumentFileCompat?, displayName: String?): DocumentFileCompat? { + documentFile ?: return null + for (doc in documentFile.listFiles()) { + if (displayName.equals(doc.name, ignoreCase = true)) { + return doc + } + } + return null + } + + /** + * Misc + */ + + fun canEditByFile(context: Context, path: String) = !requireAccessPermission(context, path) + + fun requireAccessPermission(context: Context, anyPath: String): Boolean { + if (isAppFile(context, anyPath)) return false + + // on Android 11, we should always require access permission, even on primary volume + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) return true + + val onPrimaryVolume = anyPath.startsWith(getPrimaryVolumePath(context)) + return !onPrimaryVolume + } + + fun isMediaStoreContentUri(uri: Uri?): Boolean { + uri ?: return false + // a URI's authority is [userinfo@]host[:port] + // but we only want the host when comparing to Media Store's "authority" + return SCHEME_CONTENT.equals(uri.scheme, ignoreCase = true) && MediaStore.AUTHORITY.equals(uri.host, ignoreCase = true) + } + + fun getOriginalUri(context: Context, uri: Uri): Uri { + // we get a permission denial if we require original from a provider other than the media store + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isMediaStoreContentUri(uri)) { + val path = uri.path + path ?: return uri + // from Android 11 (API 30), accessing the original URI for a `file` or `downloads` media content yields a `SecurityException` + if (path.startsWith(IMAGE_PATH_ROOT) || path.startsWith(VIDEO_PATH_ROOT)) { + // "Caller must hold ACCESS_MEDIA_LOCATION permission to access original" + if (context.checkSelfPermission(Manifest.permission.ACCESS_MEDIA_LOCATION) == PackageManager.PERMISSION_GRANTED) { + return MediaStore.setRequireOriginal(uri) + } + } + } + return uri + } + + // As of Glide v4.12.0, a special loader `QMediaStoreUriLoader` is automatically used + // to work around a bug from Android 10 (API 29) where metadata redaction corrupts HEIC images. + // This loader relies on `MediaStore.setRequireOriginal` but this yields a `SecurityException` + // for some non image/video content URIs (e.g. `downloads`, `file`) + fun getGlideSafeUri(context: Context, uri: Uri, mimeType: String, sizeBytes: Long? = null): Uri { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isMediaStoreContentUri(uri)) { + val uriPath = uri.path + when { + uriPath?.contains("/downloads/") == true -> { + // e.g. `content://media/external_primary/downloads/...` + getMediaUriImageVideoUri(uri, mimeType)?.let { imageVideoUri -> return imageVideoUri } + } + + uriPath?.contains("/file/") == true -> { + // e.g. `content://media/external/file/...` + // create an ad-hoc temporary file for decoding only + createTempFile(context).apply { + try { + transferFrom(openInputStream(context, uri), sizeBytes) + return Uri.fromFile(this) + } catch (e: Exception) { + Log.e(LOG_TAG, "failed to create temporary file from uri=$uri", e) + } + } + } + + uri.userInfo != null -> return stripMediaUriUserInfo(uri) + } + } + return uri + } + + // requesting access or writing to some MediaStore content URIs + // yields an exception with `All requested items must be referenced by specific ID` + fun getMediaStoreScopedStorageSafeUri(uri: Uri, mimeType: String): Uri { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isMediaStoreContentUri(uri)) { + val uriPath = uri.path + when { + uriPath?.contains("/downloads/") == true -> { + // e.g. `content://media/external_primary/downloads/...` + getMediaUriImageVideoUri(uri, mimeType)?.let { imageVideoUri -> return imageVideoUri } + } + + uri.userInfo != null -> return stripMediaUriUserInfo(uri) + } + } + return uri + } + + // Build a typical `images` or `video` content URI from the original content ID. + // We cannot safely apply this to a `file` content URI, as it may point to a file not indexed + // by the Media Store (via `.nomedia`), and therefore has no matching image/video content URI. + private fun getMediaUriImageVideoUri(uri: Uri, mimeType: String): Uri? { + return uri.tryParseId()?.let { id -> + return when { + isImage(mimeType) -> ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) + isVideo(mimeType) -> ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id) + else -> uri + } + } + } + + // strip user info, if any + // e.g. `content://0@media/...` + private fun stripMediaUriUserInfo(uri: Uri) = uri.toString().replaceFirst("${uri.userInfo}@", "").toUri() + + fun openInputStream(context: Context, uri: Uri): InputStream? { + val effectiveUri = getOriginalUri(context, uri) + return try { + return when (uri.scheme) { + ContentResolver.SCHEME_FILE -> FileInputStream(uri.path) + else -> context.contentResolver.openInputStream(effectiveUri) + } + } catch (e: Exception) { + // among various other exceptions, + // opening a file marked pending and owned by another package throws an `IllegalStateException` + Log.w(LOG_TAG, "failed to open input stream from effectiveUri=$effectiveUri for uri=$uri", e) + null + } + } + + fun openOutputStream(context: Context, mimeType: String, uri: Uri, mode: String): OutputStream? { + val effectiveUri = getMediaStoreScopedStorageSafeUri(uri, mimeType) + return try { + context.contentResolver.openOutputStream(effectiveUri, mode) + } catch (e: Exception) { + // among various other exceptions, + // opening a file marked pending and owned by another package throws an `IllegalStateException` + Log.w(LOG_TAG, "failed to open output stream from effectiveUri=$effectiveUri for uri=$uri mode=$mode", e) + null + } + } + + fun openInputFileDescriptor(context: Context, uri: Uri): ParcelFileDescriptor? { + val effectiveUri = getOriginalUri(context, uri) + return try { + context.contentResolver.openFileDescriptor(effectiveUri, "r") + } catch (e: Exception) { + // among various other exceptions, + // opening a file marked pending and owned by another package throws an `IllegalStateException` + Log.w(LOG_TAG, "failed to open input file descriptor from effectiveUri=$effectiveUri for uri=$uri", e) + null + } + } + + fun openOutputFileDescriptor(context: Context, mimeType: String, uri: Uri, path: String, mode: String): ParcelFileDescriptor? { + val effectiveUri = if (ImageProvider.isMediaUriPermissionGranted(context, uri, mimeType)) { + getMediaStoreScopedStorageSafeUri(uri, mimeType) + } else { + getDocumentFile(context, path, uri)?.uri ?: throw Exception("failed to get document file for path=$path, uri=$uri") + } + return try { + context.contentResolver.openFileDescriptor(effectiveUri, mode) + } catch (e: Exception) { + // among various other exceptions, + // opening a file marked pending and owned by another package throws an `IllegalStateException` + Log.w(LOG_TAG, "failed to open output file descriptor from effectiveUri=$effectiveUri for uri=$uri path=$path", e) + null + } + } + + fun openMetadataRetriever(context: Context, uri: Uri): MediaMetadataRetriever? { + val effectiveUri = getOriginalUri(context, uri) + return try { + MediaMetadataRetriever().apply { + // on Android 12 preview, setting the data source works but yields an internal IOException + // (`Input file descriptor already original`), whether we provide the original URI or not + setDataSource(context, effectiveUri) + } + } catch (_: Exception) { + // unsupported format + Log.w(LOG_TAG, "failed to initialize MediaMetadataRetriever for uri=$uri effectiveUri=$effectiveUri") + null + } + } + + private fun getTempDirectory(context: Context): File = File(context.cacheDir, "temp") + + fun createTempFile(context: Context, extension: String? = null): File { + val directory = getTempDirectory(context) + directory.mkdirs() + if (!directory.exists()) { + throw IOException("failed to create directories at path=$directory") + } + val tempFile = File.createTempFile("aves", extension, directory) + // `deleteOnExit` is unreliable, but it does not hurt + tempFile.deleteOnExit() + return tempFile + } + + fun deleteTempDirectory(context: Context): Boolean { + val directory = getTempDirectory(context) + if (!directory.exists()) return false + return directory.deleteRecursively() + } + + // convenience methods + + fun getFolderSize(f: File): Long { + var size: Long = 0 + if (f.isDirectory) { + for (file in f.listFiles()!!) { + size += getFolderSize(file) + } + } else { + size = f.length() + } + return size + } + + fun ensureTrailingSeparator(dirPath: String): String { + return if (dirPath.endsWith(File.separator)) dirPath else dirPath + File.separator + } + + fun removeTrailingSeparator(dirPath: String): String { + return if (dirPath.endsWith(File.separator)) dirPath.substring(0, dirPath.length - 1) else dirPath + } + + // `fullPath` should match "volumePath + relativeDir + fileName" + class PathSegments(context: Context, fullPath: String) { + var volumePath: String? = null // `volumePath` with trailing "/" + var relativeDir: String? = null // `relativeDir` with trailing "/" + private var fileName: String? = null // null for directories + + init { + volumePath = getVolumePath(context, fullPath) + if (volumePath != null) { + val lastSeparatorIndex = fullPath.lastIndexOf(File.separator) + 1 + val volumePathLength = volumePath!!.length + if (lastSeparatorIndex > volumePathLength) { + fileName = fullPath.substring(lastSeparatorIndex) + relativeDir = fullPath.substring(volumePathLength, lastSeparatorIndex) + } + } + } + } +}
\ No newline at end of file diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/UriUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/UriUtils.kt new file mode 100644 index 0000000..9e10927 --- /dev/null +++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/UriUtils.kt @@ -0,0 +1,18 @@ +package deckers.thibault.aves.utils + +import android.content.ContentUris +import android.net.Uri +import android.util.Log + +object UriUtils { + private val LOG_TAG = LogUtils.createTag<UriUtils>() + + fun Uri.tryParseId(): Long? { + try { + return ContentUris.parseId(this) + } catch (e: Exception) { + Log.w(LOG_TAG, "failed to parse ID from contentUri=$this") + } + return null + } +}
\ No newline at end of file diff --git a/android/app/src/main/res/drawable-nodpi/banner.png b/android/app/src/main/res/drawable-nodpi/banner.png Binary files differnew file mode 100644 index 0000000..ac4ec59 --- /dev/null +++ b/android/app/src/main/res/drawable-nodpi/banner.png diff --git a/android/app/src/main/res/drawable-v26/ic_shortcut_collection_foreground.xml b/android/app/src/main/res/drawable-v26/ic_shortcut_collection_foreground.xml new file mode 100644 index 0000000..13e0900 --- /dev/null +++ b/android/app/src/main/res/drawable-v26/ic_shortcut_collection_foreground.xml @@ -0,0 +1,16 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="108dp" + android:height="108dp" + android:tint="@color/ic_shortcut_foreground" + android:viewportWidth="108" + android:viewportHeight="108"> + <group + android:scaleX="1.7226" + android:scaleY="1.7226" + android:translateX="33.3288" + android:translateY="33.3288"> + <path + android:fillColor="@android:color/white" + android:pathData="M20,4v12L8,16L8,4h12m0,-2L8,2c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM11.5,11.67l1.69,2.26 2.48,-3.1L19,15L9,15zM2,6v14c0,1.1 0.9,2 2,2h14v-2L4,20L4,6L2,6z" /> + </group> +</vector> diff --git a/android/app/src/main/res/drawable-v26/ic_shortcut_movie_foreground.xml b/android/app/src/main/res/drawable-v26/ic_shortcut_movie_foreground.xml new file mode 100644 index 0000000..84db2f5 --- /dev/null +++ b/android/app/src/main/res/drawable-v26/ic_shortcut_movie_foreground.xml @@ -0,0 +1,16 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="108dp" + android:height="108dp" + android:tint="@color/ic_shortcut_foreground" + android:viewportWidth="108" + android:viewportHeight="108"> + <group + android:scaleX="1.7226" + android:scaleY="1.7226" + android:translateX="33.3288" + android:translateY="33.3288"> + <path + android:fillColor="@android:color/white" + android:pathData="M4,6.47L5.76,10H20v8H4V6.47M22,4h-4l2,4h-3l-2,-4h-2l2,4h-3l-2,-4H8l2,4H7L5,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V4z" /> + </group> +</vector> diff --git a/android/app/src/main/res/drawable-v26/ic_shortcut_search_foreground.xml b/android/app/src/main/res/drawable-v26/ic_shortcut_search_foreground.xml new file mode 100644 index 0000000..13f7071 --- /dev/null +++ b/android/app/src/main/res/drawable-v26/ic_shortcut_search_foreground.xml @@ -0,0 +1,16 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="108dp" + android:height="108dp" + android:tint="@color/ic_shortcut_foreground" + android:viewportWidth="108" + android:viewportHeight="108"> + <group + android:scaleX="1.7226" + android:scaleY="1.7226" + android:translateX="33.3288" + android:translateY="33.3288"> + <path + android:fillColor="@android:color/white" + android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z" /> + </group> +</vector> diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..4155b35 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,38 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="100dp" + android:height="100dp" + android:viewportWidth="100" + android:viewportHeight="100"> + <path + android:fillColor="#ef435a" + android:fillType="evenOdd" + android:pathData="m41.03,57.12 l8.31,8.31a1.47,1.47 0,0 1,0 2.08l-3.97,3.97a7.6,7.6 0,0 1,-10.75 0l-3.97,-3.97a1.47,1.47 0,0 1,0 -2.08l8.31,-8.31a1.47,1.47 0,0 1,2.08 0z" + android:strokeWidth="1.53903" + android:strokeColor="#000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="#e0e0e0" + android:fillType="evenOdd" + android:pathData="m53.43,44.71 l8.31,8.31a1.46,1.46 0,0 1,-0 2.08l-8.31,8.31a1.46,1.46 0,0 1,-2.08 0l-8.31,-8.31a1.46,1.46 0,0 1,0 -2.08l8.31,-8.31a1.46,1.46 0,0 1,2.08 0z" + android:strokeWidth="1.53902" + android:strokeColor="#000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="#ffc11f" + android:fillType="evenOdd" + android:pathData="m55.45,40.62a1.47,1.47 0,0 0,0 2.08l8.31,8.31a1.47,1.47 0,0 0,2.08 0l8.31,-8.31a1.47,1.47 0,0 0,0 -2.08l-4.12,-4.12a7.39,7.39 0,0 0,-10.44 0zM63.65,40.51a1.62,1.62 0,0 1,2.29 0,1.62 1.62,0 0,1 0,2.29 1.62,1.62 0,0 1,-2.29 0,1.62 1.62,0 0,1 0,-2.29z" + android:strokeWidth="1.53902" + android:strokeColor="#000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="@color/ic_launcher_flavour" + android:fillType="evenOdd" + android:pathData="m37.26,28.54 l12.13,12.13a1.47,1.47 0,0 1,0 2.08l-8.31,8.31a1.47,1.47 0,0 1,-2.08 0l-5.39,-5.39a11.47,11.47 0,0 1,0 -16.22l0.9,-0.9a1.94,1.94 0,0 1,2.74 0z" + android:strokeWidth="1.53903" + android:strokeColor="#000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> +</vector> diff --git a/android/app/src/main/res/drawable/ic_launcher_mono.xml b/android/app/src/main/res/drawable/ic_launcher_mono.xml new file mode 100644 index 0000000..9f78191 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_mono.xml @@ -0,0 +1,38 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="100dp" + android:height="100dp" + android:viewportWidth="100" + android:viewportHeight="100"> + <path + android:fillColor="#000000" + android:fillType="evenOdd" + android:pathData="m41.03,57.12 l8.31,8.31a1.47,1.47 0,0 1,0 2.08l-3.97,3.97a7.6,7.6 0,0 1,-10.75 0l-3.97,-3.97a1.47,1.47 0,0 1,0 -2.08l8.3,-8.3a1.47,1.47 0,0 1,2.08 0z" + android:strokeWidth="1.53871" + android:strokeColor="#00000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="#000000" + android:fillType="evenOdd" + android:pathData="m53.43,44.72 l8.31,8.31a1.46,1.46 0,0 1,-0 2.08l-8.31,8.31a1.46,1.46 0,0 1,-2.08 0l-8.31,-8.31a1.46,1.46 0,0 1,0 -2.08L51.35,44.72a1.46,1.46 0,0 1,2.08 0z" + android:strokeWidth="1.5387" + android:strokeColor="#00000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="#000000" + android:fillType="evenOdd" + android:pathData="m55.45,40.62a1.47,1.47 0,0 0,0 2.08l8.31,8.3a1.47,1.47 0,0 0,2.08 0l8.3,-8.3a1.47,1.47 0,0 0,0 -2.08l-4.12,-4.12a7.38,7.38 0,0 0,-10.44 0zM63.65,40.51a1.62,1.62 0,0 1,2.29 0,1.62 1.62,0 0,1 0,2.29 1.62,1.62 0,0 1,-2.29 0,1.62 1.62,0 0,1 0,-2.29z" + android:strokeWidth="1.5387" + android:strokeColor="#00000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="#000000" + android:fillType="evenOdd" + android:pathData="m37.26,28.54 l12.13,12.13a1.47,1.47 0,0 1,0 2.08l-8.31,8.3a1.47,1.47 0,0 1,-2.08 0L33.62,45.67a11.47,11.47 0,0 1,0 -16.22l0.9,-0.9a1.94,1.94 0,0 1,2.74 0z" + android:strokeWidth="1.53871" + android:strokeColor="#00000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> +</vector> diff --git a/android/app/src/main/res/drawable/ic_notification.xml b/android/app/src/main/res/drawable/ic_notification.xml new file mode 100644 index 0000000..480be0b --- /dev/null +++ b/android/app/src/main/res/drawable/ic_notification.xml @@ -0,0 +1,38 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="100dp" + android:height="100dp" + android:viewportWidth="100" + android:viewportHeight="100"> + <path + android:fillColor="#000000" + android:fillType="evenOdd" + android:pathData="m31.78,63.61 l16.47,16.47a2.91,2.91 0,0 1,0 4.12l-7.87,7.87a15.07,15.07 0,0 1,-21.31 0L11.2,84.2a2.91,2.91 0,0 1,0 -4.12l16.47,-16.47a2.91,2.91 0,0 1,4.12 0z" + android:strokeWidth="3.05097" + android:strokeColor="#00000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="#000000" + android:fillType="evenOdd" + android:pathData="M56.37,39.03L72.84,55.49A2.91,2.91 90,0 1,72.84 59.61L56.37,76.08A2.91,2.91 0,0 1,52.25 76.08L35.78,59.61A2.91,2.91 0,0 1,35.78 55.49L52.25,39.03A2.91,2.91 90,0 1,56.37 39.03z" + android:strokeWidth="3.05095" + android:strokeColor="#00000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="#000000" + android:fillType="evenOdd" + android:pathData="m60.37,30.91a2.91,2.91 0,0 0,0 4.12l16.47,16.47a2.91,2.91 0,0 0,4.12 0l16.47,-16.47a2.91,2.91 0,0 0,0 -4.12l-8.17,-8.17a14.64,14.64 0,0 0,-20.7 0zM76.62,30.7a3.21,3.21 0,0 1,4.54 0,3.21 3.21,0 0,1 0,4.54 3.21,3.21 0,0 1,-4.54 0,3.21 3.21,0 0,1 0,-4.54z" + android:strokeWidth="3.05095" + android:strokeColor="#00000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> + <path + android:fillColor="#000000" + android:fillType="evenOdd" + android:pathData="m24.31,6.96 l24.04,24.04a2.91,2.91 0,0 1,0 4.12L31.88,51.59a2.91,2.91 0,0 1,-4.12 0L17.08,40.91a22.74,22.74 0,0 1,0 -32.16L18.87,6.96a3.84,3.84 0,0 1,5.43 0z" + android:strokeWidth="3.05097" + android:strokeColor="#00000000" + android:strokeLineCap="round" + android:strokeLineJoin="round" /> +</vector> diff --git a/android/app/src/main/res/drawable/ic_outline_stop_24.xml b/android/app/src/main/res/drawable/ic_outline_stop_24.xml new file mode 100644 index 0000000..0214f12 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_outline_stop_24.xml @@ -0,0 +1,9 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <path + android:fillColor="@android:color/white" + android:pathData="M16,8v8H8V8h8m2,-2H6v12h12V6z"/> +</vector> diff --git a/android/app/src/main/res/drawable/ic_shortcut_collection.xml b/android/app/src/main/res/drawable/ic_shortcut_collection.xml new file mode 100644 index 0000000..f20e57d --- /dev/null +++ b/android/app/src/main/res/drawable/ic_shortcut_collection.xml @@ -0,0 +1,16 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="48dp" + android:height="48dp" + android:viewportWidth="48" + android:viewportHeight="48"> + <path + android:fillColor="@color/ic_shortcut_background" + android:pathData="M0,24 A1,1 0 1,1 48,24 A1,1 0 1,1 0,24" /> + <group + android:translateX="12" + android:translateY="12"> + <path + android:fillColor="@color/ic_shortcut_foreground" + android:pathData="M20,4v12L8,16L8,4h12m0,-2L8,2c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM11.5,11.67l1.69,2.26 2.48,-3.1L19,15L9,15zM2,6v14c0,1.1 0.9,2 2,2h14v-2L4,20L4,6L2,6z" /> + </group> +</vector> diff --git a/android/app/src/main/res/drawable/ic_shortcut_map.xml b/android/app/src/main/res/drawable/ic_shortcut_map.xml new file mode 100644 index 0000000..7dc10d1 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_shortcut_map.xml @@ -0,0 +1,16 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="48dp" + android:height="48dp" + android:viewportWidth="48" + android:viewportHeight="48"> + <path + android:fillColor="@color/ic_shortcut_background" + android:pathData="M0,24 A1,1 0 1,1 48,24 A1,1 0 1,1 0,24" /> + <group + android:translateX="12" + android:translateY="12"> + <path + android:fillColor="@color/ic_shortcut_foreground" + android:pathData="M20.5,3l-0.16,0.03L15,5.1 9,3 3.36,4.9c-0.21,0.07 -0.36,0.25 -0.36,0.48L3,20.5c0,0.28 0.22,0.5 0.5,0.5l0.16,-0.03L9,18.9l6,2.1 5.64,-1.9c0.21,-0.07 0.36,-0.25 0.36,-0.48L21,3.5c0,-0.28 -0.22,-0.5 -0.5,-0.5zM10,5.47l4,1.4v11.66l-4,-1.4L10,5.47zM5,6.46l3,-1.01v11.7l-3,1.16L5,6.46zM19,17.54l-3,1.01L16,6.86l3,-1.16v11.84z" /> + </group> +</vector> diff --git a/android/app/src/main/res/drawable/ic_shortcut_map_foreground.xml b/android/app/src/main/res/drawable/ic_shortcut_map_foreground.xml new file mode 100644 index 0000000..d450c31 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_shortcut_map_foreground.xml @@ -0,0 +1,16 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="108dp" + android:height="108dp" + android:tint="@color/ic_shortcut_foreground" + android:viewportWidth="108" + android:viewportHeight="108"> + <group + android:scaleX="1.7226" + android:scaleY="1.7226" + android:translateX="33.3288" + android:translateY="33.3288"> + <path + android:fillColor="@android:color/white" + android:pathData="M20.5,3l-0.16,0.03L15,5.1 9,3 3.36,4.9c-0.21,0.07 -0.36,0.25 -0.36,0.48L3,20.5c0,0.28 0.22,0.5 0.5,0.5l0.16,-0.03L9,18.9l6,2.1 5.64,-1.9c0.21,-0.07 0.36,-0.25 0.36,-0.48L21,3.5c0,-0.28 -0.22,-0.5 -0.5,-0.5zM10,5.47l4,1.4v11.66l-4,-1.4L10,5.47zM5,6.46l3,-1.01v11.7l-3,1.16L5,6.46zM19,17.54l-3,1.01L16,6.86l3,-1.16v11.84z" /> + </group> +</vector> diff --git a/android/app/src/main/res/drawable/ic_shortcut_movie.xml b/android/app/src/main/res/drawable/ic_shortcut_movie.xml new file mode 100644 index 0000000..c69c379 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_shortcut_movie.xml @@ -0,0 +1,16 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="48dp" + android:height="48dp" + android:viewportWidth="48" + android:viewportHeight="48"> + <path + android:fillColor="@color/ic_shortcut_background" + android:pathData="M0,24 A1,1 0 1,1 48,24 A1,1 0 1,1 0,24" /> + <group + android:translateX="12" + android:translateY="12"> + <path + android:fillColor="@color/ic_shortcut_foreground" + android:pathData="M4,6.47L5.76,10H20v8H4V6.47M22,4h-4l2,4h-3l-2,-4h-2l2,4h-3l-2,-4H8l2,4H7L5,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V4z" /> + </group> +</vector> diff --git a/android/app/src/main/res/drawable/ic_shortcut_search.xml b/android/app/src/main/res/drawable/ic_shortcut_search.xml new file mode 100644 index 0000000..f28c549 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_shortcut_search.xml @@ -0,0 +1,16 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="48dp" + android:height="48dp" + android:viewportWidth="48" + android:viewportHeight="48"> + <path + android:fillColor="@color/ic_shortcut_background" + android:pathData="M0,24 A1,1 0 1,1 48,24 A1,1 0 1,1 0,24" /> + <group + android:translateX="12" + android:translateY="12"> + <path + android:fillColor="@color/ic_shortcut_foreground" + android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z" /> + </group> +</vector> diff --git a/android/app/src/main/res/layout/app_widget.xml b/android/app/src/main/res/layout/app_widget.xml new file mode 100644 index 0000000..b4a2c16 --- /dev/null +++ b/android/app/src/main/res/layout/app_widget.xml @@ -0,0 +1,5 @@ +<ImageView xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/widget_img" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:scaleType="fitCenter" /> diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..fe5fad3 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@color/ic_launcher_background"/> + <foreground android:drawable="@drawable/ic_launcher_foreground"/> + <monochrome android:drawable="@drawable/ic_launcher_mono" /> +</adaptive-icon>
\ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..fe5fad3 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@color/ic_launcher_background"/> + <foreground android:drawable="@drawable/ic_launcher_foreground"/> + <monochrome android:drawable="@drawable/ic_launcher_mono" /> +</adaptive-icon>
\ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_collection.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_collection.xml new file mode 100644 index 0000000..8ec076f --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_collection.xml @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@color/ic_shortcut_background" /> + <foreground android:drawable="@drawable/ic_shortcut_collection_foreground" /> +</adaptive-icon>
\ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_map.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_map.xml new file mode 100644 index 0000000..2857b49 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_map.xml @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@color/ic_shortcut_background" /> + <foreground android:drawable="@drawable/ic_shortcut_map_foreground" /> +</adaptive-icon>
\ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_movie.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_movie.xml new file mode 100644 index 0000000..8789ba0 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_movie.xml @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@color/ic_shortcut_background" /> + <foreground android:drawable="@drawable/ic_shortcut_movie_foreground" /> +</adaptive-icon>
\ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_search.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_search.xml new file mode 100644 index 0000000..ab1fb94 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_search.xml @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@color/ic_shortcut_background" /> + <foreground android:drawable="@drawable/ic_shortcut_search_foreground" /> +</adaptive-icon>
\ No newline at end of file diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..7c532b7 --- /dev/null +++ b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png Binary files differnew file mode 100644 index 0000000..7407041 --- /dev/null +++ b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..f9bbc54 --- /dev/null +++ b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png Binary files differnew file mode 100644 index 0000000..c31695e --- /dev/null +++ b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..e3491da --- /dev/null +++ b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png Binary files differnew file mode 100644 index 0000000..8e5ee2b --- /dev/null +++ b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..51adec0 --- /dev/null +++ b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png Binary files differnew file mode 100644 index 0000000..b11aeb8 --- /dev/null +++ b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..8da583b --- /dev/null +++ b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png Binary files differnew file mode 100644 index 0000000..8b7999b --- /dev/null +++ b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png diff --git a/android/app/src/main/res/values-ar/strings.xml b/android/app/src/main/res/values-ar/strings.xml new file mode 100644 index 0000000..478e4f4 --- /dev/null +++ b/android/app/src/main/res/values-ar/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_widget_label">إطار الصورة</string> + <string name="wallpaper">الخلفية</string> + <string name="search_shortcut_short_label">البحث</string> + <string name="videos_shortcut_short_label">الفيديوهات</string> + <string name="analysis_channel_name">فحص الوسائط</string> + <string name="analysis_notification_default_title">يتم فحص الوسائط</string> + <string name="analysis_notification_action_stop">إيقاف</string> + <string name="app_name">Aves</string> + <string name="map_shortcut_short_label">خريطة</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-az/strings.xml b/android/app/src/main/res/values-az/strings.xml new file mode 100644 index 0000000..31f1b1c --- /dev/null +++ b/android/app/src/main/res/values-az/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Şəkil Çərçivəsi</string> + <string name="wallpaper">Divar kağızı</string> + <string name="map_shortcut_short_label">Xəritə</string> + <string name="search_shortcut_short_label">Axtarış</string> + <string name="videos_shortcut_short_label">Videolar</string> + <string name="analysis_channel_name">Medianı yoxla</string> + <string name="analysis_notification_default_title">Media yoxlanılır</string> + <string name="analysis_notification_action_stop">Dayandır</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-b+zxx+Shaw/strings.xml b/android/app/src/main/res/values-b+zxx+Shaw/strings.xml new file mode 100644 index 0000000..f7bb920 --- /dev/null +++ b/android/app/src/main/res/values-b+zxx+Shaw/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">𐑱𐑝𐑰𐑟</string> + <string name="app_widget_label">𐑓𐑴𐑑𐑴 𐑓𐑮𐑱𐑥</string> + <string name="wallpaper">𐑢𐑷𐑤𐑐𐑱𐑐𐑼</string> + <string name="map_shortcut_short_label">𐑥𐑨𐑐</string> + <string name="search_shortcut_short_label">𐑕𐑻𐑗</string> + <string name="videos_shortcut_short_label">𐑝𐑦𐑛𐑦𐑴𐑟</string> + <string name="analysis_channel_name">𐑥𐑰𐑛𐑾 𐑕𐑒𐑨𐑯</string> + <string name="analysis_notification_default_title">𐑕𐑒𐑨𐑯𐑦𐑙 𐑥𐑰𐑛𐑾</string> + <string name="analysis_notification_action_stop">𐑕𐑑𐑪𐑐</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-be/strings.xml b/android/app/src/main/res/values-be/strings.xml new file mode 100644 index 0000000..cf307df --- /dev/null +++ b/android/app/src/main/res/values-be/strings.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="analysis_channel_name">Сканаванне носьбітаў</string> + <string name="videos_shortcut_short_label">Відэа</string> + <string name="wallpaper">Шпалеры</string> + <string name="analysis_notification_default_title">Сканаванне носьбітаў</string> + <string name="app_name">Aves</string> + <string name="app_widget_label">Фотарамка</string> + <string name="search_shortcut_short_label">Пошук</string> + <string name="analysis_notification_action_stop">Стоп</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-bg/strings.xml b/android/app/src/main/res/values-bg/strings.xml new file mode 100644 index 0000000..d33ecff --- /dev/null +++ b/android/app/src/main/res/values-bg/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Фоторамка</string> + <string name="wallpaper">Тапет</string> + <string name="map_shortcut_short_label">Карта</string> + <string name="search_shortcut_short_label">Търсене</string> + <string name="analysis_channel_name">Сканиране медия</string> + <string name="analysis_notification_default_title">Сканиране медия</string> + <string name="analysis_notification_action_stop">Стоп</string> + <string name="videos_shortcut_short_label">Видео</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-bn/strings.xml b/android/app/src/main/res/values-bn/strings.xml new file mode 100644 index 0000000..936f4ce --- /dev/null +++ b/android/app/src/main/res/values-bn/strings.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="wallpaper">ওয়ালপেপার</string> + <string name="search_shortcut_short_label">সার্চ</string> + <string name="videos_shortcut_short_label">ভিডিও</string> + <string name="analysis_notification_default_title">মিডিয়া সন্ধান চলছে</string> + <string name="analysis_channel_name">মিডিয়া সন্ধান</string> + <string name="analysis_notification_action_stop">থামান</string> + <string name="app_name">আভেস</string> + <string name="app_widget_label">ছবির ফ্রেম</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-ca/strings.xml b/android/app/src/main/res/values-ca/strings.xml new file mode 100644 index 0000000..1146f3a --- /dev/null +++ b/android/app/src/main/res/values-ca/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Marc de foto</string> + <string name="wallpaper">Fons de pantalla</string> + <string name="search_shortcut_short_label">Buscar</string> + <string name="videos_shortcut_short_label">Vídeos</string> + <string name="analysis_channel_name">Exploració de mitjans</string> + <string name="analysis_notification_default_title">Explorant mitjans</string> + <string name="analysis_notification_action_stop">Atura</string> + <string name="map_shortcut_short_label">Mapa</string> +</resources> diff --git a/android/app/src/main/res/values-ckb/strings.xml b/android/app/src/main/res/values-ckb/strings.xml new file mode 100644 index 0000000..65b05be --- /dev/null +++ b/android/app/src/main/res/values-ckb/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">ئاڤێس</string> + <string name="app_widget_label">قەراغی وێنە</string> + <string name="wallpaper">پاشبنەما</string> + <string name="search_shortcut_short_label">گەڕان</string> + <string name="videos_shortcut_short_label">ڤیدیۆ</string> + <string name="analysis_channel_name">گەڕان لە ڕەنگاڵە</string> + <string name="analysis_notification_default_title">لە ڕەنگاڵەکان دەگەڕێت</string> + <string name="analysis_notification_action_stop">وەستاندن</string> + <string name="map_shortcut_short_label">نەخشە</string> +</resources> diff --git a/android/app/src/main/res/values-cs/strings.xml b/android/app/src/main/res/values-cs/strings.xml new file mode 100644 index 0000000..af729a9 --- /dev/null +++ b/android/app/src/main/res/values-cs/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="wallpaper">Tapeta</string> + <string name="search_shortcut_short_label">Hledat</string> + <string name="videos_shortcut_short_label">Videa</string> + <string name="analysis_channel_name">Prohledat média</string> + <string name="analysis_notification_default_title">Prohledávání médií</string> + <string name="analysis_notification_action_stop">Zastavit</string> + <string name="app_widget_label">Fotorámeček</string> + <string name="map_shortcut_short_label">Mapa</string> +</resources> diff --git a/android/app/src/main/res/values-da/strings.xml b/android/app/src/main/res/values-da/strings.xml new file mode 100644 index 0000000..f475147 --- /dev/null +++ b/android/app/src/main/res/values-da/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_widget_label">Fotoramme</string> + <string name="wallpaper">Baggrund</string> + <string name="videos_shortcut_short_label">Videoer</string> + <string name="analysis_channel_name">Mediescanning</string> + <string name="analysis_notification_default_title">Scanner medier</string> + <string name="analysis_notification_action_stop">Stop</string> + <string name="app_name">Aves</string> + <string name="search_shortcut_short_label">Søg</string> + <string name="map_shortcut_short_label">Kort</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml new file mode 100644 index 0000000..2c7396d --- /dev/null +++ b/android/app/src/main/res/values-de/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Bilderrahmen</string> + <string name="wallpaper">Hintergrundbild</string> + <string name="search_shortcut_short_label">Suche</string> + <string name="videos_shortcut_short_label">Videos</string> + <string name="analysis_channel_name">Analyse von Medien</string> + <string name="analysis_notification_default_title">Medien scannen</string> + <string name="analysis_notification_action_stop">Abbrechen</string> + <string name="map_shortcut_short_label">Karte</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-el/strings.xml b/android/app/src/main/res/values-el/strings.xml new file mode 100644 index 0000000..77d0d3a --- /dev/null +++ b/android/app/src/main/res/values-el/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Κορνίζα</string> + <string name="wallpaper">Ταπετσαρία</string> + <string name="search_shortcut_short_label">Αναζήτηση</string> + <string name="videos_shortcut_short_label">Βίντεο</string> + <string name="analysis_channel_name">Σάρωση πολυμέσων</string> + <string name="analysis_notification_default_title">Σάρωση στοιχείων</string> + <string name="analysis_notification_action_stop">Διακοπή</string> + <string name="map_shortcut_short_label">Χάρτης</string> +</resources> diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml new file mode 100644 index 0000000..6cc0b28 --- /dev/null +++ b/android/app/src/main/res/values-es/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Marco de foto</string> + <string name="wallpaper">Fondo de pantalla</string> + <string name="search_shortcut_short_label">Buscar</string> + <string name="videos_shortcut_short_label">Vídeos</string> + <string name="analysis_channel_name">Explorar medios</string> + <string name="analysis_notification_default_title">Explorando medios</string> + <string name="analysis_notification_action_stop">Anular</string> + <string name="map_shortcut_short_label">Mapa</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-et/strings.xml b/android/app/src/main/res/values-et/strings.xml new file mode 100644 index 0000000..b596c8b --- /dev/null +++ b/android/app/src/main/res/values-et/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Fotoraam</string> + <string name="wallpaper">Taustapilt</string> + <string name="map_shortcut_short_label">Kaart</string> + <string name="search_shortcut_short_label">Otsi</string> + <string name="videos_shortcut_short_label">Videod</string> + <string name="analysis_channel_name">Meedia tuvastamine</string> + <string name="analysis_notification_default_title">Tuvastame meediat</string> + <string name="analysis_notification_action_stop">Peata</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-eu/strings.xml b/android/app/src/main/res/values-eu/strings.xml new file mode 100644 index 0000000..c8e57d8 --- /dev/null +++ b/android/app/src/main/res/values-eu/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="search_shortcut_short_label">Bilatu</string> + <string name="videos_shortcut_short_label">Bideoak</string> + <string name="app_widget_label">Argazki-markoa</string> + <string name="wallpaper">Horma-papera</string> + <string name="analysis_channel_name">Media eskaneatu</string> + <string name="analysis_notification_action_stop">Gelditu</string> + <string name="analysis_notification_default_title">Media eskaneatzen</string> + <string name="app_name">Aves</string> + <string name="map_shortcut_short_label">Mapa</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-fa/strings.xml b/android/app/src/main/res/values-fa/strings.xml new file mode 100644 index 0000000..aa8d9ee --- /dev/null +++ b/android/app/src/main/res/values-fa/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="videos_shortcut_short_label">ویدئو ها</string> + <string name="analysis_channel_name">کنکاش رسانه</string> + <string name="search_shortcut_short_label">جستجو</string> + <string name="wallpaper">کاغذدیواری</string> + <string name="analysis_notification_default_title">در حال کنکاش رسانهها</string> + <string name="analysis_notification_action_stop">توقف کردن</string> + <string name="app_widget_label">قاب عکس</string> + <string name="app_name">Aves</string> + <string name="map_shortcut_short_label">نقشه</string> +</resources> diff --git a/android/app/src/main/res/values-fi/strings.xml b/android/app/src/main/res/values-fi/strings.xml new file mode 100644 index 0000000..9d7d1f8 --- /dev/null +++ b/android/app/src/main/res/values-fi/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="analysis_notification_action_stop">Lopeta</string> + <string name="app_widget_label">Valokuvakehys</string> + <string name="analysis_notification_default_title">Mediaa skannataan</string> + <string name="videos_shortcut_short_label">Videot</string> + <string name="wallpaper">Taustakuva</string> + <string name="app_name">Aves</string> + <string name="analysis_channel_name">Median skannaus</string> + <string name="search_shortcut_short_label">Hae</string> + <string name="map_shortcut_short_label">Kartta</string> +</resources> diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml new file mode 100644 index 0000000..159a984 --- /dev/null +++ b/android/app/src/main/res/values-fr/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Cadre photo</string> + <string name="wallpaper">Fond d’écran</string> + <string name="search_shortcut_short_label">Recherche</string> + <string name="videos_shortcut_short_label">Vidéos</string> + <string name="analysis_channel_name">Analyse des images</string> + <string name="analysis_notification_default_title">Analyse des images</string> + <string name="analysis_notification_action_stop">Annuler</string> + <string name="map_shortcut_short_label">Carte</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-gl/strings.xml b/android/app/src/main/res/values-gl/strings.xml new file mode 100644 index 0000000..a90ab7c --- /dev/null +++ b/android/app/src/main/res/values-gl/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Marco de fotos</string> + <string name="wallpaper">Fondo da pantalla</string> + <string name="search_shortcut_short_label">Procura</string> + <string name="videos_shortcut_short_label">Vídeos</string> + <string name="analysis_channel_name">Escanear medios</string> + <string name="analysis_notification_default_title">Escaneando medios</string> + <string name="analysis_notification_action_stop">Pare</string> + <string name="map_shortcut_short_label">Mapa</string> +</resources> diff --git a/android/app/src/main/res/values-hi/strings.xml b/android/app/src/main/res/values-hi/strings.xml new file mode 100644 index 0000000..9b6676a --- /dev/null +++ b/android/app/src/main/res/values-hi/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="analysis_notification_default_title">मीडिया जाँचा जा राहा है</string> + <string name="analysis_notification_action_stop">रोके</string> + <string name="app_widget_label">फोटो फ्रेम</string> + <string name="wallpaper">वॉलपेपर</string> + <string name="search_shortcut_short_label">खोजें</string> + <string name="analysis_channel_name">मीडिया जाँचे</string> + <string name="app_name">ऐवीज</string> + <string name="videos_shortcut_short_label">वीडियो</string> + <string name="map_shortcut_short_label">मैप</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-hu/strings.xml b/android/app/src/main/res/values-hu/strings.xml new file mode 100644 index 0000000..a8da148 --- /dev/null +++ b/android/app/src/main/res/values-hu/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="wallpaper">Háttérkép</string> + <string name="search_shortcut_short_label">Keresés</string> + <string name="videos_shortcut_short_label">Videók</string> + <string name="analysis_notification_action_stop">Állj</string> + <string name="app_widget_label">Fotó keret</string> + <string name="analysis_channel_name">Médiafájlok keresése</string> + <string name="analysis_notification_default_title">Média beolvasása</string> + <string name="map_shortcut_short_label">Térkép</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-id/strings.xml b/android/app/src/main/res/values-id/strings.xml new file mode 100644 index 0000000..13708b5 --- /dev/null +++ b/android/app/src/main/res/values-id/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Bingkai Foto</string> + <string name="wallpaper">Wallpaper</string> + <string name="search_shortcut_short_label">Cari</string> + <string name="videos_shortcut_short_label">Video</string> + <string name="analysis_channel_name">Pindai media</string> + <string name="analysis_notification_default_title">Memindai media</string> + <string name="analysis_notification_action_stop">Berhenti</string> + <string name="map_shortcut_short_label">Peta</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-is/strings.xml b/android/app/src/main/res/values-is/strings.xml new file mode 100644 index 0000000..d188a9d --- /dev/null +++ b/android/app/src/main/res/values-is/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="analysis_notification_action_stop">Stöðva</string> + <string name="app_widget_label">Myndarammi</string> + <string name="analysis_notification_default_title">Skanna myndefni</string> + <string name="videos_shortcut_short_label">Myndskeið</string> + <string name="wallpaper">Bakgrunnur</string> + <string name="app_name">Aves</string> + <string name="analysis_channel_name">Skönnun myndefnis</string> + <string name="search_shortcut_short_label">Leita</string> + <string name="map_shortcut_short_label">Landakort</string> +</resources> diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml new file mode 100644 index 0000000..519f158 --- /dev/null +++ b/android/app/src/main/res/values-it/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Cornice foto</string> + <string name="wallpaper">Sfondo</string> + <string name="search_shortcut_short_label">Ricerca</string> + <string name="videos_shortcut_short_label">Video</string> + <string name="analysis_channel_name">Scansione media</string> + <string name="analysis_notification_default_title">Scansione in corso</string> + <string name="analysis_notification_action_stop">Annulla</string> + <string name="map_shortcut_short_label">Mappa</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-iw/strings.xml b/android/app/src/main/res/values-iw/strings.xml new file mode 100644 index 0000000..fc8b10d --- /dev/null +++ b/android/app/src/main/res/values-iw/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">מסגרת תמונה</string> + <string name="wallpaper">טפט</string> + <string name="search_shortcut_short_label">חיפוש</string> + <string name="videos_shortcut_short_label">סרטים</string> + <string name="analysis_channel_name">סריקת מדיה</string> + <string name="analysis_notification_default_title">סורק מדיה</string> + <string name="analysis_notification_action_stop">הפסק</string> + <string name="map_shortcut_short_label">מפה</string> +</resources> diff --git a/android/app/src/main/res/values-ja/strings.xml b/android/app/src/main/res/values-ja/strings.xml new file mode 100644 index 0000000..cf16df9 --- /dev/null +++ b/android/app/src/main/res/values-ja/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">フォトフレーム</string> + <string name="wallpaper">壁紙</string> + <string name="search_shortcut_short_label">検索</string> + <string name="videos_shortcut_short_label">動画</string> + <string name="analysis_channel_name">メディアスキャン</string> + <string name="analysis_notification_default_title">メディアをスキャン中</string> + <string name="analysis_notification_action_stop">停止</string> + <string name="map_shortcut_short_label">マップ</string> +</resources> diff --git a/android/app/src/main/res/values-kmr/strings.xml b/android/app/src/main/res/values-kmr/strings.xml new file mode 100644 index 0000000..d9d18d8 --- /dev/null +++ b/android/app/src/main/res/values-kmr/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Çarçoveya wêneyê</string> + <string name="wallpaper">Paşrû</string> + <string name="map_shortcut_short_label">Nexşe</string> + <string name="search_shortcut_short_label">Bigere</string> + <string name="videos_shortcut_short_label">Vîdyo</string> + <string name="analysis_channel_name">Dîtina medya</string> + <string name="analysis_notification_default_title">Medya tê dîtin</string> + <string name="analysis_notification_action_stop">Rawestîne</string> +</resources> diff --git a/android/app/src/main/res/values-kn/strings.xml b/android/app/src/main/res/values-kn/strings.xml new file mode 100644 index 0000000..c4900bd --- /dev/null +++ b/android/app/src/main/res/values-kn/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">ಎವೀಸ್</string> + <string name="app_widget_label">ಫೋಟೋ ಫ್ರೇಮ್</string> + <string name="wallpaper">ವಾಲ್ಪೇಪರ್</string> + <string name="videos_shortcut_short_label">ವೀಡಿಯೊಗಳು</string> + <string name="analysis_channel_name">ಮೀಡಿಯಾ ಸ್ಕ್ಯಾನ್</string> + <string name="analysis_notification_default_title">ಮೀಡಿಯಾ ಸ್ಕ್ಯಾನ್ ಮಾಡಲಾಗುತ್ತಿದೆ</string> + <string name="analysis_notification_action_stop">ನಿಲ್ಲಿಸಿ</string> + <string name="search_shortcut_short_label">ಹುಡುಕಿ</string> + <string name="map_shortcut_short_label">ನಕ್ಷೆ</string> +</resources> diff --git a/android/app/src/main/res/values-ko/strings.xml b/android/app/src/main/res/values-ko/strings.xml new file mode 100644 index 0000000..207fcda --- /dev/null +++ b/android/app/src/main/res/values-ko/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">아베스</string> + <string name="app_widget_label">사진 액자</string> + <string name="wallpaper">배경화면</string> + <string name="search_shortcut_short_label">검색</string> + <string name="videos_shortcut_short_label">동영상</string> + <string name="analysis_channel_name">미디어 분석</string> + <string name="analysis_notification_default_title">미디어 분석</string> + <string name="analysis_notification_action_stop">취소</string> + <string name="map_shortcut_short_label">지도</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-lt/strings.xml b/android/app/src/main/res/values-lt/strings.xml new file mode 100644 index 0000000..c8c6027 --- /dev/null +++ b/android/app/src/main/res/values-lt/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="wallpaper">Ekrano paveikslėlis</string> + <string name="videos_shortcut_short_label">Vaizdo įrašai</string> + <string name="app_name">Aves</string> + <string name="app_widget_label">Nuotraukų rėmelis</string> + <string name="analysis_channel_name">Medijos nuskaitymas</string> + <string name="search_shortcut_short_label">Paieška</string> + <string name="analysis_notification_action_stop">Sustabdyti</string> + <string name="analysis_notification_default_title">Nuskaitoma medija</string> + <string name="map_shortcut_short_label">Žemėlapis</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-ml/strings.xml b/android/app/src/main/res/values-ml/strings.xml new file mode 100644 index 0000000..06647e9 --- /dev/null +++ b/android/app/src/main/res/values-ml/strings.xml @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">എവ്സ്</string> + <string name="wallpaper">ചുമർ ചിത്രം</string> + <string name="search_shortcut_short_label">തിരയുക</string> + <string name="videos_shortcut_short_label">വീഡിയോകൾ</string> + <string name="analysis_channel_name">മാധ്യമ സൂക്ഷ്മപരിശോധന</string> + <string name="analysis_notification_action_stop">നിർത്തുക</string> +</resources> diff --git a/android/app/src/main/res/values-my/strings.xml b/android/app/src/main/res/values-my/strings.xml new file mode 100644 index 0000000..ae4237c --- /dev/null +++ b/android/app/src/main/res/values-my/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">ရုပ်ပုံဘောင်</string> + <string name="wallpaper">နောက်ခံ ရုပ်ပုံ</string> + <string name="analysis_channel_name">မီဒီယာ စကင်</string> + <string name="search_shortcut_short_label">ရှာရန်</string> + <string name="videos_shortcut_short_label">ဗီဒီယိုများ</string> + <string name="analysis_notification_default_title">မီဒီယာ ကိုစကင်ဖတ်နေသည်</string> + <string name="analysis_notification_action_stop">ရပ်ရန်</string> + <string name="map_shortcut_short_label">မြေပုံ</string> +</resources> diff --git a/android/app/src/main/res/values-nb-rNO/strings.xml b/android/app/src/main/res/values-nb-rNO/strings.xml new file mode 100644 index 0000000..fd061b6 --- /dev/null +++ b/android/app/src/main/res/values-nb-rNO/strings.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="videos_shortcut_short_label">Videoer</string> + <string name="analysis_channel_name">Mediaskanning</string> + <string name="analysis_notification_default_title">Skanning av media</string> + <string name="app_widget_label">Bilderamme</string> + <string name="wallpaper">Bakgrunnsbilde</string> + <string name="search_shortcut_short_label">Søk</string> + <string name="analysis_notification_action_stop">Stopp</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-ne/strings.xml b/android/app/src/main/res/values-ne/strings.xml new file mode 100644 index 0000000..6dc61ac --- /dev/null +++ b/android/app/src/main/res/values-ne/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">एभस</string> +</resources> diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..807a30b --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources xmlns:tools="http://schemas.android.com/tools"> + <style name="NormalTheme" parent="Theme.AppCompat.NoActionBar"> + <item name="android:windowBackground">@color/window_background_night</item> + <item name="android:windowSplashScreenBackground" tools:targetApi="s">@color/window_background_night</item> + <item name="android:windowSplashScreenAnimatedIcon" tools:targetApi="s">@mipmap/ic_launcher</item> + + <!-- API28+, draws next to the notch in fullscreen --> + <item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="28">shortEdges</item> + </style> +</resources> diff --git a/android/app/src/main/res/values-nl/strings.xml b/android/app/src/main/res/values-nl/strings.xml new file mode 100644 index 0000000..103f471 --- /dev/null +++ b/android/app/src/main/res/values-nl/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Fotolijst</string> + <string name="wallpaper">Achtergrond</string> + <string name="search_shortcut_short_label">Zoeken</string> + <string name="videos_shortcut_short_label">Video’s</string> + <string name="analysis_channel_name">Media indexeren</string> + <string name="analysis_notification_default_title">Media indexeren</string> + <string name="analysis_notification_action_stop">Stoppen</string> + <string name="map_shortcut_short_label">Kaart</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-nn/strings.xml b/android/app/src/main/res/values-nn/strings.xml new file mode 100644 index 0000000..615c9eb --- /dev/null +++ b/android/app/src/main/res/values-nn/strings.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Bileteramme</string> + <string name="wallpaper">Bakgrunnsbilete</string> + <string name="search_shortcut_short_label">Søk</string> + <string name="videos_shortcut_short_label">Videoar</string> + <string name="analysis_channel_name">Mediasøking</string> + <string name="analysis_notification_default_title">Søkjer igjennom media</string> + <string name="analysis_notification_action_stop">Stogg</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-or/strings.xml b/android/app/src/main/res/values-or/strings.xml new file mode 100644 index 0000000..bec8cc7 --- /dev/null +++ b/android/app/src/main/res/values-or/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="search_shortcut_short_label">ସନ୍ଧାନ</string> +</resources> diff --git a/android/app/src/main/res/values-pl/strings.xml b/android/app/src/main/res/values-pl/strings.xml new file mode 100644 index 0000000..1cc7a69 --- /dev/null +++ b/android/app/src/main/res/values-pl/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_widget_label">Ramka Zdjęcia</string> + <string name="search_shortcut_short_label">Szukaj</string> + <string name="videos_shortcut_short_label">Wideo</string> + <string name="analysis_channel_name">Przeskanuj multimedia</string> + <string name="analysis_notification_default_title">Skanowanie multimediów</string> + <string name="analysis_notification_action_stop">Zatrzymaj</string> + <string name="app_name">Aves</string> + <string name="wallpaper">Tapeta</string> + <string name="map_shortcut_short_label">Mapa</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml new file mode 100644 index 0000000..a793c01 --- /dev/null +++ b/android/app/src/main/res/values-pt/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Porta-retratos</string> + <string name="wallpaper">Papel de parede</string> + <string name="search_shortcut_short_label">Procurar</string> + <string name="videos_shortcut_short_label">Vídeos</string> + <string name="analysis_channel_name">Digitalização de mídia</string> + <string name="analysis_notification_default_title">Digitalizando mídia</string> + <string name="analysis_notification_action_stop">Pare</string> + <string name="map_shortcut_short_label">Mapa</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-ro/strings.xml b/android/app/src/main/res/values-ro/strings.xml new file mode 100644 index 0000000..7334d4c --- /dev/null +++ b/android/app/src/main/res/values-ro/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Rama foto</string> + <string name="wallpaper">Tapet</string> + <string name="videos_shortcut_short_label">Videoclipuri</string> + <string name="analysis_channel_name">Scanare media</string> + <string name="analysis_notification_default_title">Scanarea suporturilor</string> + <string name="analysis_notification_action_stop">Stop</string> + <string name="search_shortcut_short_label">Căutare</string> + <string name="map_shortcut_short_label">Hartă</string> +</resources> diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml new file mode 100644 index 0000000..ca3cde8 --- /dev/null +++ b/android/app/src/main/res/values-ru/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Фоторамка</string> + <string name="wallpaper">Обои</string> + <string name="search_shortcut_short_label">Поиск</string> + <string name="videos_shortcut_short_label">Видео</string> + <string name="analysis_channel_name">Сканировать медия</string> + <string name="analysis_notification_default_title">Сканирование медиа</string> + <string name="analysis_notification_action_stop">Стоп</string> + <string name="map_shortcut_short_label">Карта</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-sat/strings.xml b/android/app/src/main/res/values-sat/strings.xml new file mode 100644 index 0000000..5383771 --- /dev/null +++ b/android/app/src/main/res/values-sat/strings.xml @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">ᱮᱣᱥ</string> + <string name="app_widget_label">ᱪᱤᱛᱟᱹᱨ ᱯᱷᱨᱮᱢ</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-sk/strings.xml b/android/app/src/main/res/values-sk/strings.xml new file mode 100644 index 0000000..a6c5056 --- /dev/null +++ b/android/app/src/main/res/values-sk/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="search_shortcut_short_label">Hľadať</string> + <string name="app_name">Aves</string> + <string name="app_widget_label">Rám fotky</string> + <string name="wallpaper">Tapeta</string> + <string name="videos_shortcut_short_label">Videá</string> + <string name="analysis_notification_action_stop">Zastaviť</string> + <string name="analysis_channel_name">Skenovanie médií</string> + <string name="analysis_notification_default_title">Skenovanie média</string> + <string name="map_shortcut_short_label">Mapa</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-sl/strings.xml b/android/app/src/main/res/values-sl/strings.xml new file mode 100644 index 0000000..dd0bce1 --- /dev/null +++ b/android/app/src/main/res/values-sl/strings.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_widget_label">Okvir za sliko</string> + <string name="app_name">Aves</string> + <string name="videos_shortcut_short_label">Videoposnetki</string> + <string name="wallpaper">Ozadje</string> + <string name="search_shortcut_short_label">Iskanje</string> + <string name="analysis_notification_default_title">Skeniram medijske datoteke</string> + <string name="analysis_notification_action_stop">Ustavi</string> + <string name="analysis_channel_name">Sken za medijske datoteke</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-sr/strings.xml b/android/app/src/main/res/values-sr/strings.xml new file mode 100644 index 0000000..b03879d --- /dev/null +++ b/android/app/src/main/res/values-sr/strings.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_widget_label">Okvir Slike</string> + <string name="wallpaper">Pozadina</string> + <string name="videos_shortcut_short_label">Snimci</string> + <string name="analysis_channel_name">Pretraga medija</string> + <string name="analysis_notification_default_title">Skeniranje medija</string> + <string name="analysis_notification_action_stop">Stop</string> + <string name="app_name">Aves</string> + <string name="search_shortcut_short_label">Pretraga</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-sv/strings.xml b/android/app/src/main/res/values-sv/strings.xml new file mode 100644 index 0000000..fb447ef --- /dev/null +++ b/android/app/src/main/res/values-sv/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Fotoram</string> + <string name="wallpaper">Bakgrund</string> + <string name="videos_shortcut_short_label">Videor</string> + <string name="analysis_channel_name">Media scanning</string> + <string name="analysis_notification_default_title">Scannar media</string> + <string name="analysis_notification_action_stop">Stopp</string> + <string name="search_shortcut_short_label">Sök</string> + <string name="map_shortcut_short_label">Karta</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-ta/strings.xml b/android/app/src/main/res/values-ta/strings.xml new file mode 100644 index 0000000..ca82090 --- /dev/null +++ b/android/app/src/main/res/values-ta/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">ஏவ்ச்</string> + <string name="app_widget_label">புகைப்பட சட்டகம்</string> + <string name="wallpaper">வால்பேப்பர்</string> + <string name="map_shortcut_short_label">வரைபடம்</string> + <string name="search_shortcut_short_label">தேடல்</string> + <string name="analysis_notification_default_title">ஊடக ச்கேனிங்</string> + <string name="videos_shortcut_short_label">வீடியோக்கள்</string> + <string name="analysis_channel_name">மீடியா ச்கேன்</string> + <string name="analysis_notification_action_stop">நிறுத்து</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-th/strings.xml b/android/app/src/main/res/values-th/strings.xml new file mode 100644 index 0000000..2ac9295 --- /dev/null +++ b/android/app/src/main/res/values-th/strings.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">กรอบรูป</string> + <string name="wallpaper">ภาพพื้นหลัง</string> + <string name="search_shortcut_short_label">ค้นหา</string> + <string name="videos_shortcut_short_label">วิดีโอ</string> + <string name="analysis_channel_name">สแกนสื่อบันเทิง</string> + <string name="analysis_notification_default_title">กำลังสแกนสื่อบันเทิง</string> + <string name="analysis_notification_action_stop">หยุด</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-tr/strings.xml b/android/app/src/main/res/values-tr/strings.xml new file mode 100644 index 0000000..c115ff9 --- /dev/null +++ b/android/app/src/main/res/values-tr/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Fotoğraf Çerçevesi</string> + <string name="wallpaper">Duvar kağıdı</string> + <string name="search_shortcut_short_label">Arama</string> + <string name="videos_shortcut_short_label">Videolar</string> + <string name="analysis_channel_name">Medya tarama</string> + <string name="analysis_notification_default_title">Medya taranıyor</string> + <string name="analysis_notification_action_stop">Durdur</string> + <string name="map_shortcut_short_label">Harita</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-uk/strings.xml b/android/app/src/main/res/values-uk/strings.xml new file mode 100644 index 0000000..60717a3 --- /dev/null +++ b/android/app/src/main/res/values-uk/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="wallpaper">Шпалери</string> + <string name="search_shortcut_short_label">Пошук</string> + <string name="videos_shortcut_short_label">Відео</string> + <string name="analysis_channel_name">Сканувати медіа</string> + <string name="analysis_notification_action_stop">Стоп</string> + <string name="app_widget_label">Фоторамка</string> + <string name="analysis_notification_default_title">Сканування медіа</string> + <string name="map_shortcut_short_label">Мапа</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-ur/strings.xml b/android/app/src/main/res/values-ur/strings.xml new file mode 100644 index 0000000..68d8716 --- /dev/null +++ b/android/app/src/main/res/values-ur/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> +</resources> diff --git a/android/app/src/main/res/values-vi/strings.xml b/android/app/src/main/res/values-vi/strings.xml new file mode 100644 index 0000000..96db6a4 --- /dev/null +++ b/android/app/src/main/res/values-vi/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="analysis_notification_action_stop">Dừng</string> + <string name="app_widget_label">Khung Ảnh</string> + <string name="analysis_notification_default_title">Đang quét phương tiện</string> + <string name="videos_shortcut_short_label">Video</string> + <string name="wallpaper">Hình nền</string> + <string name="app_name">Aves</string> + <string name="analysis_channel_name">Quét phương tiện</string> + <string name="search_shortcut_short_label">Tìm kiếm</string> + <string name="map_shortcut_short_label">Bản đồ</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values-zh-rTW/strings.xml b/android/app/src/main/res/values-zh-rTW/strings.xml new file mode 100644 index 0000000..bf3e0c4 --- /dev/null +++ b/android/app/src/main/res/values-zh-rTW/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="videos_shortcut_short_label">影片</string> + <string name="wallpaper">桌布</string> + <string name="analysis_notification_default_title">掃描媒體中</string> + <string name="app_name">Aves</string> + <string name="app_widget_label">相框</string> + <string name="search_shortcut_short_label">搜尋</string> + <string name="analysis_channel_name">媒體掃描</string> + <string name="analysis_notification_action_stop">停止</string> + <string name="map_shortcut_short_label">地圖</string> +</resources> diff --git a/android/app/src/main/res/values-zh/strings.xml b/android/app/src/main/res/values-zh/strings.xml new file mode 100644 index 0000000..70b8d1c --- /dev/null +++ b/android/app/src/main/res/values-zh/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">相框</string> + <string name="wallpaper">壁纸</string> + <string name="search_shortcut_short_label">搜索</string> + <string name="videos_shortcut_short_label">视频</string> + <string name="analysis_channel_name">媒体扫描</string> + <string name="analysis_notification_default_title">正在扫描媒体</string> + <string name="analysis_notification_action_stop">停止</string> + <string name="map_shortcut_short_label">地图</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..8c34775 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <color name="ic_launcher_background">#FFFFFF</color> + <color name="ic_shortcut_background">#FFFFFF</color> + <color name="ic_shortcut_foreground">#455A64</color> + <color name="ic_launcher_flavour">#1cc8eb</color> + <color name="window_background_day">#FFFFFF</color> + <color name="window_background_night">#262626</color> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..286ae61 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves</string> + <string name="app_widget_label">Photo Frame</string> + <string name="wallpaper">Wallpaper</string> + <string name="map_shortcut_short_label">Map</string> + <string name="search_shortcut_short_label">Search</string> + <string name="videos_shortcut_short_label">Videos</string> + <string name="analysis_channel_name">Media scan</string> + <string name="analysis_notification_default_title">Scanning media</string> + <string name="analysis_notification_action_stop">Stop</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..eca13a9 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources xmlns:tools="http://schemas.android.com/tools"> + <style name="NormalTheme" parent="Theme.AppCompat.Light.NoActionBar"> + <item name="android:windowBackground">@color/window_background_day</item> + <item name="android:windowSplashScreenBackground" tools:targetApi="s">@color/window_background_day</item> + <item name="android:windowSplashScreenAnimatedIcon" tools:targetApi="s">@mipmap/ic_launcher</item> + + <!-- API28+, draws next to the notch in fullscreen --> + <item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="28">shortEdges</item> + </style> +</resources> diff --git a/android/app/src/main/res/xml/app_widget_info.xml b/android/app/src/main/res/xml/app_widget_info.xml new file mode 100644 index 0000000..eb1d68c --- /dev/null +++ b/android/app/src/main/res/xml/app_widget_info.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8"?> +<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:configure="deckers.thibault.aves.HomeWidgetSettingsActivity" + android:initialLayout="@layout/app_widget" + android:minWidth="40dp" + android:minHeight="40dp" + android:resizeMode="horizontal|vertical" + android:targetCellWidth="2" + android:targetCellHeight="2" + android:updatePeriodMillis="3600000" + android:widgetCategory="home_screen" + android:widgetFeatures="reconfigurable" + tools:targetApi="s" />
\ No newline at end of file diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000..9f73294 --- /dev/null +++ b/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="utf-8"?> +<data-extraction-rules> + <cloud-backup disableIfNoEncryptionCapabilities="true"> + <include + domain="file" + path="." /> + <include + domain="database" + path="." /> + <include + domain="external" + path="." /> + <include + domain="sharedpref" + path="." /> + <exclude + domain="sharedpref" + path="secret_shared_prefs.xml" /> + </cloud-backup> + <device-transfer> + <include + domain="file" + path="." /> + <include + domain="database" + path="." /> + <include + domain="external" + path="." /> + <include + domain="sharedpref" + path="." /> + <exclude + domain="sharedpref" + path="secret_shared_prefs.xml" /> + </device-transfer> +</data-extraction-rules> diff --git a/android/app/src/main/res/xml/full_backup_content.xml b/android/app/src/main/res/xml/full_backup_content.xml new file mode 100644 index 0000000..5e5ca09 --- /dev/null +++ b/android/app/src/main/res/xml/full_backup_content.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<full-backup-content> + <include + domain="file" + path="." /> + <include + domain="database" + path="." /> + <include + domain="external" + path="." /> + <include + domain="sharedpref" + path="." /> + <exclude + domain="sharedpref" + path="secret_shared_prefs.xml" /> +</full-backup-content> diff --git a/android/app/src/main/res/xml/provider_paths.xml b/android/app/src/main/res/xml/provider_paths.xml new file mode 100644 index 0000000..168574e --- /dev/null +++ b/android/app/src/main/res/xml/provider_paths.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<paths> + <!-- `external-path` only covers files on regular device storage --> + <external-path + name="external" + path="." /> + + <!-- `root-path` is necessary to cover files on removable storage --> + <!-- cf https://iditect.com/article/fileprovider-for-android-get-content-uri-through-fileprovider.html --> + <!--suppress AndroidElementNotAllowed --> + <root-path + name="root" + path="." /> + + <!-- embedded images & other media that are exported for viewing and sharing --> + <cache-path + name="embedded" + path="." /> +</paths>
\ No newline at end of file diff --git a/android/app/src/main/res/xml/screen_saver.xml b/android/app/src/main/res/xml/screen_saver.xml new file mode 100644 index 0000000..d1de689 --- /dev/null +++ b/android/app/src/main/res/xml/screen_saver.xml @@ -0,0 +1,2 @@ +<dream xmlns:android="http://schemas.android.com/apk/res/android" + android:settingsActivity="@string/screen_saver_settings_activity" />
\ No newline at end of file diff --git a/android/app/src/main/res/xml/searchable.xml b/android/app/src/main/res/xml/searchable.xml new file mode 100644 index 0000000..d86475b --- /dev/null +++ b/android/app/src/main/res/xml/searchable.xml @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="utf-8"?> +<searchable xmlns:android="http://schemas.android.com/apk/res/android" + android:includeInGlobalSearch="true" + android:label="@string/app_name" + android:searchSuggestAuthority="@string/search_provider" + android:searchSuggestIntentAction="android.intent.action.SEARCH" + android:searchSuggestSelection=" ?" + android:searchSuggestThreshold="3" /> diff --git a/android/app/src/profile/res/values/colors.xml b/android/app/src/profile/res/values/colors.xml new file mode 100644 index 0000000..9981f6c --- /dev/null +++ b/android/app/src/profile/res/values/colors.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <color name="ic_launcher_flavour">#007A78</color> +</resources>
\ No newline at end of file diff --git a/android/app/src/profile/res/values/strings.xml b/android/app/src/profile/res/values/strings.xml new file mode 100644 index 0000000..2190231 --- /dev/null +++ b/android/app/src/profile/res/values/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">Aves [Profile]</string> +</resources>
\ No newline at end of file diff --git a/android/app/src/test/kotlin/deckers/thibault/aves/model/provider/ImageProviderTest.kt b/android/app/src/test/kotlin/deckers/thibault/aves/model/provider/ImageProviderTest.kt new file mode 100644 index 0000000..14a126f --- /dev/null +++ b/android/app/src/test/kotlin/deckers/thibault/aves/model/provider/ImageProviderTest.kt @@ -0,0 +1,18 @@ +package deckers.thibault.aves.model.provider + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.Month +import java.util.TimeZone + +class ImageProviderTest { + @Test + fun imageProvider_CorrectEmailSimple_ReturnsTrue() { + val date = LocalDate.of(1990, Month.FEBRUARY, 11).toEpochDay() + assertEquals("+01:00", ImageProvider.getTimeZoneString(TimeZone.getTimeZone("Europe/Paris"), date)) + assertEquals("+00:00", ImageProvider.getTimeZoneString(TimeZone.getTimeZone("UTC"), date)) + assertEquals("+05:30", ImageProvider.getTimeZoneString(TimeZone.getTimeZone("Asia/Kolkata"), date)) + assertEquals("-06:00", ImageProvider.getTimeZoneString(TimeZone.getTimeZone("America/Chicago"), date)) + } +} diff --git a/android/app/src/test/kotlin/deckers/thibault/aves/utils/MathUtilsTest.kt b/android/app/src/test/kotlin/deckers/thibault/aves/utils/MathUtilsTest.kt new file mode 100644 index 0000000..48382cc --- /dev/null +++ b/android/app/src/test/kotlin/deckers/thibault/aves/utils/MathUtilsTest.kt @@ -0,0 +1,17 @@ +package deckers.thibault.aves.utils + +import deckers.thibault.aves.utils.MathUtils.highestPowerOf2 +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class MathUtilsTest { + @Test + fun mathUtils_highestPowerOf2() { + assertEquals(1024, highestPowerOf2(1024)) + assertEquals(32, highestPowerOf2(42)) + assertEquals(0, highestPowerOf2(0)) + assertEquals(0, highestPowerOf2(-42)) + assertEquals(0, highestPowerOf2(.5)) + assertEquals(1, highestPowerOf2(1.5)) + } +} |
