Skip to content

Jetpack REST connection: connect site and user #22126

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 58 commits into from
Aug 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
58 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
6185c2d
Merge branch 'trunk' into feature/jetpack-connect-site-and-user
nbradbury Aug 15, 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
@@ -0,0 +1,72 @@
package org.wordpress.android.ui.jetpackrestconnection

import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.utils.AppLogWrapper
import org.wordpress.android.util.AppLog
import rs.wordpress.api.kotlin.WpApiClient
import rs.wordpress.api.kotlin.WpRequestExecutor
import uniffi.wp_api.JetpackConnectionClient
import uniffi.wp_api.ParsedUrl
import uniffi.wp_api.WpApiClientDelegate
import uniffi.wp_api.WpApiMiddlewarePipeline
import uniffi.wp_api.WpAppNotifier
import uniffi.wp_api.WpAuthenticationProvider
import java.net.URL
import javax.inject.Inject

class JetpackConnectionHelper @Inject constructor(
private val appLogWrapper: AppLogWrapper
) {
fun initWpApiClient(site: SiteModel): WpApiClient {
requireRestCredentials(site)
return WpApiClient(
wpOrgSiteApiRootUrl = URL(resolveRestApiUrl(site)),
authProvider = createRestAuthProvider(site)
)
}
Comment on lines +20 to +26
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⛏️ I know I have already mentioned this, but what about keeping all the WpApiClient creations inside the WpApiClientProviderso the maintenante is clearer?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, this is already a task on the Linear project. I'll DM you the project link.


fun initJetpackConnectionClient(site: SiteModel): JetpackConnectionClient {
requireRestCredentials(site)

val delegate = WpApiClientDelegate(
authProvider = createRestAuthProvider(site),
requestExecutor = WpRequestExecutor(),
middlewarePipeline = WpApiMiddlewarePipeline(emptyList()),
appNotifier = InvalidAuthNotifier()
)

return JetpackConnectionClient(
apiRootUrl = ParsedUrl.parse(resolveRestApiUrl(site)),
delegate = delegate
)
}

private fun createRestAuthProvider(site: SiteModel) =
WpAuthenticationProvider.staticWithUsernameAndPassword(
site.apiRestUsernamePlain!!,
site.apiRestPasswordPlain!!
)

private fun requireRestCredentials(site: SiteModel) {
require(!site.apiRestUsernamePlain.isNullOrBlank()) {
"API username is required"
}
require(!site.apiRestPasswordPlain.isNullOrBlank()) {
"API password is required"
}
}

private fun resolveRestApiUrl(site: SiteModel) =
site.wpApiRestUrl ?: "${site.url}/wp-json"

private inner class InvalidAuthNotifier : WpAppNotifier {
override suspend fun requestedWithInvalidAuthentication() {
appLogWrapper.d(AppLog.T.API, "$TAG: requestedWithInvalidAuthentication")
throw IllegalArgumentException("Invalid credentials")
}
}

companion object {
private const val TAG = "JetpackConnectionHelper"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.wordpress.android.ui.jetpackrestconnection

import org.wordpress.android.fluxc.model.SiteModel
import uniffi.wp_api.WpAuthentication
import uniffi.wp_api.WpComSiteId
import javax.inject.Inject

class JetpackConnector @Inject constructor(
private val jetpackConnectionHelper: JetpackConnectionHelper
) {
/**
* Connects the Jetpack site to WordPress.com and returns the site ID
*/
suspend fun connectSite(site: SiteModel): Result<WpComSiteId> = runCatching {
val client = jetpackConnectionHelper.initJetpackConnectionClient(site)
val wpComSiteId = client.connectSite(CONNECT_FROM)
requireValidSiteId(wpComSiteId)
}

/**
* Connects the Jetpack user to WordPress.com and returns the site ID
*/
suspend fun connectUser(site: SiteModel, accessToken: String): Result<WpComSiteId> = runCatching {
val client = jetpackConnectionHelper.initJetpackConnectionClient(site)
val wpComAuthentication = WpAuthentication.Bearer(token = accessToken)
val wpComSiteId = client.connectUser(
wpComAuthentication = wpComAuthentication,
from = CONNECT_FROM
)
requireValidSiteId(wpComSiteId)
}

private fun requireValidSiteId(wpComSiteId: WpComSiteId): WpComSiteId {
require(wpComSiteId > 0UL) { "Jetpack connection failed, no site ID returned" }
return wpComSiteId
}

companion object {
const val CONNECT_FROM = "jetpack-android-app"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,19 @@ import uniffi.wp_api.PluginSlug
import uniffi.wp_api.PluginStatus
import uniffi.wp_api.PluginUpdateParams
import uniffi.wp_api.PluginWpOrgDirectorySlug
import uniffi.wp_api.WpAuthenticationProvider
import java.net.URL
import javax.inject.Inject

/**
* Installs the Jetpack plugin on the given site using wordpress-rs
*/
class JetpackInstaller @Inject constructor(
private val jetpackConnectionHelper: JetpackConnectionHelper,
private val appLogWrapper: AppLogWrapper,
) {
@Suppress("TooGenericExceptionCaught")
suspend fun installJetpack(site: SiteModel): Result<PluginStatus> {
if (!validateCredentials(site)) {
return Result.failure(IllegalArgumentException("Missing credentials for Jetpack installation"))
}

val apiClient = initApiClient(site)

return try {
val apiClient = jetpackConnectionHelper.initWpApiClient(site)
val info = getPluginInfo(apiClient)
when (info?.status) {
PluginStatus.ACTIVE, PluginStatus.NETWORK_ACTIVE -> {
Expand All @@ -56,20 +50,6 @@ class JetpackInstaller @Inject constructor(
}
}

private fun validateCredentials(site: SiteModel): Boolean {
return !site.apiRestUsernamePlain.isNullOrBlank() && !site.apiRestPasswordPlain.isNullOrBlank()
}

private fun initApiClient(site: SiteModel): WpApiClient {
return WpApiClient(
wpOrgSiteApiRootUrl = URL(site.wpApiRestUrl),
authProvider = WpAuthenticationProvider.staticWithUsernameAndPassword(
site.apiRestUsernamePlain!!,
site.apiRestPasswordPlain!!
)
)
}

private suspend fun getPluginInfo(apiClient: WpApiClient): PluginInfo? {
val response = apiClient.request { requestBuilder ->
requestBuilder.plugins().listWithEditContext(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
Expand Down Expand Up @@ -148,9 +148,9 @@ private val stepConfigs = listOf(
icon = Icons.Default.Home
),
StepConfig(
step = ConnectionStep.ConnectWpCom,
titleRes = R.string.jetpack_rest_connection_step_connect_wpcom,
icon = Icons.Default.Settings
step = ConnectionStep.ConnectUser,
titleRes = R.string.jetpack_rest_connection_step_connect_user,
icon = Icons.Default.Person
),
StepConfig(
step = ConnectionStep.Finalize,
Expand Down Expand Up @@ -270,9 +270,12 @@ private fun getErrorText(context: Context, errorType: ErrorType): String {
ErrorType.LoginWpComFailed -> R.string.jetpack_rest_connection_error_login_wpcom
ErrorType.ConnectWpComFailed -> R.string.jetpack_rest_connection_error_connect_wpcom
ErrorType.InstallJetpackInactive -> R.string.jetpack_rest_connection_error_install_jetpack_inactive
is ErrorType.InstallJetpackFailed -> R.string.jetpack_rest_connection_error_install_jetpack
is ErrorType.Timeout -> R.string.jetpack_rest_connection_error_timeout
is ErrorType.Offline -> R.string.jetpack_rest_connection_error_offline
ErrorType.ConnectUserFailed -> R.string.jetpack_rest_connection_error_connect_user
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.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
}
val baseMessage = context.getString(messageRes)
Expand Down Expand Up @@ -421,7 +424,7 @@ private fun JetpackRestConnectionScreenPreview() {
ConnectionStep.LoginWpCom to StepState(ConnectionStatus.Completed),
ConnectionStep.InstallJetpack to StepState(ConnectionStatus.Completed),
ConnectionStep.ConnectSite to StepState(ConnectionStatus.InProgress),
ConnectionStep.ConnectWpCom to StepState(
ConnectionStep.ConnectUser to StepState(
ConnectionStatus.Failed,
ErrorType.ConnectWpComFailed
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class JetpackRestConnectionViewModel @Inject constructor(
private val selectedSiteRepository: SelectedSiteRepository,
private val accountStore: AccountStore,
private val jetpackInstaller: JetpackInstaller,
private val jetpackConnector: JetpackConnector,
private val appLogWrapper: AppLogWrapper,
) : ScopedViewModel(mainDispatcher) {
private val _currentStep = MutableStateFlow<ConnectionStep?>(null)
Expand All @@ -39,11 +40,6 @@ class JetpackRestConnectionViewModel @Inject constructor(
private val _buttonType = MutableStateFlow<ButtonType?>(ButtonType.Start)
val buttonType = _buttonType

data class StepState(
val status: ConnectionStatus = ConnectionStatus.NotStarted,
val errorType: ErrorType? = null,
)

private val _stepStates = MutableStateFlow(initialStepStates)
val stepStates = _stepStates

Expand All @@ -68,7 +64,6 @@ class JetpackRestConnectionViewModel @Inject constructor(
*/
private fun onJobCompleted() {
appLogWrapper.d(AppLog.T.API, "$TAG: Jetpack connection job completed")
job?.cancel()
_buttonType.value = ButtonType.Done
_currentStep.value = null
}
Expand All @@ -77,8 +72,8 @@ class JetpackRestConnectionViewModel @Inject constructor(
null -> ConnectionStep.LoginWpCom
ConnectionStep.LoginWpCom -> ConnectionStep.InstallJetpack
ConnectionStep.InstallJetpack -> ConnectionStep.ConnectSite
ConnectionStep.ConnectSite -> ConnectionStep.ConnectWpCom
ConnectionStep.ConnectWpCom -> ConnectionStep.Finalize
ConnectionStep.ConnectSite -> ConnectionStep.ConnectUser
ConnectionStep.ConnectUser -> ConnectionStep.Finalize
ConnectionStep.Finalize -> null
}

Expand Down Expand Up @@ -238,7 +233,7 @@ class JetpackRestConnectionViewModel @Inject constructor(
} catch (e: Exception) {
appLogWrapper.e(AppLog.T.API, "$TAG: Error in step $step: ${e.message}")
val errorType = when (e) {
is TimeoutCancellationException -> ErrorType.Timeout(e.message)
is TimeoutCancellationException -> ErrorType.Timeout
else -> ErrorType.Unknown(e.message)
}
updateStepStatus(
Expand All @@ -262,12 +257,12 @@ class JetpackRestConnectionViewModel @Inject constructor(

ConnectionStep.ConnectSite -> {
appLogWrapper.d(AppLog.T.API, "$TAG: Connecting site")
// TODO
connectSite()
}

ConnectionStep.ConnectWpCom -> {
ConnectionStep.ConnectUser -> {
appLogWrapper.d(AppLog.T.API, "$TAG: Connecting WordPress.com user")
// TODO
connectUser()
}

ConnectionStep.Finalize -> {
Expand Down Expand Up @@ -334,6 +329,7 @@ class JetpackRestConnectionViewModel @Inject constructor(
status = ConnectionStatus.Completed
)
}

PluginStatus.INACTIVE -> {
updateStepStatus(
step = ConnectionStep.InstallJetpack,
Expand All @@ -353,6 +349,61 @@ class JetpackRestConnectionViewModel @Inject constructor(
)
}

/**
* Connects the current site to Jetpack
*/
private suspend fun connectSite() {
val result = jetpackConnector.connectSite(getSite())
result.fold(
onSuccess = {
updateStepStatus(
step = ConnectionStep.ConnectSite,
status = ConnectionStatus.Completed
)
},
onFailure = {
updateStepStatus(
step = ConnectionStep.ConnectSite,
status = ConnectionStatus.Failed,
error = ErrorType.ConnectSiteFailed
)
}
)
}

/**
* Connects the user to the current site to Jetpack
*/
private suspend fun connectUser() {
if (!accountStore.hasAccessToken()) {
updateStepStatus(
step = ConnectionStep.ConnectUser,
status = ConnectionStatus.Failed,
error = ErrorType.MissingAccessToken
)
return
}
val result = jetpackConnector.connectUser(
site = getSite(),
accessToken = accountStore.accessToken!!
)
result.fold(
onSuccess = {
updateStepStatus(
step = ConnectionStep.ConnectUser,
status = ConnectionStatus.Completed
)
},
onFailure = {
updateStepStatus(
step = ConnectionStep.ConnectUser,
status = ConnectionStatus.Failed,
error = ErrorType.ConnectUserFailed
)
}
)
}

/**
* Gets the current site from the store
*/
Expand All @@ -363,7 +414,7 @@ class JetpackRestConnectionViewModel @Inject constructor(
data object LoginWpCom : ConnectionStep()
data object InstallJetpack : ConnectionStep()
data object ConnectSite : ConnectionStep()
data object ConnectWpCom : ConnectionStep()
data object ConnectUser : ConnectionStep()
data object Finalize : ConnectionStep()
}

Expand All @@ -385,8 +436,11 @@ class JetpackRestConnectionViewModel @Inject constructor(
data object InstallJetpackFailed : ErrorType()
data object InstallJetpackInactive : ErrorType()
data object ConnectWpComFailed : ErrorType()
data class Timeout(override val message: String? = null) : ErrorType(message)
data class Offline(override val message: String? = null) : ErrorType(message)
data object ConnectSiteFailed : ErrorType()
data object ConnectUserFailed : ErrorType()
data object MissingAccessToken : ErrorType()
data object Timeout : ErrorType()
data object Offline : ErrorType()
data class Unknown(override val message: String? = null) : ErrorType(message)
}

Expand All @@ -396,6 +450,11 @@ class JetpackRestConnectionViewModel @Inject constructor(
data object Retry : ButtonType()
}

data class StepState(
val status: ConnectionStatus = ConnectionStatus.NotStarted,
val errorType: ErrorType? = null,
)

companion object {
private const val TAG = "JetpackRestConnectionViewModel"
private const val LIMIT_VERSION = "14.2"
Expand All @@ -419,7 +478,7 @@ class JetpackRestConnectionViewModel @Inject constructor(
ConnectionStep.LoginWpCom to StepState(),
ConnectionStep.InstallJetpack to StepState(),
ConnectionStep.ConnectSite to StepState(),
ConnectionStep.ConnectWpCom to StepState(),
ConnectionStep.ConnectUser to StepState(),
ConnectionStep.Finalize to StepState()
)
}
Expand Down
Loading