Skip to content
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

Removes multiple calls to the WebSettings.getDefaultUserAgent api #20603

Merged
merged 7 commits into from
Apr 11, 2024
Merged
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
2 changes: 1 addition & 1 deletion RELEASE-NOTES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

24.7
-----

* [*] [internal] Updates the way the app retrieves the User-Agent request header [https://github.com/wordpress-mobile/WordPress-Android/pull/20603]

24.6
-----
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
package org.wordpress.android;

import android.webkit.WebSettings;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.wordpress.android.fluxc.network.UserAgent;

import javax.inject.Inject;

import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNotNull;
Expand All @@ -24,14 +30,21 @@ public class UserAgentTest {
@Rule(order = 1)
public InitializationRule initRule = new InitializationRule();

@Inject UserAgent mUserAgent;

@Before
public void setUp() {
hiltRule.inject();
}

@Test
public void testGetUserAgentAndGetDefaultUserAgent() {
String userAgent = WordPress.getUserAgent();
String userAgent = mUserAgent.toString();
assertNotNull("User-Agent must be set", userAgent);
assertTrue("User-Agent must not be an empty string", userAgent.length() > 0);
assertTrue("User-Agent must contain app name substring", userAgent.contains(USER_AGENT_APPNAME));

String defaultUserAgent = WordPress.getDefaultUserAgent();
String defaultUserAgent = WebSettings.getDefaultUserAgent(AppInitializer.Companion.getContext());
assertNotNull("Default User-Agent must be set", defaultUserAgent);
assertTrue("Default User-Agent must not be an empty string", defaultUserAgent.length() > 0);
assertFalse("Default User-Agent must not contain app name", defaultUserAgent.contains(USER_AGENT_APPNAME));
Expand Down
59 changes: 7 additions & 52 deletions WordPress/src/main/java/org/wordpress/android/AppInitializer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ import android.os.Build.VERSION_CODES
import android.os.Bundle
import android.os.SystemClock
import android.text.TextUtils
import android.util.AndroidRuntimeException
import android.util.Log
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatDelegate
Expand Down Expand Up @@ -55,6 +53,7 @@ import org.wordpress.android.fluxc.generated.ListActionBuilder
import org.wordpress.android.fluxc.generated.PostActionBuilder
import org.wordpress.android.fluxc.generated.SiteActionBuilder
import org.wordpress.android.fluxc.generated.ThemeActionBuilder
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.site.PrivateAtomicCookie
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.fluxc.store.AccountStore.OnAccountChanged
Expand Down Expand Up @@ -124,6 +123,9 @@ class AppInitializer @Inject constructor(
wellSqlInitializer: WellSqlInitializer,
private val application: Application
) : DefaultLifecycleObserver {
@Inject
lateinit var userAgent: UserAgent

@Inject
lateinit var dispatcher: Dispatcher

Expand Down Expand Up @@ -305,7 +307,7 @@ class AppInitializer @Inject constructor(
.installDefaultEventBus()
}

RestClientUtils.setUserAgent(userAgent)
RestClientUtils.setUserAgent(userAgent.toString())

if (!initialized) {
zendeskHelper.setupZendesk(
Expand Down Expand Up @@ -363,6 +365,8 @@ class AppInitializer @Inject constructor(
initAppOpsManager()
}

AppLog.i(T.UTILS, "AppInitializer.userAgentString: $userAgent")

initialized = true
}

Expand Down Expand Up @@ -1052,55 +1056,6 @@ class AppInitializer @Inject constructor(
)
}

/**
* Device's default User-Agent string.
* E.g.:
* "Mozilla/5.0 (Linux; Android 6.0; Android SDK built for x86_64 Build/MASTER; wv)
* AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/44.0.2403.119 Mobile
* Safari/537.36"
*/
@Suppress("SwallowedException")
val defaultUserAgent: String by lazy {
try {
WebSettings.getDefaultUserAgent(context)
} catch (e: AndroidRuntimeException) {
// Catch AndroidRuntimeException that could be raised by the WebView() constructor.
// See https://github.com/wordpress-mobile/WordPress-Android/issues/3594

// initialize with the empty string, it's a rare issue
""
} catch (expected: NullPointerException) {
// Catch NullPointerException that could be raised by WebSettings.getDefaultUserAgent()
// See https://github.com/wordpress-mobile/WordPress-Android/issues/3838

// initialize with the empty string, it's a rare issue
""
} catch (e: IllegalArgumentException) {
// Catch IllegalArgumentException that could be raised by WebSettings.getDefaultUserAgent()
// See https://github.com/wordpress-mobile/WordPress-Android/issues/9015

// initialize with the empty string, it's a rare issue
""
}
}

/**
* User-Agent string when making HTTP connections, for both API traffic and WebViews. Appends
* "wp-android/version" to WebView's default User-Agent string for the webservers to get the full feature list
* of the browser and serve content accordingly, e.g.:
* "Mozilla/5.0 (Linux; Android 6.0; Android SDK built for x86_64 Build/MASTER; wv)
* AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/44.0.2403.119 Mobile
* Safari/537.36 wp-android/4.7"
* Note that app versions prior to 2.7 simply used "wp-android" as the user agent
**/
val userAgent: String by lazy {
if (TextUtils.isEmpty(defaultUserAgent)) {
WordPress.USER_AGENT_APPNAME + "/" + PackageUtils.getVersionName(context)
} else {
(defaultUserAgent + " " + WordPress.USER_AGENT_APPNAME + "/" + PackageUtils.getVersionName(context))
}
}

fun getBitmapCache(): BitmapLruCache {
if (bitmapCache == null) {
// The cache size will be measured in kilobytes rather than number of items.
Expand Down
6 changes: 0 additions & 6 deletions WordPress/src/main/java/org/wordpress/android/WordPress.kt
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,5 @@ abstract class WordPress : Application() {
fun getRestClientUtilsV2() = AppInitializer.restClientUtilsV2

fun getRestClientUtilsV0() = AppInitializer.restClientUtilsV0

@JvmStatic
fun getDefaultUserAgent() = AppInitializer.defaultUserAgent

@JvmStatic
fun getUserAgent() = AppInitializer.userAgent
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import org.wordpress.android.fluxc.network.UserAgent;
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AppSecrets;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
Expand All @@ -25,6 +27,7 @@ public AppSecrets provideAppSecrets() {
return new AppSecrets(BuildConfig.OAUTH_APP_ID, BuildConfig.OAUTH_APP_SECRET);
}

@Singleton
@Provides
public UserAgent provideUserAgent(@ApplicationContext Context appContext) {
return new UserAgent(appContext, WordPress.USER_AGENT_APPNAME);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@
import androidx.appcompat.widget.Toolbar;

import org.wordpress.android.R;
import org.wordpress.android.WordPress;
import org.wordpress.android.analytics.AnalyticsTracker;
import org.wordpress.android.fluxc.network.UserAgent;
import org.wordpress.android.util.extensions.CompatExtensionsKt;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

/**
* Basic activity for displaying a WebView.
*/
Expand All @@ -35,6 +37,8 @@ public abstract class WebViewActivity extends LocaleAwareActivity {

protected WebView mWebView;

@Inject UserAgent mUserAgent;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
supportRequestWindowFeature(Window.FEATURE_PROGRESS);
Expand Down Expand Up @@ -64,7 +68,7 @@ public void handleOnBackPressed() {
mWebView = (WebView) findViewById(R.id.webView);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
// Setting this user agent makes Calypso sites hide any WordPress UIs (e.g. Masterbar, banners, etc.).
mWebView.getSettings().setUserAgentString(WordPress.getUserAgent());
mWebView.getSettings().setUserAgentString(mUserAgent.toString());
configureWebView();

if (savedInstanceState == null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package org.wordpress.android.ui.blaze

import org.wordpress.android.WordPress
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.page.PageModel
import org.wordpress.android.fluxc.model.page.PageStatus
import org.wordpress.android.fluxc.model.post.PostStatus
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.ui.WPWebViewActivity
import org.wordpress.android.ui.blaze.blazecampaigns.campaigndetail.CampaignDetailPageSource
import org.wordpress.android.ui.blaze.blazecampaigns.campaignlisting.CampaignListingPageSource
Expand All @@ -18,6 +18,7 @@ import org.wordpress.android.util.config.BlazeManageCampaignFeatureConfig
import javax.inject.Inject

class BlazeFeatureUtils @Inject constructor(
private val userAgent: UserAgent,
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper,
private val appPrefsWrapper: AppPrefsWrapper,
private val blazeFeatureConfig: BlazeFeatureConfig,
Expand Down Expand Up @@ -153,7 +154,7 @@ class BlazeFeatureUtils @Inject constructor(
)
}

fun getUserAgent() = WordPress.getUserAgent()
fun getUserAgent() = userAgent.toString()

fun getAuthenticationPostData(authenticationUrl: String,
urlToLoad: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import androidx.lifecycle.ViewModelProvider
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.LayoutPickerPreviewFragmentBinding
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.ui.FullscreenBottomSheetDialogFragment
import org.wordpress.android.ui.PreviewMode.DESKTOP
import org.wordpress.android.ui.PreviewMode.MOBILE
Expand All @@ -38,6 +39,9 @@ private const val JS_EVALUATION_DELAY = 250L
private const val JS_READY_CALLBACK_ID = 926L

abstract class LayoutPreviewFragment : FullscreenBottomSheetDialogFragment() {
@Inject
lateinit var userAgent: UserAgent

@Inject
lateinit var displayUtilsWrapper: DisplayUtilsWrapper

Expand Down Expand Up @@ -125,7 +129,7 @@ abstract class LayoutPreviewFragment : FullscreenBottomSheetDialogFragment() {

binding?.previewTypeSelectorButton?.setOnClickListener { viewModel.onPreviewModePressed() }

binding?.webView?.settings?.userAgentString = WordPress.getUserAgent()
binding?.webView?.settings?.userAgentString = userAgent.toString()
binding?.webView?.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,22 @@ import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory
import com.google.android.exoplayer2.util.Util
import dagger.Reusable
import org.wordpress.android.WordPress
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.ui.utils.AuthenticationUtils
import javax.inject.Inject

@Reusable
@Suppress("DEPRECATION")
class ExoPlayerUtils @Inject constructor(
private val userAgent: UserAgent,
private val authenticationUtils: AuthenticationUtils,
private val appContext: Context
) {
private var httpDataSourceFactory: DefaultHttpDataSourceFactory? = null

fun buildHttpDataSourceFactory(url: String): DefaultHttpDataSourceFactory {
if (httpDataSourceFactory == null) {
httpDataSourceFactory = DefaultHttpDataSourceFactory(WordPress.getUserAgent())
httpDataSourceFactory = DefaultHttpDataSourceFactory(userAgent.toString())
}
httpDataSourceFactory?.defaultRequestProperties?.set(authenticationUtils.getAuthHeaders(url))
return httpDataSourceFactory as DefaultHttpDataSourceFactory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
import org.wordpress.android.fluxc.generated.MediaActionBuilder;
import org.wordpress.android.fluxc.model.MediaModel;
import org.wordpress.android.fluxc.model.SiteModel;
import org.wordpress.android.fluxc.network.UserAgent;
import org.wordpress.android.fluxc.store.MediaStore;
import org.wordpress.android.fluxc.store.MediaStore.MediaPayload;
import org.wordpress.android.fluxc.store.MediaStore.OnMediaChanged;
Expand Down Expand Up @@ -153,6 +154,8 @@ private enum MediaType {

private MediaType mMediaType;

@Inject UserAgent mUserAgent;

@Inject MediaStore mMediaStore;
@Inject Dispatcher mDispatcher;
@Inject ImageManager mImageManager;
Expand Down Expand Up @@ -1031,7 +1034,7 @@ private void saveMediaToDevice() {
}
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.addRequestHeader("User-Agent", WordPress.getUserAgent());
request.addRequestHeader("User-Agent", mUserAgent.toString());

mDownloadId = dm.enqueue(request);
invalidateOptionsMenu();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ import org.wordpress.android.BuildConfig
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.WordPress.Companion.getContext
import org.wordpress.android.WordPress.Companion.getUserAgent
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.editor.AztecEditorFragment
Expand Down Expand Up @@ -94,6 +93,7 @@ import org.wordpress.android.fluxc.model.PostImmutableModel
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.post.PostStatus
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.site.PrivateAtomicCookie
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.fluxc.store.AccountStore.OnAccountChanged
Expand Down Expand Up @@ -323,6 +323,8 @@ class EditPostActivity : LocaleAwareActivity(), EditorFragmentActivity, EditorIm

@Inject lateinit var dispatcher: Dispatcher

@Inject lateinit var userAgent: UserAgent

@Inject lateinit var accountStore: AccountStore

@Inject lateinit var siteStore: SiteStore
Expand Down Expand Up @@ -2387,7 +2389,7 @@ class EditPostActivity : LocaleAwareActivity(), EditorFragmentActivity, EditorIm
siteModel.password,
siteModel.isUsingWpComRestApi,
siteModel.webEditor,
getUserAgent(),
userAgent.toString(),
isJetpackSsoEnabled
)
return GutenbergEditorFragment.newInstance(
Expand Down Expand Up @@ -2424,7 +2426,7 @@ class EditPostActivity : LocaleAwareActivity(), EditorFragmentActivity, EditorIm
editorMediaUploadListener = editorFragment as EditorMediaUploadListener?

// Set up custom headers for the visual editor's internal WebView
editorFragment?.setCustomHttpHeader("User-Agent", getUserAgent())
editorFragment?.setCustomHttpHeader("User-Agent", userAgent.toString())
reattachUploadingMediaForAztec()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.wordpress.android.WordPress;
import org.wordpress.android.datasets.PublicizeTable;
import org.wordpress.android.fluxc.model.SiteModel;
import org.wordpress.android.fluxc.network.UserAgent;
import org.wordpress.android.fluxc.store.AccountStore;
import org.wordpress.android.models.PublicizeConnection;
import org.wordpress.android.models.PublicizeService;
Expand All @@ -39,6 +40,8 @@ public class PublicizeWebViewFragment extends PublicizeBaseFragment {
private WebView mWebView;
private ProgressBar mProgress;

@Inject UserAgent mUserAgent;

@Inject AccountStore mAccountStore;

/*
Expand Down Expand Up @@ -106,7 +109,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setUserAgentString(WordPress.getUserAgent());
mWebView.getSettings().setUserAgentString(mUserAgent.toString());

return rootView;
}
Expand Down
Loading
Loading