Мне необходимо, чтобы в shouldOverrideUrlLoading, когда в WebView пытаются сделать переход на ссылку не с бэкенда, то открывалась она в браузере. package ru.maxi.mobile.feature.offlinepromo

import ru.maxi.mobile.core.navigation.BottomSheetFragmentScreen
import ru.maxi.mobile.core.navigation.FragmentScreenWithArgs
import ru.maxi.mobile.feature.offlinepromo.model.OfflinePromoCodeId
import ru.maxi.mobile.feature.offlinepromo.ui.offlinePromoCodeDetails.OfflinePromoCodeDetailsArgs
import ru.maxi.mobile.feature.offlinepromo.ui.offlinePromoCodeDetails.OfflinePromoCodeDetailsFragment
import ru.maxi.mobile.feature.offlinepromo.ui.offlinePromoCodeList.OfflinePromoCodeListFragment
import ru.maxi.mobile.feature.offlinepromo.ui.offlinePromoCodeList.model.OfflinePromoCodeListArgs
import ru.maxi.mobile.feature.offlinepromo.ui.offlinePromoCodePoints.OfflinePromoPointsActivationFragment
import ru.maxi.mobile.presentation.common.screens.CommonScreens
import java.net.URI

/**
 * Экраны офлайн промокодов
 */
@Suppress("FunctionName")
object OfflinePromoCodeScreens {

    /**
     * Экран списка офлайн промокодов
     */
    fun OfflinePromoCodeListScreen(promoCode: String? = null) = FragmentScreenWithArgs(
        args = OfflinePromoCodeListArgs(promoCode = promoCode),
    ) {
        OfflinePromoCodeListFragment()
    }

    /**
     * Экран деталки офлайн промокода
     *
     * @param id идентификатор офлайн промокода
     * @param afterActivation флаг открыт экран после активации или нет
     */
    fun OfflinePromoCodeDetailsScreen(id: OfflinePromoCodeId, afterActivation: Boolean) = FragmentScreenWithArgs(
        args = OfflinePromoCodeDetailsArgs(id = id, afterActivation = afterActivation),
    ) {
        OfflinePromoCodeDetailsFragment()
    }

    /**
     * Экран активации офлайн промокода на баллы
     */
    fun OfflinePromoPointsActivationScreen() = BottomSheetFragmentScreen {
        OfflinePromoPointsActivationFragment()
    }

    /**
     * Экран правил функционала офлайн промокодов
     */
    fun InfoScreen() = CommonScreens.WebViewScreen(
        uri = URI.create(RULES_URL),
        title = RULES_TITLE,
    )

    private const val RULES_URL = "api/v1/offline-promocode/rules"
    private const val RULES_TITLE = "Правила акции"
}
package ru.maxi.mobile.feature.webview.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.DownloadListener
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import by.kirich1409.viewbindingdelegate.viewBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import ru.maxi.mobile.R
import ru.maxi.mobile.base.ui.MvvmBaseFragment
import ru.maxi.mobile.common.utils.android.screenArgs
import ru.maxi.mobile.common.utils.android.setupDarkMode
import ru.maxi.mobile.core.data.LoadableData
import ru.maxi.mobile.databinding.FragmentWebviewBinding
import java.net.URL

/**
 * Фрагмент для отображения WebView
 */
@AndroidEntryPoint
class WebViewFragment : MvvmBaseFragment(R.layout.fragment_webview) {

    private val screenArgs by screenArgs(WebViewArgs)

    private val viewBinding by viewBinding(FragmentWebviewBinding::bind)

    private val viewModel by viewModels<WebViewViewModel>()

    override val analyticsName: String = "_WebView"

    @SuppressLint("SetJavaScriptEnabled")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        actionBarManager.setTitle(screenArgs.title)
        actionBarManager.showBackButton()

        with(viewBinding) {
            webView.apply {
                settings.apply {
                    textZoom = 100
                    javaScriptEnabled = true
                }
                webViewClient = CustomWebViewClient()
                setupDarkMode()
                setDownloadListener(CustomDownloadListener())
            }
            noConnectionView.setOnActionButtonClickListener { webView.reload() }
        }

        with(viewLifecycleOwner) {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    launch { viewModel.viewState.collect(::onViewStateChange) }
                }
            }
        }
        Log.d("TESTING", "WebViewCreated uri ${screenArgs.uri}")
        Log.d("TESTING", "WebViewCreated uri path ${screenArgs.uri.path}")
    }

    private fun onViewStateChange(viewState: LoadableData<URL>) {
        when (viewState) {
            is LoadableData.Loading -> with(viewBinding) {
                loaderView.show()
                noConnectionView.isVisible = false
                webView.isInvisible = true
                viewState.value?.let(::loadPage)
            }

            is LoadableData.Error -> with(viewBinding) {
                loaderView.hide()
                noConnectionView.isVisible = true
                webView.isInvisible = true
            }

            is LoadableData.Success -> with(viewBinding) {
                loaderView.hide()
                noConnectionView.isVisible = false
                webView.isVisible = true
                loadPage(viewState.value)
            }
        }
    }

    private fun loadPage(url: URL) {
        if (viewBinding.webView.url != url.toString()) {
            viewBinding.webView.loadUrl(url.toString())
        }
    }

    private inner class CustomDownloadListener : DownloadListener {
        override fun onDownloadStart(
            url: String?,
            userAgent: String?,
            contentDisposition: String?,
            mimeType: String?,
            contentLength: Long,
        ) {
            if (url != null) {
                Log.d("TESTING", "$mimeType")
                try {
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.setDataAndType(Uri.parse(url), mimeType)
                    val packageManager = requireContext().packageManager
                    if (intent.resolveActivity(packageManager) != null) {
                        startActivity(intent)
                    } else {
                        val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(browserIntent)
                    }
                } catch (ignored: Exception) {
                }
            }
        }
    }

    private inner class CustomWebViewClient : WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            val uri = request.url
            Log.d("TESTING", "uri.host = ${uri.host}")
            Log.d("TESTING", "request.url (uri) = $uri")
            return when {
                uri.host == MAXI_TODAY_HOST -> return super.shouldOverrideUrlLoading(view, request)
                else -> return false //
            }
            // return when {
            // //
            // // if (url.endsWith(".pdf")) {
            // //     return true
            // // } else  {
            // //     val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
            // //     startActivity(browserIntent)
            // //     return true
            // // }
            // }
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            viewModel.onPageStarted()
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            viewModel.onPageFinished()
        }

        override fun onReceivedError(
            view: WebView?,
            request: WebResourceRequest,
            error: WebResourceError?,
        ) {
            if (request.isForMainFrame) {
                viewModel.onError()
            }
        }

        override fun onReceivedHttpError(
            view: WebView?,
            request: WebResourceRequest,
            errorResponse: WebResourceResponse?,
        ) {
            if (request.isForMainFrame) {
                viewModel.onError()
            }
        }
    }

    companion object {
        private const val MAXI_TODAY_HOST = "maxi.today"
    }
}