Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="mixin.onelink.me"
android:pathPrefix="/rlR3" />
</intent-filter>

<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
Expand Down
32 changes: 32 additions & 0 deletions app/src/main/java/one/mixin/android/MixinApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import com.bugsnag.android.Configuration as BugsnagConfiguration
import com.appsflyer.AppsFlyerLib
import com.appsflyer.share.AppsFlyerConversionListener
import com.appsflyer.share.attribution.AppsFlyerRequestListener
import com.appsflyer.share.deeplink.DeepLinkListener
import com.appsflyer.share.deeplink.DeepLinkResult
import com.google.android.gms.net.CronetProviderInstaller
import com.google.android.gms.tasks.Tasks
import com.google.firebase.analytics.FirebaseAnalytics
Expand All @@ -41,6 +43,7 @@ import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import one.mixin.android.Constants.Account.PREF_APP_AUTH
import one.mixin.android.api.referral.PendingReferralStore
import one.mixin.android.crypto.CryptoWalletHelper
import one.mixin.android.crypto.clearPendingImportMnemonic
import one.mixin.android.crypto.MixinSignalProtocolLogger
Expand Down Expand Up @@ -227,6 +230,35 @@ open class MixinApplication :
return
}
AppsFlyerLib.getInstance().apply {
setDeepLinkTimeout(10_000L)
subscribeForDeepLink(
DeepLinkListener { result ->
when (result.status) {
DeepLinkResult.Status.FOUND -> {
val deepLink = result.deepLink ?: return@DeepLinkListener
Timber.d(
"AppsFlyer UDL found: value=%s, sub1=%s, deferred=%s",
deepLink.deepLinkValue,
deepLink.getStringValue(PendingReferralStore.deepLinkSub1Key()),
deepLink.isDeferred,
)
val referralCode = PendingReferralStore.extractCodeFromDeepLink(
deepLinkValue = deepLink.deepLinkValue,
deepLinkSub1 = deepLink.getStringValue(PendingReferralStore.deepLinkSub1Key()),
)
if (referralCode != null) {
PendingReferralStore.save(this@MixinApplication, referralCode)
}
}
DeepLinkResult.Status.NOT_FOUND -> {
Timber.d("AppsFlyer UDL not found")
}
DeepLinkResult.Status.ERROR -> {
Timber.e("AppsFlyer UDL error: %s", result.error)
}
}
},
)
init(BuildConfig.APPSFLYER_DEV_KEY, object : AppsFlyerConversionListener {
override fun onConversionDataSuccess(conversionData: Map<String, Any>) {
Timber.d("AppsFlyer Conversion Data: $conversionData")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package one.mixin.android.api.referral

import android.content.Context
import androidx.core.content.edit
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.net.URI
import java.util.Locale

object PendingReferralStore {
const val ONELINK_HOST = "mixin.onelink.me"
const val ONELINK_PATH_PREFIX = "/rlR3"

private const val PREFS_NAME = "pending_referral_prefs"
private const val KEY_CODE = "pending_referral_code"
private const val KEY_SAVED_AT = "pending_referral_saved_at"
private const val KEY_SIGN_UP_PENDING = "pending_referral_sign_up_pending"
private const val EXPIRY_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val DEEP_LINK_VALUE_REFERRAL = "referral"
private const val DEEP_LINK_SUB1 = "deep_link_sub1"
private const val PATH_REFERRALS = "referrals"
private const val MIXIN_HOST = "mixin.one"

private val _pendingCodeFlow = MutableStateFlow<String?>(null)
val pendingCodeFlow: StateFlow<String?> = _pendingCodeFlow.asStateFlow()

// True from the first home session after sign-up until the process ends.
private var postSignUpSessionActive = false

fun deepLinkSub1Key(): String = DEEP_LINK_SUB1

fun save(
context: Context,
rawCode: String?,
nowMs: Long = System.currentTimeMillis(),
): Boolean {
val code = normalizeCode(rawCode) ?: return false
prefs(context).edit {
putString(KEY_CODE, code)
putLong(KEY_SAVED_AT, nowMs)
}
_pendingCodeFlow.value = code
return true
}

fun markSignUpCompleted(context: Context) {
prefs(context).edit(commit = true) {
putBoolean(KEY_SIGN_UP_PENDING, true)
}
}

fun getForPostSignUp(
context: Context,
nowMs: Long = System.currentTimeMillis(),
): String? {
val sharedPrefs = prefs(context)
if (sharedPrefs.getBoolean(KEY_SIGN_UP_PENDING, false)) {
sharedPrefs.edit { remove(KEY_SIGN_UP_PENDING) }
postSignUpSessionActive = true
}
if (!postSignUpSessionActive) return null
return get(context, nowMs)
}

internal fun endPostSignUpSessionForTest() {
postSignUpSessionActive = false
}

fun get(
context: Context,
nowMs: Long = System.currentTimeMillis(),
): String? {
val sharedPrefs = prefs(context)
val code = normalizeCode(sharedPrefs.getString(KEY_CODE, null))
if (code == null) {
if (_pendingCodeFlow.value != null) {
_pendingCodeFlow.value = null
}
return null
}
val savedAt = sharedPrefs.getLong(KEY_SAVED_AT, 0L)
if (savedAt <= 0L || nowMs - savedAt > EXPIRY_MILLIS) {
sharedPrefs.edit {
remove(KEY_CODE)
remove(KEY_SAVED_AT)
}
if (_pendingCodeFlow.value != null) {
_pendingCodeFlow.value = null
}
return null
}
if (_pendingCodeFlow.value != code) {
_pendingCodeFlow.value = code
}
return code
}

fun clear(context: Context) {
prefs(context).edit {
clear()
}
postSignUpSessionActive = false
_pendingCodeFlow.value = null
}

fun extractCodeFromDeepLink(
deepLinkValue: String?,
deepLinkSub1: String?,
): String? {
val value = deepLinkValue?.trim().orEmpty()
if (value.equals(DEEP_LINK_VALUE_REFERRAL, ignoreCase = true)) {
return normalizeCode(deepLinkSub1)
}
return extractCodeFromUrl(value)
}

fun extractCodeFromUrl(rawUrl: String?): String? {
val trimmed = rawUrl?.trim()?.takeIf { it.isNotEmpty() } ?: return null
val uri = runCatching { URI(trimmed) }.getOrNull() ?: return null
val scheme = uri.scheme?.lowercase(Locale.US) ?: return null
val host = uri.host?.lowercase(Locale.US) ?: return null
val segments = uri.path.orEmpty().split('/').filter { it.isNotBlank() }

return when {
(scheme == "https" || scheme == "http") && host == MIXIN_HOST -> {
if (segments.size >= 2 && segments[0].equals(PATH_REFERRALS, ignoreCase = true)) {
normalizeCode(segments[1])
} else {
null
}
}
scheme == "mixin" && host == PATH_REFERRALS -> {
normalizeCode(segments.firstOrNull())
}
scheme == "mixin" && host == MIXIN_HOST -> {
if (segments.size >= 2 && segments[0].equals(PATH_REFERRALS, ignoreCase = true)) {
normalizeCode(segments[1])
} else {
null
}
}
else -> null
}
}

fun isOneLinkUrl(rawUrl: String?): Boolean {
val trimmed = rawUrl?.trim()?.takeIf { it.isNotEmpty() } ?: return false
val uri = runCatching { URI(trimmed) }.getOrNull() ?: return false
val path = uri.path.orEmpty()
return uri.scheme.equals("https", ignoreCase = true) &&
uri.host.equals(ONELINK_HOST, ignoreCase = true) &&
(path == ONELINK_PATH_PREFIX || path.startsWith("$ONELINK_PATH_PREFIX/"))
}

fun normalizeCode(raw: String?): String? =
raw?.trim()?.uppercase(Locale.US)?.takeIf { it.isNotEmpty() }

private fun prefs(context: Context) =
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
}
2 changes: 2 additions & 0 deletions app/src/main/java/one/mixin/android/session/Session.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import okio.ByteString.Companion.toByteString
import one.mixin.android.Constants.Account.PREF_TRIED_UPDATE_KEY
import one.mixin.android.Constants.INTERVAL_1_HOUR
import one.mixin.android.MixinApplication
import one.mixin.android.api.referral.PendingReferralStore
import one.mixin.android.crypto.EdKeyPair
import one.mixin.android.crypto.aesDecrypt
import one.mixin.android.crypto.calculateAgreement
Expand Down Expand Up @@ -139,6 +140,7 @@ object Session {
val preference = MixinApplication.appContext.sharedPreferences(PREF_SESSION)
preference.clear()
ThirdPartyUserIdentity.clearUser()
PendingReferralStore.clear(MixinApplication.appContext)
}

fun storeEd25519Seed(token: String) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package one.mixin.android.ui.common.profile

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.View
Expand Down Expand Up @@ -45,6 +46,7 @@ import com.google.android.material.bottomsheet.BottomSheetBehavior
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import one.mixin.android.R
import one.mixin.android.api.referral.PendingReferralStore
import one.mixin.android.api.response.referral.ReferralCodeInfo
import one.mixin.android.compose.theme.MixinAppTheme
import one.mixin.android.extension.getSafeAreaInsetsTop
Expand All @@ -69,18 +71,28 @@ class InputReferralBottomSheetDialogFragment : MixinComposeBottomSheetDialogFrag
companion object {
const val TAG = "InputReferralBottomSheetDialogFragment"
private const val ARG_DEFAULT_VALUE = "default_value"
private const val ARG_IS_POST_SIGN_UP = "is_post_sign_up"

fun newInstance(defaultValue: String = "") =
fun newInstance(
defaultValue: String = "",
isPostSignUp: Boolean = false,
) =
InputReferralBottomSheetDialogFragment().apply {
arguments = Bundle().apply {
putString(ARG_DEFAULT_VALUE, defaultValue)
putBoolean(ARG_IS_POST_SIGN_UP, isPostSignUp)
}
}
}

var onConfirm: ((String) -> Unit)? = null
var onDismissCallback: (() -> Unit)? = null

private var navigatedToPreview = false

private val isPostSignUp: Boolean
get() = arguments?.getBoolean(ARG_IS_POST_SIGN_UP, false) == true

private val viewModel: BottomSheetViewModel by viewModels()

override fun getTheme() = R.style.AppTheme_Dialog
Expand Down Expand Up @@ -146,7 +158,7 @@ class InputReferralBottomSheetDialogFragment : MixinComposeBottomSheetDialogFrag
) {
Spacer(Modifier.height(30.dp))
Text(
text = stringResource(R.string.apply_referral_code),
text = stringResource(if (isPostSignUp) R.string.referred_by_a_friend else R.string.apply_referral_code),
fontSize = 22.sp,
fontWeight = FontWeight.W600,
color = MixinAppTheme.colors.textPrimary,
Expand Down Expand Up @@ -211,9 +223,15 @@ class InputReferralBottomSheetDialogFragment : MixinComposeBottomSheetDialogFrag
val inviter = viewModel.refreshUser(info.inviterUserId)
uiState = UiState.Initial
if (inviter != null) {
navigatedToPreview = true
this@InputReferralBottomSheetDialogFragment.dismiss()
ReferralBindPreviewBottomSheetDialogFragment
.newInstance(code, inviter, info.inviteePercent)
.newInstance(
code = code,
inviter = inviter,
inviteePercent = info.inviteePercent,
clearPendingOnResult = isPostSignUp,
)
.showNow(parentFragmentManager, ReferralBindPreviewBottomSheetDialogFragment.TAG)
} else {
uiState = UiState.Failure(getString(R.string.Data_error))
Expand All @@ -236,7 +254,7 @@ class InputReferralBottomSheetDialogFragment : MixinComposeBottomSheetDialogFrag

Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.Later),
text = stringResource(if (isPostSignUp) R.string.Cancel else R.string.Later),
color = MixinAppTheme.colors.accent,
fontSize = 16.sp,
fontWeight = FontWeight.W500,
Expand Down Expand Up @@ -298,6 +316,13 @@ class InputReferralBottomSheetDialogFragment : MixinComposeBottomSheetDialogFrag
super.onDestroyView()
}

override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
if (isPostSignUp && !navigatedToPreview && activity?.isChangingConfigurations != true) {
context?.let(PendingReferralStore::clear)
}
}

override fun onDetach() {
super.onDetach()
// UrlInterpreterActivity doesn't have a UI and needs it's son fragment to handle it's finish.
Expand Down
Loading