Skip to content

Jetpack REST connection: Finalize #22133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 92 commits into from
Aug 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
92 commits
Select commit Hold shift + click to select a range
da347ce
Skip wp.com login if access token exists
nbradbury Aug 12, 2025
c95fa12
First pass at installing Jetpack
nbradbury Aug 12, 2025
f9dba6f
Second pass at installing Jetpack
nbradbury Aug 12, 2025
03f85e7
First pass at handling error response
nbradbury Aug 12, 2025
74f5f45
Return a pair for installJetpack and restored launch wpcom login from…
nbradbury Aug 12, 2025
a298f39
Added InstallJetpackResult to make it clear the second item in the pa…
nbradbury Aug 12, 2025
d15a2bb
Added InstallJetpackResult to make it clear the second item in the pa…
nbradbury Aug 12, 2025
8d426ca
refresh the site before starting jetpack install
nbradbury Aug 12, 2025
ae6eaa3
Fixed detekt warnings, fetch site directly
nbradbury Aug 12, 2025
f72cc1f
Added/updated comments
nbradbury Aug 12, 2025
b2f520b
Merge branch 'trunk' of https://github.com/wordpress-mobile/WordPress…
nbradbury Aug 12, 2025
fe56a2e
Handle inactive Jetpack install, refresh site in init
nbradbury Aug 12, 2025
1ee7396
Tweaked comments
nbradbury Aug 12, 2025
1cc674f
Restored check for access token
nbradbury Aug 12, 2025
2c1a58a
Check if we need to install or simply activate the jp plugin
nbradbury Aug 12, 2025
1237bc9
Simplified JetpackInstaller to always install the plugin
nbradbury Aug 12, 2025
c171b36
Increased timeout
nbradbury Aug 12, 2025
d1b59a1
Fixed Detekt warnings
nbradbury Aug 12, 2025
974941a
Merge branch 'trunk' into feature/jetpack-connect-install
nbradbury Aug 12, 2025
b5b7cbc
Simplified JetpackInstaller.kt
nbradbury Aug 12, 2025
a5ac0b4
Simplified JetpackInstaller.kt, p2
nbradbury Aug 12, 2025
5e4aa19
Added log message
nbradbury Aug 12, 2025
fe48169
Get plugin status before activating
nbradbury Aug 12, 2025
6af0b6c
Use correct names for slugs
nbradbury Aug 13, 2025
6354253
Removed iOS commented code
nbradbury Aug 13, 2025
8c4dca1
Reduced timeout from 60 to 45 seconds
nbradbury Aug 13, 2025
e19e769
Simplified installer
nbradbury Aug 13, 2025
ca4efc5
Code cleanup
nbradbury Aug 13, 2025
2a163dd
Removed refreshSite
nbradbury Aug 13, 2025
89ac854
Merge branch 'trunk' into feature/jetpack-connect-install
nbradbury Aug 13, 2025
d705d4c
Pass WpApiClient as a parameter
nbradbury Aug 13, 2025
f7f49ff
Added missing space
nbradbury Aug 13, 2025
7d7d38b
Use a Result<PluginStatus> for installJetpack
nbradbury Aug 13, 2025
4baf46d
Add a delay to wp.com login if already logged in
nbradbury Aug 13, 2025
bbccb48
Removed unnecessary launch
nbradbury Aug 13, 2025
b601a0c
Suppress TooGenericExceptionCaught
nbradbury Aug 13, 2025
b59b354
Merge branch 'trunk' into feature/jetpack-connect-install
nbradbury Aug 13, 2025
b6b0eb8
Moved JetpackConnectionHelper to its own helper class
nbradbury Aug 13, 2025
2f25831
Connect Jetpack to site
nbradbury Aug 13, 2025
61757f3
Handle failure
nbradbury Aug 13, 2025
3f2aa5a
Added fun to connect user
nbradbury Aug 13, 2025
dc18965
Added error handling to connect user
nbradbury Aug 13, 2025
9ee69c6
Updated error handling to connect user
nbradbury Aug 13, 2025
615f0c9
Remove extra message from all errors except ErrorType.Unknown
nbradbury Aug 13, 2025
860cd15
Throw exception on invalid authentication
nbradbury Aug 13, 2025
078494b
Simplified JetpackConnectionHelper.kt
nbradbury Aug 13, 2025
59676e7
Simplified JetpackConnector
nbradbury Aug 13, 2025
c94134f
Code tweaks
nbradbury Aug 13, 2025
eaa9003
Further simplified JetpackConnector.kt
nbradbury Aug 13, 2025
7a2dcd1
Modified text & icon for user connection step
nbradbury Aug 13, 2025
b28a408
Merge branch 'trunk' into feature/jetpack-connect-site-and-user
nbradbury Aug 13, 2025
cdbe695
Clarified that REST credentials are required
nbradbury Aug 13, 2025
086d881
Corrected ConnectUser step completion
nbradbury Aug 13, 2025
ff4f1fb
Corrected ConnectUser step failure
nbradbury Aug 13, 2025
35e77b0
Removed unnecessary job?.cancel
nbradbury Aug 14, 2025
6c03ee4
Merge branch 'trunk' of https://github.com/wordpress-mobile/WordPress…
nbradbury Aug 14, 2025
328139a
Minor code cleanup
nbradbury Aug 14, 2025
76734d0
Added skeleton for finalization
nbradbury Aug 14, 2025
88d58dd
Handle Done click separately
nbradbury Aug 14, 2025
1665a55
Remove "Simulated" from screen title
nbradbury Aug 14, 2025
ddbd8a1
Pass the connection source to the activity and retain it in the view …
nbradbury Aug 14, 2025
6f68ccb
First pass at activating stats module
nbradbury Aug 14, 2025
232433f
Second pass at activating stats module
nbradbury Aug 14, 2025
69ace6a
Second pass at activating stats module
nbradbury Aug 14, 2025
a03cd69
Renamed stats helper to module helper
nbradbury Aug 14, 2025
4f4cca0
Fixed JetpackModuleHelper
nbradbury Aug 14, 2025
163941a
Fixed JetpackModuleHelper, p2
nbradbury Aug 14, 2025
7d6ebac
Reload site before checking if module is activated
nbradbury Aug 14, 2025
64fd886
Simplified JetpackModuleHelper.kt
nbradbury Aug 14, 2025
d3e5261
Ignore response in JetpackModuleHelper.kt
nbradbury Aug 14, 2025
ffceda9
Use isActiveModuleEnabled
nbradbury Aug 14, 2025
2f55e53
Refetch sites before checking if module is activated
nbradbury Aug 14, 2025
73db472
Added TODO
nbradbury Aug 14, 2025
91638ef
Apply the connected site ID to the site
nbradbury Aug 15, 2025
be4abdd
Use more reliable isActiveModuleEnabled
nbradbury Aug 15, 2025
3ff0556
Store site rather than call getSelectedSite everywhere
nbradbury Aug 15, 2025
18c0e39
Removed unnecessary var
nbradbury Aug 15, 2025
c7f773a
Retain the REST passwords
nbradbury Aug 15, 2025
67adc41
Reworded comment
nbradbury Aug 15, 2025
54a00c4
Simplified copyRestPasswords
nbradbury Aug 15, 2025
3ba69c3
Removed unused PREFS
nbradbury Aug 15, 2025
e55e551
Simplified JetpackModuleHelper
nbradbury Aug 15, 2025
ec1eafa
Defer copying passwords to a future PR
nbradbury Aug 15, 2025
77802b9
Limit feature to Jetpack app
nbradbury Aug 15, 2025
49bdb79
Merge branch 'trunk' into feature/jetpack-connect-finalize
nbradbury Aug 15, 2025
05fd643
Fixed failing test
nbradbury Aug 15, 2025
6fe83ba
First pass at rest connection from notifs
nbradbury Aug 15, 2025
c72efff
Second pass at rest connection from notifs
nbradbury Aug 15, 2025
ec8b6a8
Simplified starting the flow
nbradbury Aug 15, 2025
abc9c54
Fixed detekt warning
nbradbury Aug 15, 2025
784ed28
Renamed class to clarify that it's solely about the stats module
nbradbury Aug 15, 2025
4280ce0
Merge branch 'trunk' of https://github.com/wordpress-mobile/WordPress…
nbradbury Aug 18, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import uniffi.wp_api.WpComSiteId
import javax.inject.Inject

