Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob] Log source automatically

Neeraj Gupta2540023aefb9
diff --git a/mobile/apps/photos/android/app/build.gradle b/mobile/apps/photos/android/app/build.gradle
index 37197ed806..2962d42ecc 100644
--- a/mobile/apps/photos/android/app/build.gradle
+++ b/mobile/apps/photos/android/app/build.gradle
@@ -46,6 +46,10 @@ android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
+ playstore.java.srcDirs += 'src/playstore/kotlin'
+ fdroid.java.srcDirs += 'src/noReferrer/kotlin'
+ independent.java.srcDirs += 'src/noReferrer/kotlin'
+ dev.java.srcDirs += 'src/noReferrer/kotlin'
}
lintOptions {
@@ -174,6 +178,7 @@ dependencies {
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
implementation 'com.microsoft.onnxruntime:onnxruntime-android:1.8.1'
+ playstoreImplementation 'com.android.installreferrer:installreferrer:2.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/InstallSourceEventStore.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/InstallSourceEventStore.kt
new file mode 100644
index 0000000000..03aa887a8b
--- /dev/null
+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/InstallSourceEventStore.kt
@@ -0,0 +1,166 @@
+package io.ente.photos
+
+import android.content.Context
+import android.content.pm.PackageInfo
+import android.os.Build
+import java.net.URLDecoder
+import java.util.UUID
+import org.json.JSONObject
+
+data class InstallSource(
+ val channel: String,
+ val platform: String,
+ val referrerParams: Map<String, String>,
+) {
+ val hasReferrer: Boolean get() = referrerParams.isNotEmpty()
+}
+
+class InstallSourceEventStore(private val context: Context) {
+ private val prefs = context.getSharedPreferences("install_source_state", Context.MODE_PRIVATE)
+
+ fun sourceFromState(): InstallSource? {
+ val sourceJson = prefs.getString(KEY_SOURCE, null) ?: return null
+ return runCatching {
+ val json = JSONObject(sourceJson)
+ val paramsJson = json.optJSONObject("referrer_params")
+ val params = buildMap {
+ paramsJson?.keys()?.forEach { key ->
+ put(key, paramsJson.optString(key))
+ }
+ }
+ InstallSource(
+ channel = json.optString("channel", channelForPackage()),
+ platform = json.optString("platform", PLATFORM_ANDROID),
+ referrerParams = params,
+ )
+ }.getOrNull()
+ }
+
+ fun fallbackSource(channel: String = channelForPackage()): InstallSource = InstallSource(
+ channel = channel,
+ platform = PLATFORM_ANDROID,
+ referrerParams = emptyMap(),
+ )
+
+ fun playSource(
+ referrer: String?,
+ ): InstallSource = InstallSource(
+ channel = CHANNEL_PLAYSTORE,
+ platform = PLATFORM_ANDROID,
+ referrerParams = parseReferrerParams(referrer),
+ )
+
+ fun saveSource(source: InstallSource) {
+ prefs.edit()
+ .putString(KEY_SOURCE, source.toJson().toString())
+ .putInt(
+ KEY_FLAGS,
+ flags.withFlag(FLAG_SOURCE_PRESENT, source.hasReferrer) or FLAG_SOURCE_RESOLVED
+ )
+ .apply()
+ }
+
+ fun logInstallSource(source: InstallSource): String? {
+ if (flags.hasFlag(FLAG_INSTALL_EVENT_LOGGED)) {
+ return null
+ }
+ val installSourceId = prefs.getString(KEY_INSTALL_SOURCE_ID, null) ?: UUID.randomUUID().toString()
+ val eventJson = buildEvent(source, installSourceId).toString()
+ prefs.edit()
+ .putString(KEY_SOURCE, source.toJson().toString())
+ .putString(KEY_INSTALL_SOURCE_ID, installSourceId)
+ .putInt(
+ KEY_FLAGS,
+ flags.withFlag(FLAG_SOURCE_PRESENT, source.hasReferrer) or
+ FLAG_SOURCE_RESOLVED or
+ FLAG_INSTALL_EVENT_LOGGED
+ )
+ .putInt(KEY_SCHEMA_VERSION, 1)
+ .apply()
+ return eventJson
+ }
+
+ fun channelForPackage(): String {
+ val packageName = context.packageName.removeSuffix(".debug")
+ return when (packageName) {
+ "io.ente.photos" -> CHANNEL_PLAYSTORE
+ "io.ente.photos.fdroid" -> "fdroid"
+ "io.ente.photos.independent" -> "github"
+ "io.ente.photos.dev" -> "dev"
+ else -> "unknown"
+ }
+ }
+
+ private fun buildEvent(source: InstallSource, installSourceId: String): JSONObject {
+ val packageInfo = packageInfo()
+ return JSONObject()
+ .put("event", "install_source")
+ .put("install_source_id", installSourceId)
+ .put("event_type", "install")
+ .put("app", "photos")
+ .put("platform", source.platform)
+ .put("channel", source.channel)
+ .put("package_name", context.packageName)
+ .put("app_version", packageInfo?.versionName.orEmpty())
+ .put("build_number", packageInfo?.buildNumber().orEmpty())
+ .put("referrer", JSONObject().put("params", JSONObject(source.referrerParams)))
+ }
+
+ private fun parseReferrerParams(referrer: String?): Map<String, String> {
+ val query = referrer?.trim()?.removePrefix("?")
+ if (query.isNullOrEmpty()) {
+ return emptyMap()
+ }
+ return runCatching {
+ query.split("&")
+ .asSequence()
+ .filter { it.isNotBlank() }
+ .mapNotNull { part ->
+ val separator = part.indexOf("=")
+ val key = if (separator >= 0) part.substring(0, separator) else part
+ val value = if (separator >= 0) part.substring(separator + 1) else ""
+ val decodedKey = key.urlDecode()
+ if (decodedKey.isEmpty()) {
+ null
+ } else {
+ decodedKey to value.urlDecode()
+ }
+ }
+ .toMap()
+ }.getOrDefault(emptyMap())
+ }
+
+ private fun InstallSource.toJson(): JSONObject = JSONObject()
+ .put("channel", channel)
+ .put("platform", platform)
+ .put("referrer_params", JSONObject(referrerParams))
+
+ private fun String.urlDecode(): String =
+ URLDecoder.decode(this, Charsets.UTF_8.name())
+
+ private fun packageInfo(): PackageInfo? =
+ runCatching { context.packageManager.getPackageInfo(context.packageName, 0) }.getOrNull()
+
+ @Suppress("DEPRECATION")
+ private fun PackageInfo.buildNumber(): String =
+ (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) longVersionCode else versionCode.toLong()).toString()
+
+ private val flags: Int get() = prefs.getInt(KEY_FLAGS, 0)
+
+ private fun Int.hasFlag(flag: Int): Boolean = this and flag != 0
+
+ private fun Int.withFlag(flag: Int, enabled: Boolean): Int =
+ if (enabled) this or flag else this and flag.inv()
+
+ companion object {
+ private const val CHANNEL_PLAYSTORE = "playstore"
+ private const val FLAG_SOURCE_PRESENT = 1 shl 0
+ private const val FLAG_SOURCE_RESOLVED = 1 shl 1
+ private const val FLAG_INSTALL_EVENT_LOGGED = 1 shl 2
+ private const val KEY_FLAGS = "flags"
+ private const val KEY_INSTALL_SOURCE_ID = "install_source_id"
+ private const val KEY_SCHEMA_VERSION = "schema_version"
+ private const val KEY_SOURCE = "source"
+ private const val PLATFORM_ANDROID = "android"
+ }
+}
diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt
index 7422f67826..63151a2b58 100644
--- a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt
+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt
@@ -2,8 +2,26 @@ package io.ente.photos
import android.content.Intent
import io.flutter.embedding.android.FlutterFragmentActivity
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterFragmentActivity() {
+ private val installSourceProvider by lazy { InstallSourceProvider(this) }
+
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+ super.configureFlutterEngine(flutterEngine)
+ MethodChannel(
+ flutterEngine.dartExecutor.binaryMessenger,
+ "io.ente.photos/install_source"
+ ).setMethodCallHandler { call, result ->
+ when (call.method) {
+ "hasInstallSource" -> installSourceProvider.hasInstallSource(result)
+ "logInstallSource" -> installSourceProvider.logInstallSource(result)
+ else -> result.notImplemented()
+ }
+ }
+ }
+
override fun onNewIntent(intent: Intent) {
setIntent(intent)
super.onNewIntent(intent)
diff --git a/mobile/apps/photos/android/app/src/noReferrer/kotlin/io/ente/photos/InstallSourceProvider.kt b/mobile/apps/photos/android/app/src/noReferrer/kotlin/io/ente/photos/InstallSourceProvider.kt
new file mode 100644
index 0000000000..b001729485
--- /dev/null
+++ b/mobile/apps/photos/android/app/src/noReferrer/kotlin/io/ente/photos/InstallSourceProvider.kt
@@ -0,0 +1,17 @@
+package io.ente.photos
+
+import android.content.Context
+import io.flutter.plugin.common.MethodChannel
+
+class InstallSourceProvider(context: Context) {
+ private val store = InstallSourceEventStore(context)
+
+ fun hasInstallSource(result: MethodChannel.Result) {
+ result.success(false)
+ }
+
+ fun logInstallSource(result: MethodChannel.Result) {
+ val source = store.sourceFromState() ?: store.fallbackSource()
+ result.success(store.logInstallSource(source))
+ }
+}
diff --git a/mobile/apps/photos/android/app/src/playstore/kotlin/io/ente/photos/InstallSourceProvider.kt b/mobile/apps/photos/android/app/src/playstore/kotlin/io/ente/photos/InstallSourceProvider.kt
new file mode 100644
index 0000000000..8cdfb506de
--- /dev/null
+++ b/mobile/apps/photos/android/app/src/playstore/kotlin/io/ente/photos/InstallSourceProvider.kt
@@ -0,0 +1,121 @@
+package io.ente.photos
+
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
+import com.android.installreferrer.api.InstallReferrerClient
+import com.android.installreferrer.api.InstallReferrerStateListener
+import io.flutter.plugin.common.MethodChannel
+
+class InstallSourceProvider(private val context: Context) {
+ private val store = InstallSourceEventStore(context)
+ private val pendingCallbacks = mutableListOf<(InstallSource?) -> Unit>()
+
+ private var cachedSource: InstallSource? = null
+ private var isFetching = false
+
+ fun hasInstallSource(result: MethodChannel.Result) {
+ getInstallSource { source ->
+ result.success(source?.hasReferrer == true)
+ }
+ }
+
+ fun logInstallSource(result: MethodChannel.Result) {
+ getInstallSource { source ->
+ result.success(source?.let { store.logInstallSource(it) })
+ }
+ }
+
+ @Synchronized
+ private fun getInstallSource(callback: (InstallSource?) -> Unit) {
+ val source = cachedSource ?: store.sourceFromState()
+ if (source != null) {
+ cachedSource = source
+ callback(source)
+ return
+ }
+
+ pendingCallbacks.add(callback)
+ if (isFetching) {
+ return
+ }
+ isFetching = true
+ fetchInstallSource { fetchedSource ->
+ val callbacks = synchronized(this) {
+ if (fetchedSource != null) {
+ cachedSource = fetchedSource
+ store.saveSource(fetchedSource)
+ }
+ isFetching = false
+ pendingCallbacks.toList().also {
+ pendingCallbacks.clear()
+ }
+ }
+ callbacks.forEach { it(fetchedSource) }
+ }
+ }
+
+ private fun fetchInstallSource(callback: (InstallSource?) -> Unit) {
+ val client = InstallReferrerClient.newBuilder(context).build()
+ val completionLock = Any()
+ var completed = false
+ val handler = Handler(Looper.getMainLooper())
+ lateinit var timeoutRunnable: Runnable
+
+ fun complete(source: InstallSource?) {
+ synchronized(completionLock) {
+ if (completed) {
+ return
+ }
+ completed = true
+ }
+ handler.removeCallbacks(timeoutRunnable)
+ try {
+ client.endConnection()
+ } catch (_: Exception) {
+ }
+ handler.post { callback(source) }
+ }
+
+ timeoutRunnable = Runnable {
+ complete(null)
+ }
+ handler.postDelayed(
+ timeoutRunnable,
+ INSTALL_REFERRER_TIMEOUT_MS,
+ )
+
+ try {
+ client.startConnection(object : InstallReferrerStateListener {
+ override fun onInstallReferrerSetupFinished(responseCode: Int) {
+ when (responseCode) {
+ InstallReferrerClient.InstallReferrerResponse.OK -> {
+ try {
+ val details = client.installReferrer
+ complete(
+ store.playSource(
+ referrer = details.installReferrer,
+ )
+ )
+ } catch (_: Exception) {
+ complete(null)
+ }
+ }
+
+ else -> complete(null)
+ }
+ }
+
+ override fun onInstallReferrerServiceDisconnected() {
+ complete(null)
+ }
+ })
+ } catch (_: Exception) {
+ complete(null)
+ }
+ }
+
+ private companion object {
+ const val INSTALL_REFERRER_TIMEOUT_MS = 2000L
+ }
+}
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 71bcf736ff..93dd6913ef 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -36,6 +36,7 @@ import 'package:photos/services/app_lifecycle_service.dart';
import 'package:photos/services/collections_service.dart';
import 'package:photos/services/favorites_service.dart';
import 'package:photos/services/home_widget_service.dart';
+import "package:photos/services/install_source_service.dart";
import 'package:photos/services/local_file_update_service.dart';
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import 'package:photos/services/machine_learning/ml_service.dart';
@@ -189,6 +190,7 @@ Future<void> _warmForegroundDeferredServices() async {
} catch (e, s) {
_logger.warning("Deferred MemoryLaneService warm failed", e, s);
}
+ await InstallSourceService.instance.logSource();
}
ThemeMode _themeMode(AdaptiveThemeMode? savedThemeMode) {
diff --git a/mobile/apps/photos/lib/services/install_source_service.dart b/mobile/apps/photos/lib/services/install_source_service.dart
new file mode 100644
index 0000000000..972f503d91
--- /dev/null
+++ b/mobile/apps/photos/lib/services/install_source_service.dart
@@ -0,0 +1,49 @@
+import "dart:io";
+
+import "package:flutter/services.dart";
+import "package:logging/logging.dart";
+
+class InstallSourceService {
+ InstallSourceService._privateConstructor();
+
+ static final InstallSourceService instance =
+ InstallSourceService._privateConstructor();
+
+ static const _methodChannel = MethodChannel("io.ente.photos/install_source");
+ static const _platformChannelTimeout = Duration(seconds: 3);
+
+ final _logger = Logger("InstallSourceService");
+
+ Future<void> logSource() => _logSource();
+
+ Future<bool> hasInstallSource() async {
+ if (!Platform.isAndroid) {
+ return false;
+ }
+ try {
+ return await _methodChannel
+ .invokeMethod<bool>("hasInstallSource")
+ .timeout(_platformChannelTimeout) ??
+ false;
+ } catch (e, s) {
+ _logger.warning("Failed to check install source", e, s);
+ return false;
+ }
+ }
+
+ Future<void> _logSource() async {
+ if (!Platform.isAndroid) {
+ return;
+ }
+ try {
+ final eventJson = await _methodChannel
+ .invokeMethod<String>("logInstallSource")
+ .timeout(_platformChannelTimeout);
+ if (eventJson != null && eventJson.isNotEmpty) {
+ _logger.info("InstallSourceEvent $eventJson");
+ }
+ } catch (e, s) {
+ _logger.warning("Failed to log InstallSourceEvent", e, s);
+ }
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/account/email_entry_page.dart b/mobile/apps/photos/lib/ui/account/email_entry_page.dart
index 1fe5107d06..cc3e0291d6 100644
--- a/mobile/apps/photos/lib/ui/account/email_entry_page.dart
+++ b/mobile/apps/photos/lib/ui/account/email_entry_page.dart
@@ -6,6 +6,7 @@ import 'package:password_strength/password_strength.dart';
import 'package:photos/core/configuration.dart';
import "package:photos/generated/l10n.dart";
import 'package:photos/services/account/user_service.dart';
+import "package:photos/services/install_source_service.dart";
import "package:photos/theme/colors.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/theme/text_style.dart";
@@ -48,6 +49,7 @@ class _EmailEntryPageState extends State<EmailEntryPage> {
bool _emailIsValid = false;
bool _showEmailValidation = false;
bool _hasAgreedToTOS = true;
+ bool _hasInstallSource = false;
bool _passwordsMatch = false;
bool _passwordIsValid = false;
bool _showPasswordStrength = false;
@@ -60,6 +62,9 @@ class _EmailEntryPageState extends State<EmailEntryPage> {
void initState() {
super.initState();
_referralSource = widget.referralSource?.trim() ?? '';
+ if (widget.showReferralSourceField) {
+ unawaited(_updateReferralSourceFieldVisibility());
+ }
final storedEmail = _config.getEmail();
if (storedEmail != null && storedEmail.isNotEmpty) {
_email = storedEmail;
@@ -119,7 +124,9 @@ class _EmailEntryPageState extends State<EmailEntryPage> {
? () async {
_config.setVolatilePassword(_passwordController1.text);
await UserService.instance.setEmail(_email!);
- await UserService.instance.setRefSource(_referralSource);
+ await UserService.instance.setRefSource(
+ await _referralSourceForSubmission(),
+ );
await UserService.instance.sendOtt(
context,
_email!,
@@ -268,7 +275,7 @@ class _EmailEntryPageState extends State<EmailEntryPage> {
);
},
),
- if (widget.showReferralSourceField) ...[
+ if (_showReferralSourceField) ...[
const SizedBox(height: 24),
TextInputWidgetV2(
label: AppLocalizations.of(context).hearUsWhereTitle,
@@ -301,6 +308,38 @@ class _EmailEntryPageState extends State<EmailEntryPage> {
);
}
+ bool get _showReferralSourceField =>
+ widget.showReferralSourceField && !_hasInstallSource;
+
+ String get _routeSource => widget.referralSource?.trim() ?? '';
+
+ Future<void> _updateReferralSourceFieldVisibility() async {
+ final hasInstallSource = await InstallSourceService.instance
+ .hasInstallSource();
+ _setHasInstallSource(hasInstallSource);
+ }
+
+ Future<String> _referralSourceForSubmission() async {
+ if (!widget.showReferralSourceField) {
+ return _routeSource;
+ }
+ if (_hasInstallSource) {
+ return _routeSource;
+ }
+ final hasInstallSource = await InstallSourceService.instance
+ .hasInstallSource();
+ _setHasInstallSource(hasInstallSource);
+ return hasInstallSource ? _routeSource : _referralSource;
+ }
+
+ void _setHasInstallSource(bool hasInstallSource) {
+ if (mounted && hasInstallSource != _hasInstallSource) {
+ setState(() {
+ _hasInstallSource = hasInstallSource;
+ });
+ }
+ }
+
Widget _getLoginPrompt(EnteColorScheme colorScheme, EnteTextTheme textTheme) {
return SafeArea(
top: false,
diff --git a/mobile/apps/photos/scripts/prepare_fdroid_source.sh b/mobile/apps/photos/scripts/prepare_fdroid_source.sh
index f8b83dedd4..6f0a365a53 100755
--- a/mobile/apps/photos/scripts/prepare_fdroid_source.sh
+++ b/mobile/apps/photos/scripts/prepare_fdroid_source.sh
@@ -13,6 +13,14 @@ remove_direct_dependencies() {
count=$(rg -c "^ (firebase_core|firebase_messaging|in_app_purchase):" pubspec.yaml || true)
[[ "$count" == "3" ]] || fail "expected three restricted dependencies in pubspec.yaml"
perl -0pi -e 's/^ (firebase_core|firebase_messaging|in_app_purchase):[^\n]*\n//mg' pubspec.yaml
+
+ count=$(rg -c "^[[:space:]]*playstoreImplementation ['\"]com\\.android\\.installreferrer:installreferrer:" android/app/build.gradle || true)
+ [[ "$count" == "1" ]] || fail "expected one Play install referrer dependency in android/app/build.gradle"
+ perl -0pi -e 's/^[[:space:]]*playstoreImplementation ['\''"]com\.android\.installreferrer:installreferrer:[^'\''"]+['\''"]\n//mg' android/app/build.gradle
+}
+
+remove_playstore_sources() {
+ rm -rf android/app/src/playstore/kotlin
}
copy_fdroid_overlay() {
@@ -27,8 +35,13 @@ assert_fdroid_source() {
if rg -n "FirebaseMessaging|Firebase\\.initializeApp|RemoteMessage|InAppPurchase|PurchaseStatus" lib; then
fail "restricted Firebase or in-app purchase references remain"
fi
+
+ if rg -n "com\\.android\\.installreferrer|InstallReferrer(Client|StateListener)|installreferrer" android/app/build.gradle android/app/src; then
+ fail "Play install referrer dependency or source remains"
+ fi
}
remove_direct_dependencies
+remove_playstore_sources
copy_fdroid_overlay
assert_fdroid_source