π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob] Automate referral source where available
Neeraj Guptacf756cfb8b47
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.ktindex 03aa887a8b..64c5e932b2 100644--- 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@@ -1,15 +1,11 @@package io.ente.photosimport android.content.Context-import android.content.pm.PackageInfo-import android.os.Buildimport java.net.URLDecoderimport java.util.UUIDimport org.json.JSONObjectdata class InstallSource(- val channel: String,- val platform: String,val referrerParams: Map<String, String>,) {val hasReferrer: Boolean get() = referrerParams.isNotEmpty()@@ -29,83 +25,87 @@ class InstallSourceEventStore(private val context: Context) {}}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- )+ .putInt(KEY_FLAGS, sourceFlags(source)).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()+ fun autoAttributeSource(isSignUp: Boolean) {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)+ .putInt(KEY_FLAGS, flags or if (isSignUp) FLAG_SIGNED_UP else FLAG_LOGGED_IN).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"+ fun pendingEventJsons(source: InstallSource): List<String> {+ if (!source.hasReferrer) {+ return emptyList()+ }+ val eventId = eventId()+ return buildList {+ if (!flags.hasFlag(FLAG_SENT_INSTALL_SOURCE)) {+ add(buildEvent(source, eventId, EVENT_INSTALL).toString())+ }+ if (!flags.hasFlag(FLAG_LINKED_INSTALL_SOURCE)) {+ userEvent()?.let {+ add(buildEvent(source, eventId, it).toString())+ }+ }}}- 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)))+ fun markEventSent(event: String) {+ when {+ event == EVENT_INSTALL -> prefs.edit()+ .putInt(KEY_FLAGS, flags or FLAG_SENT_INSTALL_SOURCE)+ .apply()+ isUserEvent(event) -> prefs.edit()+ .putInt(KEY_FLAGS, flags or FLAG_LINKED_INSTALL_SOURCE)+ .apply()+ }}+ private fun buildEvent(source: InstallSource, eventId: String, event: String): JSONObject =+ JSONObject()+ .put("id", eventId)+ .put("event", event)+ .put(+ "data",+ if (event == EVENT_INSTALL) JSONObject(source.referrerParams) else JSONObject()+ )++ private fun eventId(): String =+ prefs.getString(KEY_EVENT_ID, null) ?: UUID.randomUUID().toString().also {+ prefs.edit().putString(KEY_EVENT_ID, it).apply()+ }++ private fun sourceFlags(source: InstallSource): Int {+ val sourceFlag = if (source.hasReferrer) FLAG_HAS_INSTALL_SOURCE else FLAG_NO_INSTALL_SOURCE+ return (flags and SOURCE_FLAGS.inv()) or sourceFlag+ }++ private fun userEvent(): String? =+ when {+ flags.hasFlag(FLAG_SIGNED_UP) -> EVENT_SIGN_UP+ flags.hasFlag(FLAG_LOGGED_IN) -> EVENT_LOG_IN+ else -> null+ }++ private fun isUserEvent(event: String): Boolean =+ event == EVENT_SIGN_UP || event == EVENT_LOG_IN+private fun parseReferrerParams(referrer: String?): Map<String, String> {val query = referrer?.trim()?.removePrefix("?")if (query.isNullOrEmpty()) {@@ -131,36 +131,28 @@ class InstallSourceEventStore(private val context: Context) {}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 EVENT_INSTALL = "install"+ private const val EVENT_LOG_IN = "log_in"+ private const val EVENT_SIGN_UP = "sign_up"+ private const val FLAG_HAS_INSTALL_SOURCE = 1 shl 0+ private const val FLAG_NO_INSTALL_SOURCE = 1 shl 1+ private const val FLAG_SENT_INSTALL_SOURCE = 1 shl 2+ private const val FLAG_LOGGED_IN = 1 shl 3+ private const val FLAG_SIGNED_UP = 1 shl 4+ private const val FLAG_LINKED_INSTALL_SOURCE = 1 shl 5+ private const val SOURCE_FLAGS = FLAG_HAS_INSTALL_SOURCE or FLAG_NO_INSTALL_SOURCE+ private const val KEY_EVENT_ID = "event_id"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.ktindex 63151a2b58..b35f615b2f 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@@ -3,23 +3,11 @@ package io.ente.photosimport android.content.Intentimport io.flutter.embedding.android.FlutterFragmentActivityimport io.flutter.embedding.engine.FlutterEngine-import io.flutter.plugin.common.MethodChannelclass 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()- }- }+ NativeChannels.register(this, flutterEngine)}override fun onNewIntent(intent: Intent) {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.ktnew file mode 100644index 0000000000..e48e0016ee--- /dev/null+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/NativeChannels.kt@@ -0,0 +1,39 @@+package io.ente.photos++import android.content.Context+import io.flutter.embedding.engine.FlutterEngine+import io.flutter.plugin.common.BinaryMessenger+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel++object NativeChannels {+ fun register(context: Context, flutterEngine: FlutterEngine) {+ val messenger = flutterEngine.dartExecutor.binaryMessenger+ InstallSourceChannel(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"+ }+}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.ktindex b001729485..9f2529ddaf 100644--- 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@@ -7,11 +7,21 @@ class InstallSourceProvider(context: Context) {private val store = InstallSourceEventStore(context)fun hasInstallSource(result: MethodChannel.Result) {+ store.saveSource(InstallSource(emptyMap()))result.success(false)}- fun logInstallSource(result: MethodChannel.Result) {- val source = store.sourceFromState() ?: store.fallbackSource()- result.success(store.logInstallSource(source))+ fun autoAttributeSource(isSignUp: Boolean, result: MethodChannel.Result) {+ store.saveSource(InstallSource(emptyMap()))+ store.autoAttributeSource(isSignUp)+ result.success(null)+ }++ fun getPendingEvents(result: MethodChannel.Result) {+ result.success(emptyList<String>())+ }++ fun markEventSent(event: String?, result: MethodChannel.Result) {+ result.success(null)}}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.ktindex 8cdfb506de..2c4d30a9c5 100644--- 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@@ -20,12 +20,22 @@ class InstallSourceProvider(private val context: Context) {}}- fun logInstallSource(result: MethodChannel.Result) {+ fun autoAttributeSource(isSignUp: Boolean, result: MethodChannel.Result) {+ store.autoAttributeSource(isSignUp)+ result.success(null)+ }++ fun getPendingEvents(result: MethodChannel.Result) {getInstallSource { source ->- result.success(source?.let { store.logInstallSource(it) })+ result.success(source?.let { store.pendingEventJsons(it) }.orEmpty())}}+ fun markEventSent(event: String?, result: MethodChannel.Result) {+ store.markEventSent(event.orEmpty())+ result.success(null)+ }+@Synchronizedprivate fun getInstallSource(callback: (InstallSource?) -> Unit) {val source = cachedSource ?: store.sourceFromState()diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dartindex 93dd6913ef..7c16fdce40 100644--- a/mobile/apps/photos/lib/main.dart+++ b/mobile/apps/photos/lib/main.dart@@ -36,7 +36,6 @@ 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';@@ -190,7 +189,12 @@ Future<void> _warmForegroundDeferredServices() async {} catch (e, s) {_logger.warning("Deferred MemoryLaneService warm failed", e, s);}- await InstallSourceService.instance.logSource();+ unawaited(+ Future.delayed(+ const Duration(seconds: 5),+ installSourceService.autoAttributePendingSource,+ ),+ );}ThemeMode _themeMode(AdaptiveThemeMode? savedThemeMode) {diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dartindex be984d86c6..94dc3e3a2b 100644--- a/mobile/apps/photos/lib/service_locator.dart+++ b/mobile/apps/photos/lib/service_locator.dart@@ -25,6 +25,7 @@ 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";@@ -285,6 +286,14 @@ WrappedCacheService get wrappedCacheService {return _wrappedCacheService!;}+InstallSourceService? _installSourceService;+InstallSourceService get installSourceService {+ _installSourceService ??= InstallSourceService(+ ServiceLocator.instance.enteDio,+ );+ return _installSourceService!;+}+// GatewaysPushGateway? _pushGateway;PushGateway get pushGateway {diff --git a/mobile/apps/photos/lib/services/account/user_service.dart b/mobile/apps/photos/lib/services/account/user_service.dartindex c98f2e07b0..f90d1d3426 100644--- a/mobile/apps/photos/lib/services/account/user_service.dart+++ b/mobile/apps/photos/lib/services/account/user_service.dart@@ -378,6 +378,7 @@ class UserService {userPassword,Configuration.instance.getKeyAttributes()!,);+ unawaited(installSourceService.autoAttributePendingSource());} else {throw Exception("unexpected response during passkey verification");}@@ -708,6 +709,7 @@ class UserService {Configuration.instance.getKeyAttributes()!,keyEncryptionKey: keyEncryptionKey,);+ unawaited(installSourceService.autoAttributePendingSource());await flagService.tryRefreshFlags();Configuration.instance.resetVolatilePassword();page = const HomeWidget();@@ -1206,6 +1208,8 @@ class UserService {} else {await Configuration.instance.setToken(responseData["token"]);}+ final isSignUp = responseData["encryptedToken"] == null;+ unawaited(installSourceService.autoAttributeSource(isSignUp: isSignUp));// Initialize shared feed cutoff at login; feed path keeps the same fallback.localSettings.getOrCreateSharedPhotoFeedCutoffTime();diff --git a/mobile/apps/photos/lib/services/install_source_service.dart b/mobile/apps/photos/lib/services/install_source_service.dartindex 972f503d91..00efe96084 100644--- a/mobile/apps/photos/lib/services/install_source_service.dart+++ b/mobile/apps/photos/lib/services/install_source_service.dart@@ -1,20 +1,53 @@+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._privateConstructor();-- static final InstallSourceService instance =- InstallSourceService._privateConstructor();+ 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> logSource() => _logSource();+ 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) {@@ -31,19 +64,24 @@ class InstallSourceService {}}- Future<void> _logSource() async {- if (!Platform.isAndroid) {+ Future<void> _sendEventJson(String eventJson) async {+ final event = jsonDecode(eventJson) as Map<String, dynamic>;+ final eventName = event["event"] as String?;+ if (eventName == null) {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);+ 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/lib/ui/account/email_entry_page.dart b/mobile/apps/photos/lib/ui/account/email_entry_page.dartindex cc3e0291d6..6bf4dab852 100644--- a/mobile/apps/photos/lib/ui/account/email_entry_page.dart+++ b/mobile/apps/photos/lib/ui/account/email_entry_page.dart@@ -5,8 +5,8 @@ import 'package:flutter/material.dart';import 'package:password_strength/password_strength.dart';import 'package:photos/core/configuration.dart';import "package:photos/generated/l10n.dart";+import "package:photos/service_locator.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";@@ -314,8 +314,7 @@ class _EmailEntryPageState extends State<EmailEntryPage> {String get _routeSource => widget.referralSource?.trim() ?? '';Future<void> _updateReferralSourceFieldVisibility() async {- final hasInstallSource = await InstallSourceService.instance- .hasInstallSource();+ final hasInstallSource = await installSourceService.hasInstallSource();_setHasInstallSource(hasInstallSource);}@@ -326,8 +325,7 @@ class _EmailEntryPageState extends State<EmailEntryPage> {if (_hasInstallSource) {return _routeSource;}- final hasInstallSource = await InstallSourceService.instance- .hasInstallSource();+ final hasInstallSource = await installSourceService.hasInstallSource();_setHasInstallSource(hasInstallSource);return hasInstallSource ? _routeSource : _referralSource;}diff --git a/mobile/apps/photos/lib/ui/account/password_reentry_page.dart b/mobile/apps/photos/lib/ui/account/password_reentry_page.dartindex d876171fed..afd9e68489 100644--- a/mobile/apps/photos/lib/ui/account/password_reentry_page.dart+++ b/mobile/apps/photos/lib/ui/account/password_reentry_page.dart@@ -111,6 +111,7 @@ class _PasswordReentryPageState extends State<PasswordReentryPage> {password,Configuration.instance.getKeyAttributes()!,);+ unawaited(installSourceService.autoAttributePendingSource());_registerSRPForExistingUsers(kek).ignore();} on KeyDerivationError catch (e, s) {_logger.severe("Password verification failed", e, s);diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex f8e2546efd..e840943513 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -182,6 +182,7 @@ func main() {legacyKitRepository := &legacykitrepo.Repository{DB: db}notificationHistoryRepo := &repo.NotificationHistoryRepository{DB: db}+ eventRepository := &repo.EventRepository{DB: db}queueRepo := &repo.QueueRepository{DB: db}objectRepo := &repo.ObjectRepository{DB: db, LatencySensitiveDB: latencySensitiveDB, QueueRepo: queueRepo}objectCleanupRepo := &repo.ObjectCleanupRepository{DB: db}@@ -568,6 +569,9 @@ func main() {timeout.WithHandler(healthCheckHandler.PingDBStats),timeout.WithResponse(timeOutResponse),))+ eventHandler := &api.EventHandler{Repo: eventRepository}+ publicAPI.POST("/events", eventHandler.Create)+ privateAPI.POST("/events/user", eventHandler.CreateForUser)fileCopyCtrl := &file_copy.FileCopyController{FileController: fileController,CollectionCtrl: collectionController,diff --git a/server/ente/event.go b/server/ente/event.gonew file mode 100644index 0000000000..ae30076280--- /dev/null+++ b/server/ente/event.go@@ -0,0 +1,15 @@+package ente++const (+ EventInstall = "install"+ EventSignUp = "sign_up"+ EventLogIn = "log_in"+)++type EventRequest struct {+ ID string `json:"id" binding:"required"`+ Event string `json:"event" binding:"required"`+ App string `json:"app" binding:"required"`+ Platform string `json:"platform" binding:"required"`+ Data map[string]interface{} `json:"data" binding:"required"`+}diff --git a/server/internal/testutil/testutil.go b/server/internal/testutil/testutil.goindex 751215dfff..2fd092c710 100644--- a/server/internal/testutil/testutil.go+++ b/server/internal/testutil/testutil.go@@ -118,6 +118,7 @@ func ResetTables(t *testing.T, db *sql.DB) {_, err := db.Exec(`TRUNCATE TABLEnotification_history,+ events,task_lock,storage_bonus,referral_codes,diff --git a/server/migrations/124_events.down.sql b/server/migrations/124_events.down.sqlnew file mode 100644index 0000000000..2c047d42c3--- /dev/null+++ b/server/migrations/124_events.down.sql@@ -0,0 +1,4 @@+DROP TRIGGER IF EXISTS update_events_updated_at ON events;+DROP INDEX IF EXISTS events_user_id_idx;+DROP INDEX IF EXISTS events_id_event_idx;+DROP TABLE IF EXISTS events;diff --git a/server/migrations/124_events.up.sql b/server/migrations/124_events.up.sqlnew file mode 100644index 0000000000..055d40bc1c--- /dev/null+++ b/server/migrations/124_events.up.sql@@ -0,0 +1,20 @@+CREATE TABLE IF NOT EXISTS events (+ id TEXT NOT NULL,+ event TEXT NOT NULL,+ app TEXT NOT NULL,+ platform TEXT NOT NULL,+ data JSONB NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(data) = 'object'),+ user_id BIGINT,+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds()+);++CREATE UNIQUE INDEX IF NOT EXISTS events_id_event_idx ON events(id, event);+CREATE INDEX IF NOT EXISTS events_user_id_idx ON events(user_id);++CREATE TRIGGER update_events_updated_at+ BEFORE UPDATE+ ON events+ FOR EACH ROW+EXECUTE PROCEDURE+ trigger_updated_at_microseconds_column();diff --git a/server/pkg/api/event.go b/server/pkg/api/event.gonew file mode 100644index 0000000000..86e5fd7c7f--- /dev/null+++ b/server/pkg/api/event.go@@ -0,0 +1,91 @@+package api++import (+ "net/http"++ "github.com/ente-io/museum/ente"+ "github.com/ente-io/museum/pkg/repo"+ "github.com/ente-io/museum/pkg/utils/auth"+ "github.com/ente-io/museum/pkg/utils/handler"+ "github.com/ente-io/stacktrace"+ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+)++type EventHandler struct {+ Repo *repo.EventRepository+}++func (h *EventHandler) Create(c *gin.Context) {+ request, ok := bindEventRequest(c)+ if !ok {+ return+ }+ if request.Event != ente.EventInstall {+ handler.Error(c, ente.NewBadRequestWithMessage("invalid event"))+ return+ }+ data := enrichEventData(c, request.Data)+ if err := h.Repo.Insert(c, request.ID, request.Event, request.App, request.Platform, data, nil); err != nil {+ handler.Error(c, stacktrace.Propagate(err, "failed to create event"))+ return+ }+ c.Status(http.StatusOK)+}++func (h *EventHandler) CreateForUser(c *gin.Context) {+ request, ok := bindEventRequest(c)+ if !ok {+ return+ }+ if request.Event != ente.EventSignUp && request.Event != ente.EventLogIn {+ handler.Error(c, ente.NewBadRequestWithMessage("invalid event"))+ return+ }+ userID := auth.GetUserID(c.Request.Header)+ installData, found, err := h.Repo.GetData(c, request.ID, ente.EventInstall)+ if err != nil {+ handler.Error(c, stacktrace.Propagate(err, "failed to read install event"))+ return+ }+ data := map[string]interface{}{}+ if found {+ data = installData+ }+ for key, value := range request.Data {+ data[key] = value+ }+ data = enrichEventData(c, data)+ if err := h.Repo.Insert(c, request.ID, request.Event, request.App, request.Platform, data, &userID); err != nil {+ handler.Error(c, stacktrace.Propagate(err, "failed to create user event"))+ return+ }+ c.Status(http.StatusOK)+}++func bindEventRequest(c *gin.Context) (ente.EventRequest, bool) {+ var request ente.EventRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "request binding failed %s", err))+ return request, false+ }+ if _, err := uuid.Parse(request.ID); err != nil {+ handler.Error(c, ente.NewBadRequestWithMessage("invalid id"))+ return request, false+ }+ if request.Data == nil {+ handler.Error(c, ente.NewBadRequestWithMessage("data is required"))+ return request, false+ }+ return request, true+}++func enrichEventData(c *gin.Context, data map[string]interface{}) map[string]interface{} {+ delete(data, "app")+ delete(data, "platform")+ version := c.GetHeader("X-Client-Version")+ if version != "" {+ data["app_version"] = version+ }+ return data+}diff --git a/server/pkg/api/event_test.go b/server/pkg/api/event_test.gonew file mode 100644index 0000000000..ad3d9fd55c--- /dev/null+++ b/server/pkg/api/event_test.go@@ -0,0 +1,189 @@+package api++import (+ "bytes"+ "database/sql"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strconv"+ "testing"++ "github.com/ente-io/museum/internal/testutil"+ "github.com/ente-io/museum/pkg/repo"+ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+)++func TestCreateEventStoresInstallWithServerMetadata(t *testing.T) {+ handler, db := setupEventHandlerTest(t)+ id := uuid.New().String()++ recorder := performEventRequest(t, "/events", handler.Create, nil, map[string]any{+ "id": id,+ "event": "install",+ "data": map[string]any{+ "utm_source": "newsletter",+ "app": "ignored",+ "platform": "ignored",+ },+ })++ if recorder.Code != http.StatusOK {+ t.Fatalf("unexpected status code: got %d want %d; body=%s", recorder.Code, http.StatusOK, recorder.Body.String())+ }+ row := fetchEvent(t, db, id, "install")+ if row.data["utm_source"] != "newsletter" ||+ row.data["app_version"] != "1.2.3" {+ t.Fatalf("unexpected data: %+v", row.data)+ }+ if row.app != "photos" || row.platform != "android" {+ t.Fatalf("unexpected app/platform: app=%s platform=%s", row.app, row.platform)+ }+ if _, ok := row.data["app"]; ok {+ t.Fatalf("app duplicated in data: %+v", row.data)+ }+ if _, ok := row.data["platform"]; ok {+ t.Fatalf("platform duplicated in data: %+v", row.data)+ }+ if row.userID.Valid {+ t.Fatalf("install user_id = %d, want null", row.userID.Int64)+ }+}++func TestCreateUserEventCopiesInstallData(t *testing.T) {+ handler, db := setupEventHandlerTest(t)+ id := uuid.New().String()++ performEventRequest(t, "/events", handler.Create, nil, map[string]any{+ "id": id,+ "event": "install",+ "data": map[string]any{+ "utm_source": "newsletter",+ },+ })+ recorder := performEventRequest(t, "/events/user", handler.CreateForUser, int64Ptr(101), map[string]any{+ "id": id,+ "event": "sign_up",+ "data": map[string]any{},+ })++ if recorder.Code != http.StatusOK {+ t.Fatalf("unexpected status code: got %d want %d; body=%s", recorder.Code, http.StatusOK, recorder.Body.String())+ }+ row := fetchEvent(t, db, id, "sign_up")+ if row.data["utm_source"] != "newsletter" ||+ row.data["app_version"] != "1.2.3" {+ t.Fatalf("unexpected data: %+v", row.data)+ }+ if row.app != "photos" || row.platform != "android" {+ t.Fatalf("unexpected app/platform: app=%s platform=%s", row.app, row.platform)+ }+ if !row.userID.Valid || row.userID.Int64 != 101 {+ t.Fatalf("sign_up user_id = %+v, want 101", row.userID)+ }+}++func TestCreateEventDuplicateIsNoOp(t *testing.T) {+ handler, db := setupEventHandlerTest(t)+ id := uuid.New().String()+ body := map[string]any{+ "id": id,+ "event": "install",+ "data": map[string]any{+ "utm_source": "first",+ },+ }++ first := performEventRequest(t, "/events", handler.Create, nil, body)+ body["data"] = map[string]any{"utm_source": "second"}+ second := performEventRequest(t, "/events", handler.Create, nil, body)++ if first.Code != http.StatusOK || second.Code != http.StatusOK {+ t.Fatalf("unexpected status codes: first=%d second=%d", first.Code, second.Code)+ }+ row := fetchEvent(t, db, id, "install")+ if row.data["utm_source"] != "first" {+ t.Fatalf("duplicate mutated data: %+v", row.data)+ }+}++func setupEventHandlerTest(t *testing.T) (*EventHandler, *sql.DB) {+ t.Helper()++ testutil.WithServerRoot(t)++ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ return &EventHandler{+ Repo: &repo.EventRepository{DB: db},+ }, db+}++func performEventRequest(+ t *testing.T,+ route string,+ handler gin.HandlerFunc,+ userID *int64,+ body map[string]any,+) *httptest.ResponseRecorder {+ t.Helper()++ gin.SetMode(gin.TestMode)++ if _, ok := body["app"]; !ok {+ body["app"] = "photos"+ }+ if _, ok := body["platform"]; !ok {+ body["platform"] = "android"+ }+ payload, err := json.Marshal(body)+ if err != nil {+ t.Fatalf("failed to marshal request body: %v", err)+ }++ recorder := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, route, bytes.NewReader(payload))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-Client-Package", "io.ente.photos")+ req.Header.Set("X-Client-Version", "1.2.3")+ if userID != nil {+ req.Header.Set("X-Auth-User-ID", strconv.FormatInt(*userID, 10))+ }++ router := gin.New()+ router.POST(route, handler)+ router.ServeHTTP(recorder, req)++ return recorder+}++type storedEvent struct {+ data map[string]any+ app string+ platform string+ userID sql.NullInt64+}++func fetchEvent(t *testing.T, db *sql.DB, id string, event string) storedEvent {+ t.Helper()++ var row storedEvent+ var raw []byte+ err := db.QueryRow(`SELECT data, app, platform, user_id FROM events WHERE id = $1 AND event = $2`, id, event).Scan(&raw, &row.app, &row.platform, &row.userID)+ if err != nil {+ t.Fatalf("failed to fetch event: %v", err)+ }+ if err := json.Unmarshal(raw, &row.data); err != nil {+ t.Fatalf("failed to unmarshal data: %v", err)+ }+ return row+}++func int64Ptr(v int64) *int64 {+ return &v+}diff --git a/server/pkg/middleware/event_test.go b/server/pkg/middleware/event_test.gonew file mode 100644index 0000000000..89db2a2e8b--- /dev/null+++ b/server/pkg/middleware/event_test.go@@ -0,0 +1,22 @@+package middleware++import (+ "net/http"+ "testing"++ util "github.com/ente-io/museum/pkg/utils"+ "github.com/stretchr/testify/require"+)++func TestShouldSkipBodyLogForEvents(t *testing.T) {+ require.True(t, shouldSkipBodyLog(http.MethodPost, "/events"))+ require.True(t, shouldSkipBodyLog(http.MethodPost, "/events/user"))+ require.False(t, shouldSkipBodyLog(http.MethodGet, "/events"))+}++func TestEventsUsePublicRouteRateLimit(t *testing.T) {+ limit := util.NewRateLimiter("10-M")+ rateLimiter := &RateLimitMiddleware{limit10ReqPerMin: limit}++ require.Same(t, limit, rateLimiter.getLimiter("/events", http.MethodPost))+}diff --git a/server/pkg/middleware/rate_limit.go b/server/pkg/middleware/rate_limit.goindex 556f20b377..a6e4cb6117 100644--- a/server/pkg/middleware/rate_limit.go+++ b/server/pkg/middleware/rate_limit.go@@ -217,6 +217,7 @@ func (r *RateLimitMiddleware) getLimiter(reqPath string, reqMethod string) *limireturn r.limit500ReqPerMin}if reqPath == "/users/ott" ||+ reqPath == "/events" ||reqPath == "/users/verify-email" ||reqPath == "/users/change-email" ||reqPath == "/paste/create" ||diff --git a/server/pkg/middleware/request_logger.go b/server/pkg/middleware/request_logger.goindex 6dbe1c75d6..b5864fa01b 100644--- a/server/pkg/middleware/request_logger.go+++ b/server/pkg/middleware/request_logger.go@@ -51,6 +51,9 @@ func shouldSkipBodyLog(method string, path string) bool {if path == "/admin/user/terminate-session" {return true}+ if method == http.MethodPost && (path == "/events" || path == "/events/user") {+ return true+ }if method == http.MethodPost && (path == "/paste/create" || path == "/paste/guard" || path == "/paste/consume") {return true}diff --git a/server/pkg/repo/event.go b/server/pkg/repo/event.gonew file mode 100644index 0000000000..ca748c9111--- /dev/null+++ b/server/pkg/repo/event.go@@ -0,0 +1,45 @@+package repo++import (+ "context"+ "database/sql"+ "encoding/json"++ "github.com/ente-io/stacktrace"+)++type EventRepository struct {+ DB *sql.DB+}++func (r *EventRepository) Insert(ctx context.Context, id string, event string, app string, platform string, data map[string]interface{}, userID *int64) error {+ payload, err := json.Marshal(data)+ if err != nil {+ return stacktrace.Propagate(err, "failed to marshal event data")+ }+ _, err = r.DB.ExecContext(ctx, `INSERT INTO events(id, event, app, platform, data, user_id)+ VALUES($1, $2, $3, $4, $5, $6)+ ON CONFLICT (id, event) DO NOTHING`, id, event, app, platform, string(payload), userID)+ return stacktrace.Propagate(err, "failed to insert event")+}++func (r *EventRepository) GetData(ctx context.Context, id string, event string) (map[string]interface{}, bool, error) {+ var raw []byte+ err := r.DB.QueryRowContext(ctx, `SELECT data FROM events WHERE id = $1 AND event = $2`, id, event).Scan(&raw)+ if err == sql.ErrNoRows {+ return nil, false, nil+ }+ if err != nil {+ return nil, false, stacktrace.Propagate(err, "failed to fetch event data")+ }+ var data map[string]interface{}+ if len(raw) > 0 {+ if err := json.Unmarshal(raw, &data); err != nil {+ return nil, false, stacktrace.Propagate(err, "failed to unmarshal event data")+ }+ }+ if data == nil {+ data = map[string]interface{}{}+ }+ return data, true, nil+}