class JetpackConnector @Inject constructor(
private val jetpackConnectionHelper: JetpackConnectionHelper
private val jetpackConnectionHelper: JetpackConnectionHelper,
) {
/**
* Connects the Jetpack site to WordPress.com and returns the site ID
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.wordpress.android.ui.jetpackrestconnection

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.viewModels
import androidx.compose.runtime.collectAsState
Expand All @@ -15,6 +16,7 @@ import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.ActivityNavigator
import org.wordpress.android.ui.RequestCodes
import org.wordpress.android.ui.jetpackrestconnection.JetpackRestConnectionViewModel.Companion.DEFAULT_CONNECTION_SOURCE
import org.wordpress.android.ui.main.BaseAppCompatActivity
import org.wordpress.android.util.extensions.setContent
import javax.inject.Inject
Expand All @@ -31,12 +33,28 @@ class JetpackRestConnectionActivity : BaseAppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

// Get the connection source from the intent and set it in the ViewModel
if (savedInstanceState == null) {
val source = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getSerializableExtra(
KEY_CONNECTION_SOURCE,
JetpackRestConnectionViewModel.ConnectionSource::class.java
)
} else {
@Suppress("DEPRECATION")
intent.getSerializableExtra(KEY_CONNECTION_SOURCE) as? JetpackRestConnectionViewModel.ConnectionSource
} ?: DEFAULT_CONNECTION_SOURCE
viewModel.setConnectionSource(source)
}

setContent {
JetpackRestConnectionScreen(
currentStep = viewModel.currentStep.collectAsState(),
stepStates = viewModel.stepStates.collectAsState(),
buttonType = viewModel.buttonType.collectAsState(),
onStartClick = viewModel::onStartClick,
onDoneClick = viewModel::onDoneClick,
onCloseClick = viewModel::onCloseClick,
onRetryClick = viewModel::onRetryClick
)
Expand All @@ -48,6 +66,10 @@ class JetpackRestConnectionActivity : BaseAppCompatActivity() {
JetpackRestConnectionViewModel.UiEvent.StartWPComLogin ->
startWPComLogin()

JetpackRestConnectionViewModel.UiEvent.Done -> {
finish()
}

JetpackRestConnectionViewModel.UiEvent.Close ->
finish()

Expand Down Expand Up @@ -84,8 +106,17 @@ class JetpackRestConnectionActivity : BaseAppCompatActivity() {
}

companion object {
@JvmStatic
fun createIntent(context: Context) =
Intent(context, JetpackRestConnectionActivity::class.java)
private const val KEY_CONNECTION_SOURCE = "key_connection_source"

fun startJetpackRestConnectionFlow(
context: Context,
source: JetpackRestConnectionViewModel.ConnectionSource
) {
context.startActivity(
Intent(context, JetpackRestConnectionActivity::class.java).apply {
putExtra(KEY_CONNECTION_SOURCE, source)
}
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ fun JetpackRestConnectionScreen(
stepStates: State<Map<ConnectionStep, StepState>>,
buttonType: State<ButtonType?>,
onStartClick: () -> Unit = {},
onDoneClick: () -> Unit = {},
onCloseClick: () -> Unit = {},
onRetryClick: () -> Unit = {}
) {
Expand All @@ -88,7 +89,7 @@ fun JetpackRestConnectionScreen(
JetpackConnectionButton(
buttonType = buttonType.value,
onStartClick = onStartClick,
onDoneClick = onCloseClick,
onDoneClick = onDoneClick,
onRetryClick = onRetryClick
)
}
Expand Down Expand Up @@ -274,6 +275,7 @@ private fun getErrorText(context: Context, errorType: ErrorType): String {
ErrorType.MissingAccessToken -> R.string.jetpack_rest_connection_error_access_token
ErrorType.ConnectSiteFailed -> R.string.jetpack_rest_connection_error_connect_site
ErrorType.InstallJetpackFailed -> R.string.jetpack_rest_connection_error_install_jetpack
ErrorType.ActivateStatsFailed -> R.string.jetpack_rest_connection_error_activate_stats
ErrorType.Timeout -> R.string.jetpack_rest_connection_error_timeout
ErrorType.Offline -> R.string.jetpack_rest_connection_error_offline
is ErrorType.Unknown -> R.string.jetpack_rest_connection_error_unknown
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ import javax.inject.Named
class JetpackRestConnectionViewModel @Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
private val selectedSiteRepository: SelectedSiteRepository,
selectedSiteRepository: SelectedSiteRepository,
private val accountStore: AccountStore,
private val jetpackInstaller: JetpackInstaller,
private val jetpackConnector: JetpackConnector,
private val jetpackModuleHelper: JetpackStatsModuleHelper,
private val appLogWrapper: AppLogWrapper,
) : ScopedViewModel(mainDispatcher) {
private val _currentStep = MutableStateFlow<ConnectionStep?>(null)
Expand All @@ -46,6 +47,17 @@ class JetpackRestConnectionViewModel @Inject constructor(
private var job: Job? = null
private var isWaitingForWPComLogin = false

private var connectionSource: ConnectionSource = DEFAULT_CONNECTION_SOURCE
private var site: SiteModel = selectedSiteRepository.getSelectedSite() ?: error("No site selected")

/**
* This will be used for analytics tracking
*/
fun setConnectionSource(source: ConnectionSource) {
connectionSource = source
appLogWrapper.d(AppLog.T.API, "$TAG: Connection source set to: $source")
}

private fun startConnectionJob(fromStep: ConnectionStep? = null) {
val stepInfo = fromStep?.let { " from step: $it" } ?: ""
appLogWrapper.d(AppLog.T.API, "$TAG: Starting Jetpack connection job$stepInfo")
Expand Down Expand Up @@ -145,6 +157,14 @@ class JetpackRestConnectionViewModel @Inject constructor(
startConnectionJob()
}

/**
* Connection flow completed successfully and user clicked the Done button
*/
fun onDoneClick() {
appLogWrapper.d(AppLog.T.API, "$TAG: Done clicked")
setUiEvent(UiEvent.Done)
}

/**
* User clicked the close button, confirm closing if the connection is in progress, otherwise close immediately
*/
Expand Down Expand Up @@ -267,13 +287,13 @@ class JetpackRestConnectionViewModel @Inject constructor(

ConnectionStep.Finalize -> {
appLogWrapper.d(AppLog.T.API, "$TAG: Finalizing connection")
// TODO
finalize()
}
}
}

/**
* Starts the wp.com login flow if the user isn't logged into wp.com
* Step 1: Starts the wp.com login flow if the user isn't logged into wp.com
*/
private fun loginWpCom() {
if (accountStore.hasAccessToken()) {
Expand Down Expand Up @@ -314,10 +334,10 @@ class JetpackRestConnectionViewModel @Inject constructor(
}

/**
* Installs Jetpack to the current site if not already installed
* Step 2: Installs Jetpack to the current site if not already installed
*/
private suspend fun installJetpack() {
val result = jetpackInstaller.installJetpack(getSite())
val result = jetpackInstaller.installJetpack(site)

result.fold(
onSuccess = { status ->
Expand Down Expand Up @@ -350,12 +370,15 @@ class JetpackRestConnectionViewModel @Inject constructor(
}

/**
* Connects the current site to Jetpack
* Step 3: Connects the current site to Jetpack
*/
private suspend fun connectSite() {
val result = jetpackConnector.connectSite(getSite())
val result = jetpackConnector.connectSite(site)
result.fold(
onSuccess = {
onSuccess = { wpComSiteId ->
// the local site won't have a siteId since it's self-hosted and previously unconnected to Jetpack,
// so assign it the siteId retrieved when connecting the site
site.siteId = wpComSiteId.toLong()
updateStepStatus(
step = ConnectionStep.ConnectSite,
status = ConnectionStatus.Completed
Expand All @@ -372,7 +395,7 @@ class JetpackRestConnectionViewModel @Inject constructor(
}

/**
* Connects the user to the current site to Jetpack
* Step 4: Connects the user to the current site to Jetpack
*/
private suspend fun connectUser() {
if (!accountStore.hasAccessToken()) {
Expand All @@ -384,11 +407,11 @@ class JetpackRestConnectionViewModel @Inject constructor(
return
}
val result = jetpackConnector.connectUser(
site = getSite(),
site = site,
accessToken = accountStore.accessToken!!
)
result.fold(
onSuccess = {
onSuccess = { wpComUserId ->
updateStepStatus(
step = ConnectionStep.ConnectUser,
status = ConnectionStatus.Completed
Expand All @@ -405,10 +428,23 @@ class JetpackRestConnectionViewModel @Inject constructor(
}

/**
* Gets the current site from the store
* Step 5: Finalize the connection by activating the stats module for the site
*/
private fun getSite() =
selectedSiteRepository.getSelectedSite() ?: error("No site is currently selected in SelectedSiteRepository")
private suspend fun finalize() {
val result = jetpackModuleHelper.activateStatsModule(site)
if (result.isSuccess) {
updateStepStatus(
step = ConnectionStep.Finalize,
status = ConnectionStatus.Completed
)
} else {
updateStepStatus(
step = ConnectionStep.Finalize,
status = ConnectionStatus.Failed,
error = ErrorType.ActivateStatsFailed
)
}
}

sealed class ConnectionStep {
data object LoginWpCom : ConnectionStep()
Expand All @@ -427,6 +463,7 @@ class JetpackRestConnectionViewModel @Inject constructor(

sealed class UiEvent {
data object StartWPComLogin : UiEvent()
data object Done : UiEvent()
data object Close : UiEvent()
data object ShowCancelConfirmation : UiEvent()
}
Expand All @@ -438,6 +475,7 @@ class JetpackRestConnectionViewModel @Inject constructor(
data object ConnectWpComFailed : ErrorType()
data object ConnectSiteFailed : ErrorType()
data object ConnectUserFailed : ErrorType()
data object ActivateStatsFailed : ErrorType()
data object MissingAccessToken : ErrorType()
data object Timeout : ErrorType()
data object Offline : ErrorType()
Expand All @@ -455,11 +493,17 @@ class JetpackRestConnectionViewModel @Inject constructor(
val errorType: ErrorType? = null,
)

enum class ConnectionSource {
STATS,
NOTIFS
}

companion object {
private const val TAG = "JetpackRestConnectionViewModel"
private const val LIMIT_VERSION = "14.2"
private const val STEP_TIMEOUT_MS = 45 * 1000L
private const val UI_DELAY_MS = 1000L
val DEFAULT_CONNECTION_SOURCE = ConnectionSource.STATS

/**
* Requirements:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package org.wordpress.android.ui.jetpackrestconnection

import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.JetpackStore
import org.wordpress.android.fluxc.store.JetpackStore.ActivateStatsModulePayload
import org.wordpress.android.fluxc.store.SiteStore
import javax.inject.Inject

class JetpackStatsModuleHelper @Inject constructor(
private val jetpackStore: JetpackStore,
private val siteStore: SiteStore
) {
suspend fun activateStatsModule(site: SiteModel): Result<Unit> {
if (isStatsModuleActivated(site)) {
return Result.success(Unit)
}

jetpackStore.activateStatsModule(ActivateStatsModulePayload(site))

// ignore the activation response as it's unreliable, instead just check if it's activated now
return verifyStatsModuleActivation(site)
}

/**
* Fetch Jetpack sites filtering for this site and check if the module is now activated. Note that fetching
* the single site fails because of changes to it during the connection flow.
*/
private suspend fun verifyStatsModuleActivation(
site: SiteModel,
): Result<Unit> {
val payload = SiteStore.FetchSitesPayload(
filters = listOf(SiteStore.SiteFilter.JETPACK)
)
return siteStore.fetchSites(payload).updatedSites.firstOrNull {
it.siteId == site.siteId
}?.let { updatedSite ->
if (isStatsModuleActivated(updatedSite)) {
Result.success(Unit)
} else {
Result.failure(Exception("Stats module not activated"))
}
} ?: Result.failure(Exception("Site not found"))
}

private fun isStatsModuleActivated(site: SiteModel) =
site.isActiveModuleEnabled(STATS_MODULE_NAME)

companion object {
private const val STATS_MODULE_NAME = "stats"
}
}
Loading