π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add Locker source attribution
Neeraj Gupta742e4d33ee3a
diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dartindex ac51e48f90..48be723864 100644--- a/mobile/apps/locker/lib/main.dart+++ b/mobile/apps/locker/lib/main.dart@@ -2,10 +2,12 @@ import 'dart:async';import 'dart:io';import 'package:adaptive_theme/adaptive_theme.dart';+import 'package:ente_accounts/services/install_source_handler.dart';import 'package:ente_accounts/services/user_service.dart';import 'package:ente_components/ente_components.dart' as components;import 'package:ente_crypto_api/ente_crypto_api.dart';import 'package:ente_crypto_dart_adapter/ente_crypto_dart_adapter.dart';+import 'package:ente_install_source/ente_install_source.dart';import "package:ente_legacy/services/emergency_service.dart";import "package:ente_legacy/services/legacy_kit_service.dart";import 'package:ente_lock_screen/lock_screen_settings.dart';@@ -191,7 +193,21 @@ Future<void> _init(bool bool, {String? via}) async {await Configuration.instance.init([LockerDB.instance]);await Network.instance.init(Configuration.instance);- await UserService.instance.init(Configuration.instance, const HomePage());+ final installSourceService = InstallSourceService(+ Network.instance.enteDio,+ app: Configuration.instance.appIdentity.app,+ getToken: Configuration.instance.getToken,+ );+ await UserService.instance.init(+ Configuration.instance,+ const HomePage(),+ installSourceHandler: InstallSourceHandler(+ hasInstallSource: installSourceService.hasInstallSource,+ autoAttributeSource: installSourceService.autoAttributeSource,+ autoAttributePendingSource:+ installSourceService.autoAttributePendingSource,+ ),+ );await LockScreenSettings.instance.init(Configuration.instance,hideAppContentDefault: true,@@ -222,6 +238,12 @@ Future<void> _init(bool bool, {String? via}) async {config: Configuration.instance,sessionProvider: LockerContactsDisplayService.buildSession,);+ unawaited(+ Future.delayed(+ const Duration(seconds: 5),+ installSourceService.autoAttributePendingSource,+ ),+ );} catch (e) {_logger.severe("Error during initialization", e);}diff --git a/mobile/apps/locker/pubspec.yaml b/mobile/apps/locker/pubspec.yamlindex b9345c4a8e..09648c2d4c 100644--- a/mobile/apps/locker/pubspec.yaml+++ b/mobile/apps/locker/pubspec.yaml@@ -36,6 +36,8 @@ dependencies:path: ../../packages/eventsente_icons:path: ../../packages/ente_icons+ ente_install_source:+ path: ../../packages/install_sourceente_legacy:path: ../../packages/legacyente_lock_screen:diff --git a/mobile/apps/locker/scripts/prepare_fdroid_source.sh b/mobile/apps/locker/scripts/prepare_fdroid_source.shnew file mode 100755index 0000000000..2e3ee16f58--- /dev/null+++ b/mobile/apps/locker/scripts/prepare_fdroid_source.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+set -euo pipefail++cd "$(dirname "$0")/.."++../../packages/install_source/scripts/prepare_fdroid_source.shdiff --git a/mobile/apps/photos/android/app/build.gradle b/mobile/apps/photos/android/app/build.gradleindex 2962d42ecc..37197ed806 100644--- a/mobile/apps/photos/android/app/build.gradle+++ b/mobile/apps/photos/android/app/build.gradle@@ -46,10 +46,6 @@ 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 {@@ -178,7 +174,6 @@ 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/NativeChannels.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/NativeChannels.ktindex 3c3af41f38..ac4b79858c 100644--- a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/NativeChannels.kt+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/NativeChannels.kt@@ -14,37 +14,10 @@ import io.flutter.plugin.common.MethodChannelobject NativeChannels {fun register(context: Context, flutterEngine: FlutterEngine) {val messenger = flutterEngine.dartExecutor.binaryMessenger- InstallSourceChannel(context.applicationContext).register(messenger)MediaStoreChannel(context.applicationContext).register(messenger)}}-private class InstallSourceChannel(context: Context) {- private val provider = InstallSourceProvider(context)-- fun register(messenger: BinaryMessenger) {- MethodChannel(messenger, CHANNEL).setMethodCallHandler(::handle)- }-- private fun handle(call: MethodCall, result: MethodChannel.Result) {- when (call.method) {- "hasInstallSource" -> provider.hasInstallSource(result)- "autoAttributeSource" -> provider.autoAttributeSource(- call.argument<Boolean>("isSignUp") == true,- result,- )-- "getPendingEvents" -> provider.getPendingEvents(result)- "markEventSent" -> provider.markEventSent(call.argument("event"), result)- else -> result.notImplemented()- }- }-- private companion object {- const val CHANNEL = "io.ente.photos/install_source"- }-}-private class MediaStoreChannel(private val context: Context) {fun register(messenger: BinaryMessenger) {MethodChannel(messenger, CHANNEL).setMethodCallHandler(::handle)diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dartindex a19ad47b6b..122132629d 100644--- a/mobile/apps/photos/lib/service_locator.dart+++ b/mobile/apps/photos/lib/service_locator.dart@@ -1,7 +1,9 @@import "package:dio/dio.dart";import "package:ente_cast/ente_cast.dart";import "package:ente_feature_flag/ente_feature_flag.dart";+import "package:ente_install_source/ente_install_source.dart";import "package:package_info_plus/package_info_plus.dart";+import "package:photos/core/configuration.dart";import "package:photos/core/network/endpoint_config.dart";import "package:photos/gateways/billing/billing_gateway.dart";import "package:photos/gateways/collections/collection_files_gateway.dart";@@ -25,7 +27,6 @@ import "package:photos/services/backup_preference_service.dart";import "package:photos/services/collections_service.dart";import "package:photos/services/entity_service.dart";import "package:photos/services/filedata/filedata_service.dart";-import "package:photos/services/install_source_service.dart";import "package:photos/services/location_service.dart";import "package:photos/services/machine_learning/compute_controller.dart";import "package:photos/services/machine_learning/face_ml/face_recognition_service.dart";@@ -292,6 +293,8 @@ InstallSourceService? _installSourceService;InstallSourceService get installSourceService {_installSourceService ??= InstallSourceService(ServiceLocator.instance.enteDio,+ app: "photos",+ getToken: Configuration.instance.getToken,);return _installSourceService!;}diff --git a/mobile/apps/photos/lib/services/install_source_service.dart b/mobile/apps/photos/lib/services/install_source_service.dartdeleted file mode 100644index 00efe96084..0000000000--- a/mobile/apps/photos/lib/services/install_source_service.dart+++ /dev/null@@ -1,87 +0,0 @@-import "dart:convert";-import "dart:io";--import "package:dio/dio.dart";-import "package:flutter/services.dart";-import "package:logging/logging.dart";-import "package:photos/core/configuration.dart";--class InstallSourceService {- InstallSourceService(this._enteDio);-- static const _methodChannel = MethodChannel("io.ente.photos/install_source");- static const _platformChannelTimeout = Duration(seconds: 3);- static const _installEvent = "install";- static const _app = "photos";-- final Dio _enteDio;- final _logger = Logger("InstallSourceService");-- Future<void> autoAttributeSource({required bool isSignUp}) async {- if (!Platform.isAndroid) {- return;- }- try {- await _methodChannel- .invokeMethod<void>("autoAttributeSource", {"isSignUp": isSignUp})- .timeout(_platformChannelTimeout);- await autoAttributePendingSource();- } catch (e, s) {- _logger.warning("Failed to auto-attribute install source", e, s);- }- }-- Future<void> autoAttributePendingSource() async {- if (!Platform.isAndroid) {- return;- }- try {- final events =- await _methodChannel- .invokeListMethod<String>("getPendingEvents")- .timeout(_platformChannelTimeout) ??- const <String>[];- for (final eventJson in events) {- await _sendEventJson(eventJson);- }- } catch (e, s) {- _logger.warning("Failed to flush install source events", e, s);- }- }-- 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> _sendEventJson(String eventJson) async {- final event = jsonDecode(eventJson) as Map<String, dynamic>;- final eventName = event["event"] as String?;- if (eventName == null) {- return;- }- if (eventName != _installEvent &&- Configuration.instance.getToken() == null) {- return;- }- event["app"] = _app;- event["platform"] = Platform.operatingSystem;- await _enteDio.post(- eventName == _installEvent ? "/events" : "/events/user",- data: event,- );- await _methodChannel.invokeMethod<void>("markEventSent", {- "event": eventName,- });- }-}diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yamlindex 9a51801819..0dc6e6906c 100644--- a/mobile/apps/photos/pubspec.yaml+++ b/mobile/apps/photos/pubspec.yaml@@ -69,6 +69,8 @@ dependencies:path: plugins/ente_feature_flagente_icons:path: ../../packages/ente_icons+ ente_install_source:+ path: ../../packages/install_sourceente_lock_screen:path: ../../packages/lock_screenente_photos_rust:diff --git a/mobile/apps/photos/scripts/prepare_fdroid_source.sh b/mobile/apps/photos/scripts/prepare_fdroid_source.shindex 6f0a365a53..6b27209a7b 100755--- a/mobile/apps/photos/scripts/prepare_fdroid_source.sh+++ b/mobile/apps/photos/scripts/prepare_fdroid_source.sh@@ -13,14 +13,10 @@ 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+ ../../packages/install_source/scripts/prepare_fdroid_source.sh}copy_fdroid_overlay() {@@ -36,7 +32,7 @@ assert_fdroid_source() {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+ if rg -n "com\\.android\\.installreferrer|InstallReferrer(Client|StateListener)|installreferrer" android/app/build.gradle android/app/src ../../packages/install_source/android; thenfail "Play install referrer dependency or source remains"fi}diff --git a/mobile/packages/accounts/lib/ente_accounts.dart b/mobile/packages/accounts/lib/ente_accounts.dartindex 9fcaf2bcf6..42f41dcd75 100644--- a/mobile/packages/accounts/lib/ente_accounts.dart+++ b/mobile/packages/accounts/lib/ente_accounts.dart@@ -24,5 +24,6 @@ export 'pages/sessions_page.dart';export 'pages/two_factor_authentication_page.dart';export 'pages/two_factor_recovery_page.dart';+export 'services/install_source_handler.dart';export 'services/passkey_service.dart';export 'services/user_service.dart';diff --git a/mobile/packages/accounts/lib/pages/email_entry_page.dart b/mobile/packages/accounts/lib/pages/email_entry_page.dartindex 22c4a57100..b56cf013fd 100644--- a/mobile/packages/accounts/lib/pages/email_entry_page.dart+++ b/mobile/packages/accounts/lib/pages/email_entry_page.dart@@ -40,6 +40,7 @@ class _EmailEntryPageState extends State<EmailEntryPage> {bool _password1Visible = false;bool _password2Visible = false;bool _passwordsMatch = false;+ bool _hasInstallSource = false;final _password1FocusNode = FocusNode();final _password2FocusNode = FocusNode();@@ -67,6 +68,7 @@ class _EmailEntryPageState extends State<EmailEntryPage> {});});super.initState();+ _updateReferralSourceFieldVisibility();}@override@@ -135,11 +137,13 @@ class _EmailEntryPageState extends State<EmailEntryPage> {isKeypadOpen: isKeypadOpen,isFormValid: _isFormValid(),buttonText: context.strings.createAccount,- onPressedFunction: () {- UserService.instance.setEmail(_email!);+ onPressedFunction: () async {+ await UserService.instance.setEmail(_email!);widget.config.setVolatilePassword(_passwordController1.text);- UserService.instance.setRefSource(_referralSource);- UserService.instance.sendOtt(+ await UserService.instance.setRefSource(+ await _referralSourceForSubmission(),+ );+ await UserService.instance.sendOtt(context,_email!,isCreateAccountScreen: true,@@ -400,42 +404,46 @@ class _EmailEntryPageState extends State<EmailEntryPage> {),),),- const SizedBox(height: 8),- Text(- context.strings.hearUsWhereTitle,- style: textTheme.bodyBold.copyWith(- color: colorScheme.textBase,- ),- ),- const SizedBox(height: 8),- TextFormField(- style: textTheme.body.copyWith(- color: colorScheme.textBase,- ),- decoration: InputDecoration(- fillColor: colorScheme.backdropBase,- filled: true,- hintStyle: TextStyle(color: colorScheme.textMuted),- contentPadding: const EdgeInsets.symmetric(- horizontal: 16,- vertical: 14,+ if (_showReferralSourceField) const SizedBox(height: 8),+ if (_showReferralSourceField)+ Text(+ context.strings.hearUsWhereTitle,+ style: textTheme.bodyBold.copyWith(+ color: colorScheme.textBase,),- border: OutlineInputBorder(- borderSide: BorderSide.none,- borderRadius: BorderRadius.circular(8),+ ),+ if (_showReferralSourceField) const SizedBox(height: 8),+ if (_showReferralSourceField)+ TextFormField(+ style: textTheme.body.copyWith(+ color: colorScheme.textBase,),- enabledBorder: OutlineInputBorder(- borderSide: BorderSide.none,- borderRadius: BorderRadius.circular(8),+ decoration: InputDecoration(+ fillColor: colorScheme.backdropBase,+ filled: true,+ hintStyle: TextStyle(+ color: colorScheme.textMuted,+ ),+ contentPadding: const EdgeInsets.symmetric(+ horizontal: 16,+ vertical: 14,+ ),+ border: OutlineInputBorder(+ borderSide: BorderSide.none,+ borderRadius: BorderRadius.circular(8),+ ),+ enabledBorder: OutlineInputBorder(+ borderSide: BorderSide.none,+ borderRadius: BorderRadius.circular(8),+ ),),+ onChanged: (value) {+ _referralSource = value.trim();+ },+ autocorrect: false,+ keyboardType: TextInputType.text,+ textInputAction: TextInputAction.next,),- onChanged: (value) {- _referralSource = value.trim();- },- autocorrect: false,- keyboardType: TextInputType.text,- textInputAction: TextInputAction.next,- ),],),),@@ -452,6 +460,30 @@ class _EmailEntryPageState extends State<EmailEntryPage> {);}+ bool get _showReferralSourceField => !_hasInstallSource;++ Future<void> _updateReferralSourceFieldVisibility() async {+ final hasInstallSource = await UserService.instance.hasInstallSource();+ _setHasInstallSource(hasInstallSource);+ }++ Future<String> _referralSourceForSubmission() async {+ if (_hasInstallSource) {+ return '';+ }+ final hasInstallSource = await UserService.instance.hasInstallSource();+ _setHasInstallSource(hasInstallSource);+ return hasInstallSource ? '' : _referralSource;+ }++ void _setHasInstallSource(bool hasInstallSource) {+ if (mounted && hasInstallSource != _hasInstallSource) {+ setState(() {+ _hasInstallSource = hasInstallSource;+ });+ }+ }+Widget _getTOSAgreement() {final textTheme = getEnteTextTheme(context);final colorScheme = getEnteColorScheme(context);diff --git a/mobile/packages/accounts/lib/pages/password_reentry_page.dart b/mobile/packages/accounts/lib/pages/password_reentry_page.dartindex a876047d9a..6d81a923c2 100644--- a/mobile/packages/accounts/lib/pages/password_reentry_page.dart+++ b/mobile/packages/accounts/lib/pages/password_reentry_page.dart@@ -115,6 +115,7 @@ class _PasswordReentryPageState extends State<PasswordReentryPage> {password,widget.config.getKeyAttributes()!,);+ unawaited(UserService.instance.autoAttributePendingSource());_registerSRPForExistingUsers(kek).ignore();} on KeyDerivationError catch (e, s) {_logger.severe("Password verification failed", e, s);diff --git a/mobile/packages/accounts/lib/services/install_source_handler.dart b/mobile/packages/accounts/lib/services/install_source_handler.dartnew file mode 100644index 0000000000..0d68fb34eb--- /dev/null+++ b/mobile/packages/accounts/lib/services/install_source_handler.dart@@ -0,0 +1,15 @@+typedef HasInstallSource = Future<bool> Function();+typedef AutoAttributeSource = Future<void> Function({required bool isSignUp});+typedef AutoAttributePendingSource = Future<void> Function();++class InstallSourceHandler {+ const InstallSourceHandler({+ required this.hasInstallSource,+ required this.autoAttributeSource,+ required this.autoAttributePendingSource,+ });++ final HasInstallSource hasInstallSource;+ final AutoAttributeSource autoAttributeSource;+ final AutoAttributePendingSource autoAttributePendingSource;+}diff --git a/mobile/packages/accounts/lib/services/user_service.dart b/mobile/packages/accounts/lib/services/user_service.dartindex 6064d5b324..c720f0c92c 100644--- a/mobile/packages/accounts/lib/services/user_service.dart+++ b/mobile/packages/accounts/lib/services/user_service.dart@@ -21,6 +21,7 @@ import 'package:ente_accounts/pages/password_reentry_page.dart';import 'package:ente_accounts/pages/recovery_page.dart';import 'package:ente_accounts/pages/two_factor_authentication_page.dart';import 'package:ente_accounts/pages/two_factor_recovery_page.dart';+import 'package:ente_accounts/services/install_source_handler.dart';import 'package:ente_base/models/key_attributes.dart';import 'package:ente_base/models/key_gen_result.dart';import 'package:ente_configuration/base_configuration.dart';@@ -60,14 +61,20 @@ class UserService {late ValueNotifier<String?> emailValueNotifier;late BaseConfiguration _config;late BaseHomePage _homePage;+ InstallSourceHandler? _installSourceHandler;UserService._privateConstructor();static final UserService instance = UserService._privateConstructor();- Future<void> init(BaseConfiguration config, BaseHomePage homePage) async {+ Future<void> init(+ BaseConfiguration config,+ BaseHomePage homePage, {+ InstallSourceHandler? installSourceHandler,+ }) async {_config = config;_homePage = homePage;+ _installSourceHandler = installSourceHandler;emailValueNotifier = ValueNotifier<String?>(config.getEmail());_preferences = await SharedPreferences.getInstance();}@@ -409,6 +416,7 @@ class UserService {userPassword,_config.getKeyAttributes()!,);+ unawaited(autoAttributePendingSource());_config.resetVolatilePassword();page = _homePage;} else {@@ -800,6 +808,7 @@ class UserService {_config.getKeyAttributes()!,keyEncryptionKey: keyEncryptionKey,);+ unawaited(autoAttributePendingSource());_config.resetVolatilePassword();page = _homePage;} else {@@ -1114,6 +1123,20 @@ class UserService {} else {await _config.setToken(responseData["token"]);}+ final isSignUp = responseData["encryptedToken"] == null;+ unawaited(autoAttributeSource(isSignUp: isSignUp));+ }++ Future<bool> hasInstallSource() async {+ return await _installSourceHandler?.hasInstallSource() ?? false;+ }++ Future<void> autoAttributeSource({required bool isSignUp}) async {+ await _installSourceHandler?.autoAttributeSource(isSignUp: isSignUp);+ }++ Future<void> autoAttributePendingSource() async {+ await _installSourceHandler?.autoAttributePendingSource();}bool? canDisableEmailMFA() {diff --git a/mobile/packages/install_source/android/build.gradle b/mobile/packages/install_source/android/build.gradlenew file mode 100644index 0000000000..742121dc69--- /dev/null+++ b/mobile/packages/install_source/android/build.gradle@@ -0,0 +1,71 @@+group 'io.ente.install_source'+version '1.0'++buildscript {+ ext.kotlin_version = '2.1.10'+ repositories {+ google()+ mavenCentral()+ }++ dependencies {+ classpath 'com.android.tools.build:gradle:8.10.1'+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"+ }+}++rootProject.allprojects {+ repositories {+ google()+ mavenCentral()+ }+}++apply plugin: 'com.android.library'+apply plugin: 'kotlin-android'++android {+ namespace 'io.ente.install_source'+ compileSdk 36++ compileOptions {+ sourceCompatibility JavaVersion.VERSION_1_8+ targetCompatibility JavaVersion.VERSION_1_8+ }++ kotlinOptions {+ jvmTarget = '1.8'+ }++ 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'+ }++ flavorDimensions "default"+ productFlavors {+ independent {+ dimension "default"+ }+ dev {+ dimension "default"+ }+ playstore {+ dimension "default"+ }+ fdroid {+ dimension "default"+ }+ }++ defaultConfig {+ minSdkVersion 21+ }+}++dependencies {+ playstoreImplementation 'com.android.installreferrer:installreferrer:2.2'+}diff --git a/mobile/packages/install_source/android/src/main/AndroidManifest.xml b/mobile/packages/install_source/android/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..a2f47b6057--- /dev/null+++ b/mobile/packages/install_source/android/src/main/AndroidManifest.xml@@ -0,0 +1,2 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+</manifest>diff --git a/mobile/packages/install_source/android/src/main/kotlin/io/ente/install_source/EnteInstallSourcePlugin.kt b/mobile/packages/install_source/android/src/main/kotlin/io/ente/install_source/EnteInstallSourcePlugin.ktnew file mode 100644index 0000000000..14ad940966--- /dev/null+++ b/mobile/packages/install_source/android/src/main/kotlin/io/ente/install_source/EnteInstallSourcePlugin.kt@@ -0,0 +1,38 @@+package io.ente.install_source++import io.flutter.embedding.engine.plugins.FlutterPlugin+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel++class EnteInstallSourcePlugin : FlutterPlugin, MethodChannel.MethodCallHandler {+ private lateinit var channel: MethodChannel+ private lateinit var provider: InstallSourceProvider++ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ provider = InstallSourceProvider(binding.applicationContext)+ channel = MethodChannel(binding.binaryMessenger, CHANNEL)+ channel.setMethodCallHandler(this)+ }++ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "hasInstallSource" -> provider.hasInstallSource(result)+ "autoAttributeSource" -> provider.autoAttributeSource(+ call.argument<Boolean>("isSignUp") == true,+ result,+ )++ "getPendingEvents" -> provider.getPendingEvents(result)+ "markEventSent" -> provider.markEventSent(call.argument("event"), result)+ else -> result.notImplemented()+ }+ }++ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel.setMethodCallHandler(null)+ }++ private companion object {+ const val CHANNEL = "io.ente.install_source/install_source"+ }+}diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/InstallSourceEventStore.kt b/mobile/packages/install_source/android/src/main/kotlin/io/ente/install_source/InstallSourceEventStore.ktsimilarity index 96%rename from mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/InstallSourceEventStore.ktrename to mobile/packages/install_source/android/src/main/kotlin/io/ente/install_source/InstallSourceEventStore.ktindex 4179f6356b..bdc0c42b29 100644--- a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/InstallSourceEventStore.kt+++ b/mobile/packages/install_source/android/src/main/kotlin/io/ente/install_source/InstallSourceEventStore.kt@@ -1,4 +1,4 @@-package io.ente.photos+package io.ente.install_sourceimport android.content.Contextimport java.net.URLDecoder@@ -29,15 +29,11 @@ class InstallSourceEventStore(private val context: Context) {put(key, paramsJson.optString(key))}}- InstallSource(- referrerParams = params,- )+ InstallSource(referrerParams = params)}.getOrNull()}- fun playSource(- referrer: String?,- ): InstallSource = InstallSource(+ fun playSource(referrer: String?): InstallSource = InstallSource(referrerParams = parseReferrerParams(referrer),)diff --git a/mobile/apps/photos/android/app/src/noReferrer/kotlin/io/ente/photos/InstallSourceProvider.kt b/mobile/packages/install_source/android/src/noReferrer/kotlin/io/ente/install_source/InstallSourceProvider.ktsimilarity index 96%rename from mobile/apps/photos/android/app/src/noReferrer/kotlin/io/ente/photos/InstallSourceProvider.ktrename to mobile/packages/install_source/android/src/noReferrer/kotlin/io/ente/install_source/InstallSourceProvider.ktindex 9f2529ddaf..10be01998f 100644--- a/mobile/apps/photos/android/app/src/noReferrer/kotlin/io/ente/photos/InstallSourceProvider.kt+++ b/mobile/packages/install_source/android/src/noReferrer/kotlin/io/ente/install_source/InstallSourceProvider.kt@@ -1,4 +1,4 @@-package io.ente.photos+package io.ente.install_sourceimport android.content.Contextimport io.flutter.plugin.common.MethodChanneldiff --git a/mobile/apps/photos/android/app/src/playstore/kotlin/io/ente/photos/InstallSourceProvider.kt b/mobile/packages/install_source/android/src/playstore/kotlin/io/ente/install_source/InstallSourceProvider.ktsimilarity index 99%rename from mobile/apps/photos/android/app/src/playstore/kotlin/io/ente/photos/InstallSourceProvider.ktrename to mobile/packages/install_source/android/src/playstore/kotlin/io/ente/install_source/InstallSourceProvider.ktindex 9025c18b7f..cc5d922d1a 100644--- a/mobile/apps/photos/android/app/src/playstore/kotlin/io/ente/photos/InstallSourceProvider.kt+++ b/mobile/packages/install_source/android/src/playstore/kotlin/io/ente/install_source/InstallSourceProvider.kt@@ -1,4 +1,4 @@-package io.ente.photos+package io.ente.install_sourceimport android.content.Contextimport android.content.pm.PackageManagerdiff --git a/mobile/packages/install_source/lib/ente_install_source.dart b/mobile/packages/install_source/lib/ente_install_source.dartnew file mode 100644index 0000000000..7e56c96478--- /dev/null+++ b/mobile/packages/install_source/lib/ente_install_source.dart@@ -0,0 +1 @@+export 'src/install_source_service.dart';diff --git a/mobile/packages/install_source/lib/src/install_source_service.dart b/mobile/packages/install_source/lib/src/install_source_service.dartnew file mode 100644index 0000000000..8c19263823--- /dev/null+++ b/mobile/packages/install_source/lib/src/install_source_service.dart@@ -0,0 +1,94 @@+import 'dart:convert';+import 'dart:io';++import 'package:dio/dio.dart';+import 'package:flutter/services.dart';+import 'package:logging/logging.dart';++class InstallSourceService {+ InstallSourceService(+ this._enteDio, {+ required String app,+ required String? Function() getToken,+ MethodChannel? methodChannel,+ }) : _app = app,+ _getToken = getToken,+ _methodChannel = methodChannel ?? const MethodChannel(_channelName);++ static const _channelName = 'io.ente.install_source/install_source';+ static const _platformChannelTimeout = Duration(seconds: 3);+ static const _installEvent = 'install';++ final Dio _enteDio;+ final String _app;+ final String? Function() _getToken;+ final MethodChannel _methodChannel;+ final _logger = Logger('InstallSourceService');++ Future<void> autoAttributeSource({required bool isSignUp}) async {+ if (!Platform.isAndroid) {+ return;+ }+ try {+ await _methodChannel+ .invokeMethod<void>('autoAttributeSource', {'isSignUp': isSignUp})+ .timeout(_platformChannelTimeout);+ await autoAttributePendingSource();+ } catch (e, s) {+ _logger.warning('Failed to auto-attribute install source', e, s);+ }+ }++ Future<void> autoAttributePendingSource() async {+ if (!Platform.isAndroid) {+ return;+ }+ try {+ final events =+ await _methodChannel+ .invokeListMethod<String>('getPendingEvents')+ .timeout(_platformChannelTimeout) ??+ const <String>[];+ for (final eventJson in events) {+ await _sendEventJson(eventJson);+ }+ } catch (e, s) {+ _logger.warning('Failed to flush install source events', e, s);+ }+ }++ 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> _sendEventJson(String eventJson) async {+ final event = jsonDecode(eventJson) as Map<String, dynamic>;+ final eventName = event['event'] as String?;+ if (eventName == null) {+ return;+ }+ if (eventName != _installEvent && _getToken() == null) {+ return;+ }+ event['app'] = _app;+ event['platform'] = Platform.operatingSystem;+ await _enteDio.post(+ eventName == _installEvent ? '/events' : '/events/user',+ data: event,+ );+ await _methodChannel.invokeMethod<void>('markEventSent', {+ 'event': eventName,+ });+ }+}diff --git a/mobile/packages/install_source/pubspec.yaml b/mobile/packages/install_source/pubspec.yamlnew file mode 100644index 0000000000..99ba821fcc--- /dev/null+++ b/mobile/packages/install_source/pubspec.yaml@@ -0,0 +1,23 @@+name: ente_install_source+description: Android install-source attribution for Ente apps++resolution: workspace+environment:+ sdk: ">=3.10.0 <4.0.0"+ flutter: ">=1.17.0"++dependencies:+ dio: 5.9.2+ flutter:+ sdk: flutter+ logging: 1.3.0++dev_dependencies:+ flutter_lints: 6.0.0++flutter:+ plugin:+ platforms:+ android:+ package: io.ente.install_source+ pluginClass: EnteInstallSourcePlugindiff --git a/mobile/packages/install_source/scripts/prepare_fdroid_source.sh b/mobile/packages/install_source/scripts/prepare_fdroid_source.shnew file mode 100755index 0000000000..993720a597--- /dev/null+++ b/mobile/packages/install_source/scripts/prepare_fdroid_source.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+set -euo pipefail++cd "$(dirname "$0")/.."++fail() {+ echo "prepare_fdroid_source: $*" >&2+ exit 1+}++remove_play_referrer_dependency() {+ local count+ count=$(rg -c "^[[:space:]]*playstoreImplementation ['\"]com\\.android\\.installreferrer:installreferrer:" android/build.gradle || true)+ [[ "$count" == "1" ]] || fail "expected one Play install referrer dependency in android/build.gradle"+ perl -0pi -e 's/^[[:space:]]*playstoreImplementation ['\''"]com\.android\.installreferrer:installreferrer:[^'\''"]+['\''"]\n//mg' android/build.gradle+}++remove_playstore_sources() {+ rm -rf android/src/playstore/kotlin+}++assert_fdroid_source() {+ if rg -n "com\\.android\\.installreferrer|InstallReferrer(Client|StateListener)|installreferrer" android; then+ fail "Play install referrer dependency or source remains"+ fi+}++remove_play_referrer_dependency+remove_playstore_sources+assert_fdroid_sourcediff --git a/mobile/pubspec.yaml b/mobile/pubspec.yamlindex 5a9f1bee10..7ef5512105 100644--- a/mobile/pubspec.yaml+++ b/mobile/pubspec.yaml@@ -22,6 +22,7 @@ workspace:- packages/ente_crypto_api- packages/ente_crypto_dart_adapter- packages/ente_icons+ - packages/install_source- packages/ente_pure_utils- packages/ente_qr- packages/ente_qr_scanner