Skip to content

Commit

Permalink
Improve PC user agent
Browse files Browse the repository at this point in the history
  • Loading branch information
hazuki0x0 committed Feb 17, 2021
1 parent 7abfbec commit f0faa63
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ import jp.hazuki.yuzubrowser.browser.tab.TabManagerFactory
import jp.hazuki.yuzubrowser.browser.view.Toolbar
import jp.hazuki.yuzubrowser.core.eventbus.LocalEventBus
import jp.hazuki.yuzubrowser.core.utility.extensions.appCacheFilePath
import jp.hazuki.yuzubrowser.core.utility.extensions.getFakeChromeUserAgent
import jp.hazuki.yuzubrowser.core.utility.extensions.getRealUserAgent
import jp.hazuki.yuzubrowser.core.utility.extensions.getResColor
import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport
import jp.hazuki.yuzubrowser.core.utility.log.Logger
Expand Down Expand Up @@ -558,14 +558,14 @@ class BrowserActivity : BrowserBaseActivity(), BrowserController, FinishAlertDia
if (resultCode != RESULT_OK || data == null) return
val ua = data.getStringExtra(Intent.EXTRA_TEXT)
val tab = tabManagerIn.currentTabData
tab.mWebView.webSettings.userAgentString = if (ua.isNullOrEmpty() && AppPrefs.fake_chrome.get()) getFakeChromeUserAgent() else ua
tab.mWebView.webSettings.userAgentString = getRealUserAgent(ua, AppPrefs.fake_chrome.get())
tab.mWebView.reload()
}
BrowserController.REQUEST_DEFAULT_USERAGENT -> {
if (resultCode != RESULT_OK || data == null) return
val ua = data.getStringExtra(Intent.EXTRA_TEXT)
AppPrefs.user_agent.set(ua)
val browserUA = if (ua.isNullOrEmpty() && AppPrefs.fake_chrome.get()) getFakeChromeUserAgent() else ua
val browserUA = getRealUserAgent(ua, AppPrefs.fake_chrome.get())
AppPrefs.commit(this, AppPrefs.user_agent)
for (tabData in tabManagerIn.loadedData) {
tabData.mWebView.webSettings.userAgentString = browserUA
Expand Down
82 changes: 37 additions & 45 deletions browser/src/main/java/jp/hazuki/yuzubrowser/browser/WebClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@ import jp.hazuki.yuzubrowser.adblock.ui.abp.AbpFilterSubscribeDialog
import jp.hazuki.yuzubrowser.adblock.ui.original.AdBlockActivity
import jp.hazuki.yuzubrowser.bookmark.view.BookmarkActivity
import jp.hazuki.yuzubrowser.core.cache.SoftCache
import jp.hazuki.yuzubrowser.core.utility.extensions.appCacheFilePath
import jp.hazuki.yuzubrowser.core.utility.extensions.getFakeChromeUserAgent
import jp.hazuki.yuzubrowser.core.utility.extensions.getResColor
import jp.hazuki.yuzubrowser.core.utility.extensions.readAssetsText
import jp.hazuki.yuzubrowser.core.utility.extensions.*
import jp.hazuki.yuzubrowser.core.utility.log.Logger
import jp.hazuki.yuzubrowser.download.*
import jp.hazuki.yuzubrowser.download.core.data.DownloadFile
Expand Down Expand Up @@ -261,13 +258,8 @@ class WebClient(

setting.allowContentAccess = AppPrefs.allow_content_access.get()
setting.defaultTextEncodingName = AppPrefs.default_encoding.get()
if (AppPrefs.user_agent.get().isNullOrEmpty()) {
if (AppPrefs.fake_chrome.get()) {
setting.userAgentString = activity.getFakeChromeUserAgent()
}
} else {
setting.userAgentString = AppPrefs.user_agent.get()
}
setting.userAgentString =
activity.getRealUserAgent(AppPrefs.user_agent.get(), AppPrefs.fake_chrome.get())
setting.loadWithOverviewMode = AppPrefs.load_overview.get()
setting.useWideViewPort = AppPrefs.web_wideview.get()
setting.displayZoomButtons = AppPrefs.show_zoom_button.get()
Expand Down Expand Up @@ -465,8 +457,8 @@ class WebClient(
.setMessage(R.string.form_resubmit)
.setPositiveButton(android.R.string.ok) { _, _ -> resend.sendToTarget() }
.setNegativeButton(android.R.string.cancel) { _, _ -> dontResend.sendToTarget() }
.setOnCancelListener { dontResend.sendToTarget() }
.show()
.setOnCancelListener { dontResend.sendToTarget() }
.show()
}

override fun doUpdateVisitedHistory(web: CustomWebView, url: String, isReload: Boolean) {
Expand Down Expand Up @@ -507,8 +499,8 @@ class WebClient(
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ -> handler.proceed() }
.setNegativeButton(android.R.string.cancel) { _, _ -> handler.cancel() }
.setOnCancelListener { handler.cancel() }
.show()
.setOnCancelListener { handler.cancel() }
.show()
}
}

Expand Down Expand Up @@ -658,18 +650,18 @@ class WebClient(
PreferenceConstants.DOWNLOAD_SELECT -> {

AlertDialog.Builder(activity)
.setTitle(R.string.download)
.setItems(
arrayOf(getString(R.string.download), getString(R.string.open), getString(R.string.share))
) { _, which ->
when (which) {
0 -> actionDownload(url, referrer, userAgent, contentDisposition, mimetype, contentLength)
1 -> actionOpen(url, referrer, userAgent, contentDisposition, mimetype, contentLength)
2 -> actionShare(url)
}
.setTitle(R.string.download)
.setItems(
arrayOf(getString(R.string.download), getString(R.string.open), getString(R.string.share))
) { _, which ->
when (which) {
0 -> actionDownload(url, referrer, userAgent, contentDisposition, mimetype, contentLength)
1 -> actionOpen(url, referrer, userAgent, contentDisposition, mimetype, contentLength)
2 -> actionShare(url)
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
}

Expand Down Expand Up @@ -771,11 +763,11 @@ class WebClient(
val tab = controller.getTabOrNull(view) ?: return true
if (tab.isAlertAllowed && !activity.isFinishing) {
JsAlertDialog(activity)
.setAlertMode(url, message, tab.alertMode == MainTabData.ALERT_MULTIPULE) { dialogResult, blockAlert ->
if (dialogResult) result.confirm() else result.cancel()
if (blockAlert) tab.alertMode = MainTabData.ALERT_BLOCKED
}
.show()
.setAlertMode(url, message, tab.alertMode == MainTabData.ALERT_MULTIPULE) { dialogResult, blockAlert ->
if (dialogResult) result.confirm() else result.cancel()
if (blockAlert) tab.alertMode = MainTabData.ALERT_BLOCKED
}
.show()
tab.alertMode = MainTabData.ALERT_MULTIPULE
} else {
result.cancel()
Expand All @@ -787,11 +779,11 @@ class WebClient(
val tab = controller.getTabOrNull(view) ?: return true
if (tab.isAlertAllowed && !activity.isFinishing) {
JsAlertDialog(activity)
.setConfirmMode(url, message, tab.alertMode == MainTabData.ALERT_MULTIPULE) { dialogResult, blockAlert ->
if (dialogResult) result.confirm() else result.cancel()
if (blockAlert) tab.alertMode = MainTabData.ALERT_BLOCKED
}
.show()
.setConfirmMode(url, message, tab.alertMode == MainTabData.ALERT_MULTIPULE) { dialogResult, blockAlert ->
if (dialogResult) result.confirm() else result.cancel()
if (blockAlert) tab.alertMode = MainTabData.ALERT_BLOCKED
}
.show()
tab.alertMode = MainTabData.ALERT_MULTIPULE
} else {
result.cancel()
Expand All @@ -803,11 +795,11 @@ class WebClient(
val tab = controller.getTabOrNull(view) ?: return true
if (tab.isAlertAllowed && !activity.isFinishing) {
JsAlertDialog(activity)
.setPromptMode(url, message, defaultValue, tab.alertMode == MainTabData.ALERT_MULTIPULE) { dialogResult, blockAlert ->
if (dialogResult != null) result.confirm(dialogResult) else result.cancel()
if (blockAlert) tab.alertMode = MainTabData.ALERT_BLOCKED
}
.show()
.setPromptMode(url, message, defaultValue, tab.alertMode == MainTabData.ALERT_MULTIPULE) { dialogResult, blockAlert ->
if (dialogResult != null) result.confirm(dialogResult) else result.cancel()
if (blockAlert) tab.alertMode = MainTabData.ALERT_BLOCKED
}
.show()
tab.alertMode = MainTabData.ALERT_MULTIPULE
} else {
result.cancel()
Expand Down Expand Up @@ -1141,19 +1133,19 @@ class WebClient(
}
if (hasError(SslError.SSL_EXPIRED)) {
builder.appendError(context.getText(R.string.ssl_error_certificate_expired))
.appendErrorInfo(context.getText(R.string.ssl_error_certificate_expired_info), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.DEFAULT).format(certificate.validNotAfterDate))
.appendErrorInfo(context.getText(R.string.ssl_error_certificate_expired_info), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.DEFAULT).format(certificate.validNotAfterDate))
}
if (hasError(SslError.SSL_IDMISMATCH)) {
builder.appendError(context.getText(R.string.ssl_error_certificate_domain_mismatch))
.appendErrorInfo(context.getText(R.string.ssl_error_certificate_domain_mismatch_info), certificate.issuedTo.cName)
.appendErrorInfo(context.getText(R.string.ssl_error_certificate_domain_mismatch_info), certificate.issuedTo.cName)
}
if (hasError(SslError.SSL_NOTYETVALID)) {
builder.appendError(context.getText(R.string.ssl_error_certificate_not_yet_valid))
.appendErrorInfo(context.getText(R.string.ssl_error_certificate_not_yet_valid_info), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.DEFAULT).format(certificate.validNotBeforeDate))
.appendErrorInfo(context.getText(R.string.ssl_error_certificate_not_yet_valid_info), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.DEFAULT).format(certificate.validNotBeforeDate))
}
if (hasError(SslError.SSL_UNTRUSTED)) {
builder.appendError(context.getText(R.string.ssl_error_certificate_untrusted))
.appendErrorInfo(context.getText(R.string.ssl_error_certificate_untrusted_info), certificate.issuedBy.dName)
.appendErrorInfo(context.getText(R.string.ssl_error_certificate_untrusted_info), certificate.issuedBy.dName)
}
if (hasError(SslError.SSL_INVALID)) {
builder.appendError(context.getText(R.string.ssl_error_certificate_invalid))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ public static void settingInitialValue(Context context, SharedPreferences shared
modified = true;
}

int versionCode = ContextExtensionsKt.getVersionCode(context);
int versionCode = (int) ContextExtensionsKt.getVersionCode(context);

if (versionCode > lastLaunch) {
if (lastLaunch > -1) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ import android.webkit.WebSettings
import androidx.fragment.app.DialogFragment
import com.squareup.moshi.Moshi
import dagger.android.support.AndroidSupportInjection
import jp.hazuki.yuzubrowser.core.USER_AGENT_PC
import jp.hazuki.yuzubrowser.core.utility.extensions.getChromePcUserAgent
import jp.hazuki.yuzubrowser.core.utility.extensions.getFakeChromeUserAgent
import jp.hazuki.yuzubrowser.core.utility.extensions.getPcUserAgent
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.ui.settings.AppPrefs
import javax.inject.Inject
Expand All @@ -45,12 +48,17 @@ class UserAgentListDialog : DialogFragment() {
val entries = arrayOfNulls<String>(mUserAgentList.size + 1)
val entryValues = arrayOfNulls<String>(mUserAgentList.size + 1)

val ua = arguments!!.getString(UA)
val defaultUserAgent = if (AppPrefs.fake_chrome.get()) activity.getFakeChromeUserAgent() else WebSettings.getDefaultUserAgent(activity)
var ua = requireArguments().getString(UA)
val isChrome = AppPrefs.fake_chrome.get()
val defaultUserAgent = if (isChrome) activity.getFakeChromeUserAgent() else WebSettings.getDefaultUserAgent(activity)
val pcUserAgent = if (isChrome) activity.getChromePcUserAgent() else activity.getPcUserAgent()

var pos = if (ua.isNullOrEmpty() || defaultUserAgent == ua) 0 else -1
if (ua == pcUserAgent) {
ua = USER_AGENT_PC
}

entries[0] = context!!.getString(R.string.default_text)
entries[0] = activity.getString(R.string.default_text)
entryValues[0] = defaultUserAgent

var userAgent: UserAgent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package jp.hazuki.yuzubrowser.legacy.useragent

import jp.hazuki.yuzubrowser.core.USER_AGENT_PC

fun UserAgentList.init() {
add(UserAgent("android", USER_AGENT_ANDROID))
add(UserAgent("android Tablet", USER_AGENT_ANDROID_TAB))
Expand Down Expand Up @@ -51,4 +53,4 @@ private const val USER_AGENT_ANDROID = "Mozilla/5.0 (Linux; Android 9; Pixel 3)
private const val USER_AGENT_ANDROID_TAB = "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 9 Build/N4F26M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.90 Safari/537.36"
private const val USER_AGENT_IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1"
private const val USER_AGENT_IPAD = "Mozilla/5.0 (iPad; CPU OS 12_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1"
private const val USER_AGENT_PC = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"

Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ const val MIME_TYPE_HTML = "text/html"
const val READER_FONT_NAME = "reader_font.bin"

const val THEME_DIR = "theme"
const val USER_AGENT_PC = "yuzu://useragent/type/pc"
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.core.content.ContextCompat
import jp.hazuki.yuzubrowser.core.USER_AGENT_PC
import java.io.File

@ColorInt
Expand Down Expand Up @@ -65,13 +66,44 @@ fun Context.convertDpToFloatPx(dp: Int): Float = resources.displayMetrics.densit
val Context.density: Float
get() = resources.displayMetrics.density

fun Context.getRealUserAgent(ua: String?, isFakeChrome: Boolean): String? {
return when {
ua == USER_AGENT_PC -> {
if (isFakeChrome) {
getChromePcUserAgent()
} else {
getPcUserAgent()
}
}
ua.isNullOrEmpty() -> {
if (isFakeChrome) {
getFakeChromeUserAgent()
} else {
null
}
}
else -> ua
}
}

fun Context.getFakeChromeUserAgent(): String {
val ua = StringBuilder(WebSettings.getDefaultUserAgent(this))
ua.replace("; wv", "")
ua.replace("Version/4.0 ", "")
return ua.toString()
}

fun Context.getPcUserAgent(): String {
val ua = WebSettings.getDefaultUserAgent(this)
return ua.convertToPc()
}

fun Context.getChromePcUserAgent(): String {
return getFakeChromeUserAgent().convertToPc()
}

private fun String.convertToPc() = replace(Regex("\\(Linux[^()]+\\)"), "(Windows NT 10.0; Win64; x64)")

fun Context.readAssetsText(fileName: String): String {
return assets.open(fileName).reader().use { it.readText() }
}
Expand All @@ -81,13 +113,13 @@ fun Context.getVersionName(): String {
return info.versionName
}

fun Context.getVersionCode(): Int {
fun Context.getVersionCode(): Long {
val info = packageManager.getPackageInfo(packageName, 0)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
info.longVersionCode.toInt()
info.longVersionCode
} else {
@Suppress("DEPRECATION")
info.versionCode
info.versionCode.toLong()
}
}

Expand Down

0 comments on commit f0faa63

Please sign in to comment.