Skip to content

Commit

Permalink
Merge pull request #40 from alexch33/refactoring
Browse files Browse the repository at this point in the history
Refactoring
  • Loading branch information
alexch33 authored Dec 27, 2024
2 parents 3bd2f79 + 2559d33 commit 3dcb25d
Show file tree
Hide file tree
Showing 36 changed files with 1,529 additions and 2,371 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ android {
applicationId "com.myAllVideoBrowser"
minSdkVersion build_versions.min_sdk
targetSdkVersion build_versions.target_sdk
versionCode 17
versionName "0.3.0"
versionCode 18
versionName "0.4.0"
testInstrumentationRunner "util.TestRunner"

ndk {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,38 +121,15 @@ class AdBlockHostsLocalDataSource @Inject constructor(
}

private suspend fun readAdServersFromStream(inputStream: InputStream): Set<AdHost> {
val br2 = BufferedReader(InputStreamReader(inputStream))
val result = mutableSetOf<AdHost>()

try {
var line2: String?

yield()

while (withContext(Dispatchers.IO) {
br2.readLine()
}.also { line2 = it } != null) {
if (!line2.toString().startsWith("#")) {
val parsedLine = parseAdsLine(line2)
if (parsedLine.contains(Regex(".+\\..+"))) {
result.add(AdHost(parsedLine))
}
}
}
yield()
} catch (e: IOException) {
yield()

e.printStackTrace()
} finally {
yield()

withContext(Dispatchers.IO) {
br2.close()
return withContext(Dispatchers.IO) {
inputStream.bufferedReader().useLines { lines ->
lines.filterNot { it.startsWith("#") }
.map { parseAdsLine(it) }
.filter { it.contains(Regex(".+\\..+")) }
.map { AdHost(it) }
.toSet()
}
}

return result
}

override fun getCachedCount(): Int {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,12 @@ class AdBlockHostsRemoteDataSource @Inject constructor(

private suspend fun fetchListFromUrl(url: String): kotlinx.coroutines.flow.Flow<Set<AdHost>> {
return flow {
val response = try {
okHttpClient.getProxyOkHttpClient().newCall(Request.Builder().url(url).build())
.execute()
} catch (e: Throwable) {
e.printStackTrace()
null
}
response?.body?.byteStream().use { responseBytesStream ->
responseBytesStream?.let {
emit(readAdServersFromStream(it))
okHttpClient.getProxyOkHttpClient().newCall(Request.Builder().url(url).build()).execute()
.use { response ->
response.takeIf { it.isSuccessful }?.body?.byteStream()?.use { stream ->
emit(readAdServersFromStream(stream))
}
}
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import com.yausername.youtubedl_android.mapper.VideoFormat
import okhttp3.Request
import org.jsoup.Jsoup
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject

interface VideoService {
Expand Down Expand Up @@ -66,34 +67,28 @@ open class VideoServiceLocal(

try {
val info = YoutubeDL.getInstance().getInfo(request)
val formats = info.formats?.map {
videoEntityFromFormat(
it
)
}
val filtered = arrayListOf<VideoFormatEntity>()

if (url.url.toString().contains(FACEBOOK_HOST)) {
if (formats != null) {
filtered.addAll(formats.filter {
it.formatId?.lowercase(Locale.ROOT)?.contains(Regex("hd|sd")) == true
})
val formats = info.formats?.map { videoEntityFromFormat(it) } ?: emptyList()
val filtered = if (url.url.toString().contains(FACEBOOK_HOST)) {
formats.filter {
it.formatId?.lowercase(Locale.ROOT)?.contains(Regex("hd|sd")) == true
}
} else {
emptyList()
}

val listFormats =
VideFormatEntityList(filtered.ifEmpty { formats?.filter { !(it.acodec != "none" && it.vcodec == "none") } }
?: emptyList())
if (listFormats.formats.isEmpty()) throw Exception("Audio Only Detected")

return VideoInfoWrapper(VideoInfo(title = info.title ?: "no title").also { videoInfo ->
videoInfo.ext = info.ext ?: MP4_EXT
videoInfo.thumbnail = info.thumbnail ?: ""
videoInfo.duration = info.duration.toLong()
videoInfo.originalUrl = url.url.toString()
videoInfo.downloadUrls = if (isM3u8OrMpd) emptyList() else listOf(url)
videoInfo.formats = listFormats
videoInfo.isRegularDownload = false
val listFormats = VideFormatEntityList(filtered.ifEmpty {
formats.filter { it.vcodec != "none" || it.acodec == "none" }
})

return VideoInfoWrapper(VideoInfo(
title = info.title ?: "no title", formats = listFormats
).apply {
ext = info.ext ?: MP4_EXT
thumbnail = info.thumbnail ?: ""
duration = info.duration.toLong()
originalUrl = url.url.toString()
downloadUrls = if (isM3u8OrMpd) emptyList() else listOf(url)
isRegularDownload = false
})
} catch (e: Throwable) {
throw e
Expand Down Expand Up @@ -145,15 +140,14 @@ open class VideoServiceLocal(
}

class YoutubedlHelper @Inject constructor(
private val okHttpProxyClient: OkHttpProxyClient,
private val sharedPrefHelper: SharedPrefHelper
private val okHttpProxyClient: OkHttpProxyClient, private val sharedPrefHelper: SharedPrefHelper
) {
companion object {
private const val SUPPORTED_SITES_URL =
"https://ytb-dl.github.io/ytb-dl/supportedsites.html"
}

private val sites: HashSet<String> = HashSet()
private val sites: MutableSet<String> = ConcurrentHashMap.newKeySet()
private var isLoading = false

fun isHostSupported(host: String): Boolean {
Expand All @@ -165,7 +159,7 @@ class YoutubedlHelper @Inject constructor(

if (sites.isEmpty() || isLoading) {
try {
loadFromAssets()
loadSupportedHostsList()
} catch (e: Throwable) {
e.printStackTrace()
isLoading = false
Expand All @@ -184,7 +178,7 @@ class YoutubedlHelper @Inject constructor(
}
}

private fun loadFromAssets() {
private fun loadSupportedHostsList() {
if (!isLoading) {
isLoading = true

Expand All @@ -195,12 +189,11 @@ class YoutubedlHelper @Inject constructor(
response.body.close()
val sitesB = doc.select("li > b")

for (b in sitesB) {
val value =
b.text().trim().split(":").first().trim().lowercase().replace("- **", "")
.replace("**", "").trim()
sites.add(value)
}
sites.addAll(sitesB.map {
it.text().trim().substringBefore(":").trim().lowercase().replace("- **", "")
.replace("**", "")
})

isLoading = false
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class NetworkModule {
}

private fun buildOkHttpClient(application: Application): OkHttpClient =
OkHttpClient.Builder()
OkHttpClient.Builder().retryOnConnectionFailure(true)
.connectTimeout(10L, TimeUnit.SECONDS)
.writeTimeout(10L, TimeUnit.SECONDS)
.readTimeout(30L, TimeUnit.SECONDS)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import com.myAllVideoBrowser.ui.main.history.HistoryViewModel
import com.myAllVideoBrowser.ui.main.home.browser.BrowserViewModel
import com.myAllVideoBrowser.ui.main.home.MainViewModel
import com.myAllVideoBrowser.ui.main.home.browser.homeTab.BrowserHomeViewModel
import com.myAllVideoBrowser.ui.main.home.browser.detectedVideos.VideoDetectionAlgVModel
import com.myAllVideoBrowser.ui.main.home.browser.detectedVideos.GlobalVideoDetectionModel
import com.myAllVideoBrowser.ui.main.home.browser.webTab.WebTabViewModel
import com.myAllVideoBrowser.ui.main.home.browser.detectedVideos.DetectedVideosTabViewModel
import com.myAllVideoBrowser.ui.main.home.browser.detectedVideos.VideoDetectionTabViewModel
import com.myAllVideoBrowser.ui.main.link.DownloadLinkViewModel
import com.myAllVideoBrowser.ui.main.player.VideoPlayerViewModel
import com.myAllVideoBrowser.ui.main.progress.ProgressViewModel
Expand Down Expand Up @@ -92,11 +92,11 @@ abstract class ViewModelModule {

@Binds
@IntoMap
@ViewModelKey(VideoDetectionAlgVModel::class)
abstract fun bindVideoDetectionAlgViewModel(viewModel: VideoDetectionAlgVModel): ViewModel
@ViewModelKey(GlobalVideoDetectionModel::class)
abstract fun bindVideoDetectionAlgViewModel(viewModel: GlobalVideoDetectionModel): ViewModel

@Binds
@IntoMap
@ViewModelKey(DetectedVideosTabViewModel::class)
abstract fun bindVideoDetectionDetectedViewModel(viewModel: DetectedVideosTabViewModel): ViewModel
@ViewModelKey(VideoDetectionTabViewModel::class)
abstract fun bindVideoDetectionDetectedViewModel(viewModel: VideoDetectionTabViewModel): ViewModel
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,21 @@ import com.myAllVideoBrowser.R
import com.myAllVideoBrowser.data.local.room.entity.VideoInfo
import com.myAllVideoBrowser.databinding.ItemVideoInfoBinding
import com.myAllVideoBrowser.ui.component.dialog.DownloadTabListener
import com.myAllVideoBrowser.ui.main.home.browser.detectedVideos.DetectedVideosTabViewModel
import com.myAllVideoBrowser.ui.main.home.browser.detectedVideos.VideoDetectionTabViewModel
import com.myAllVideoBrowser.util.AppUtil
import com.myAllVideoBrowser.util.FileUtil

class VideoInfoAdapter(
private var videoInfoList: List<VideoInfo>,
private val model: DetectedVideosTabViewModel,
private val model: VideoDetectionTabViewModel,
private val downloadVideoListener: DownloadTabListener,
private val appUtil: AppUtil
) :
RecyclerView.Adapter<VideoInfoAdapter.VideoInfoViewHolder>() {

class VideoInfoViewHolder(
val binding: ItemVideoInfoBinding,
val model: DetectedVideosTabViewModel,
val model: VideoDetectionTabViewModel,
private val candidateFormatListener: DownloadTabListener,
private val appUtil: AppUtil
) :
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import com.myAllVideoBrowser.ui.main.base.BaseFragment
import com.myAllVideoBrowser.ui.main.history.HistoryViewModel
import com.myAllVideoBrowser.ui.main.home.MainActivity
import com.myAllVideoBrowser.ui.main.home.MainViewModel
import com.myAllVideoBrowser.ui.main.home.browser.detectedVideos.VideoDetectionAlgVModel
import com.myAllVideoBrowser.ui.main.home.browser.detectedVideos.GlobalVideoDetectionModel
import com.myAllVideoBrowser.ui.main.home.browser.homeTab.BrowserHomeFragment
import com.myAllVideoBrowser.ui.main.home.browser.webTab.WebTab
import com.myAllVideoBrowser.ui.main.home.browser.webTab.WebTabFragment
Expand Down Expand Up @@ -154,18 +154,17 @@ class BrowserFragment : BaseFragment(), BrowserServicesProvider {

private lateinit var settingsModel: SettingsViewModel

private lateinit var videoDetectionModel: VideoDetectionAlgVModel
private lateinit var videoDetectionModel: GlobalVideoDetectionModel

private val compositeDisposable = CompositeDisposable()

private var backPressedOnce = false

private val requestPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
AppLogger.d("Permissions for writing isGranted: $isGranted")
}
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
AppLogger.d("Permissions for writing isGranted: $isGranted")
}

private val serviceWorkerClient = object : ServiceWorkerClient() {
override fun shouldInterceptRequest(request: WebResourceRequest): WebResourceResponse? {
Expand All @@ -185,12 +184,9 @@ class BrowserFragment : BaseFragment(), BrowserServicesProvider {
}
}

val contentType =
VideoUtils.getContentTypeByUrl(
url,
requestWithCookies?.headers,
okHttpProxyClient
)
val contentType = VideoUtils.getContentTypeByUrl(
url, requestWithCookies?.headers, okHttpProxyClient
)

if (contentType == ContentType.MPD || contentType == ContentType.M3U8 || url.contains(
".m3u8"
Expand Down Expand Up @@ -291,7 +287,7 @@ class BrowserFragment : BaseFragment(), BrowserServicesProvider {
browserViewModel = ViewModelProvider(this, viewModelFactory)[BrowserViewModel::class.java]
historyModel = ViewModelProvider(this, viewModelFactory)[HistoryViewModel::class.java]
videoDetectionModel =
ViewModelProvider(this, viewModelFactory)[VideoDetectionAlgVModel::class.java]
ViewModelProvider(this, viewModelFactory)[GlobalVideoDetectionModel::class.java]

videoDetectionModel.settingsModel = mainActivity.settingsViewModel
browserViewModel.settingsModel = mainActivity.settingsViewModel
Expand Down Expand Up @@ -338,10 +334,8 @@ class BrowserFragment : BaseFragment(), BrowserServicesProvider {

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
if (ContextCompat.checkSelfPermission(
mainActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
!= PackageManager.PERMISSION_GRANTED
mainActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import com.myAllVideoBrowser.util.AppUtil
import javax.inject.Inject

class DetectedVideosTabFragment : BaseFragment() {
var detectedVideosTabViewModel: DetectedVideosTabViewModel? = null
var detectedVideosTabViewModel: VideoDetectionTabViewModel? = null
var candidateFormatListener: DownloadTabListener? = null

@Inject
Expand Down
Loading

0 comments on commit 3dcb25d

Please sign in to comment.