removed unessessary loading of trailers if disabled and added trailers to anilist

This commit is contained in:
LagradOst 2022-06-17 22:43:42 +02:00
parent 7065b0796c
commit 81938a565f
11 changed files with 76 additions and 39 deletions

View file

@ -17,6 +17,7 @@ import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.aniListApi import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.aniListApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.malApi import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.malApi
import com.lagradost.cloudstream3.ui.player.SubtitleData import com.lagradost.cloudstream3.ui.player.SubtitleData
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.isTvSettings
import com.lagradost.cloudstream3.utils.AppUtils.toJson import com.lagradost.cloudstream3.utils.AppUtils.toJson
import com.lagradost.cloudstream3.utils.ExtractorLink import com.lagradost.cloudstream3.utils.ExtractorLink
import com.lagradost.cloudstream3.utils.loadExtractor import com.lagradost.cloudstream3.utils.loadExtractor
@ -298,6 +299,16 @@ object APIHolder {
return realSet return realSet
} }
fun Context.updateHasTrailers() {
LoadResponse.isTrailersEnabled = getHasTrailers()
}
private fun Context.getHasTrailers(): Boolean {
if (this.isTvSettings()) return false
val settingsManager = PreferenceManager.getDefaultSharedPreferences(this)
return settingsManager.getBoolean(this.getString(R.string.show_trailers_key), true)
}
fun Context.filterProviderByPreferredMedia(hasHomePageIsRequired: Boolean = true): List<MainAPI> { fun Context.filterProviderByPreferredMedia(hasHomePageIsRequired: Boolean = true): List<MainAPI> {
val settingsManager = PreferenceManager.getDefaultSharedPreferences(this) val settingsManager = PreferenceManager.getDefaultSharedPreferences(this)
val currentPrefMedia = val currentPrefMedia =
@ -865,6 +876,7 @@ interface LoadResponse {
companion object { companion object {
private val malIdPrefix = malApi.idPrefix private val malIdPrefix = malApi.idPrefix
private val aniListIdPrefix = aniListApi.idPrefix private val aniListIdPrefix = aniListApi.idPrefix
var isTrailersEnabled = true
@JvmName("addActorNames") @JvmName("addActorNames")
fun LoadResponse.addActors(actors: List<String>?) { fun LoadResponse.addActors(actors: List<String>?) {
@ -900,7 +912,7 @@ interface LoadResponse {
/**better to call addTrailer with mutible trailers directly instead of calling this multiple times*/ /**better to call addTrailer with mutible trailers directly instead of calling this multiple times*/
suspend fun LoadResponse.addTrailer(trailerUrl: String?, referer: String? = null) { suspend fun LoadResponse.addTrailer(trailerUrl: String?, referer: String? = null) {
if (trailerUrl == null) return if (!isTrailersEnabled || trailerUrl == null) return
try { try {
val newTrailers = loadExtractor(trailerUrl, referer) val newTrailers = loadExtractor(trailerUrl, referer)
addTrailer(newTrailers) addTrailer(newTrailers)
@ -920,7 +932,7 @@ interface LoadResponse {
} }
suspend fun LoadResponse.addTrailer(trailerUrls: List<String>?, referer: String? = null) { suspend fun LoadResponse.addTrailer(trailerUrls: List<String>?, referer: String? = null) {
if (trailerUrls == null) return if (!isTrailersEnabled || trailerUrls == null) return
val newTrailers = trailerUrls.apmap { trailerUrl -> val newTrailers = trailerUrls.apmap { trailerUrl ->
try { try {
loadExtractor(trailerUrl, referer) loadExtractor(trailerUrl, referer)

View file

@ -28,6 +28,7 @@ import com.lagradost.cloudstream3.APIHolder.allProviders
import com.lagradost.cloudstream3.APIHolder.apis import com.lagradost.cloudstream3.APIHolder.apis
import com.lagradost.cloudstream3.APIHolder.getApiDubstatusSettings import com.lagradost.cloudstream3.APIHolder.getApiDubstatusSettings
import com.lagradost.cloudstream3.APIHolder.initAll import com.lagradost.cloudstream3.APIHolder.initAll
import com.lagradost.cloudstream3.APIHolder.updateHasTrailers
import com.lagradost.cloudstream3.CommonActivity.loadThemes import com.lagradost.cloudstream3.CommonActivity.loadThemes
import com.lagradost.cloudstream3.CommonActivity.onColorSelectedEvent import com.lagradost.cloudstream3.CommonActivity.onColorSelectedEvent
import com.lagradost.cloudstream3.CommonActivity.onDialogDismissedEvent import com.lagradost.cloudstream3.CommonActivity.onDialogDismissedEvent
@ -614,6 +615,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener {
loadCache() loadCache()
test() test()
NewPipe.init(DownloaderTestImpl.getInstance()) NewPipe.init(DownloaderTestImpl.getInstance())
updateHasTrailers()
/*nav_view.setOnNavigationItemSelectedListener { item -> /*nav_view.setOnNavigationItemSelectedListener { item ->
when (item.itemId) { when (item.itemId) {
R.id.navigation_home -> { R.id.navigation_home -> {

View file

@ -10,7 +10,15 @@ import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeStreamExt
import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeStreamLinkHandlerFactory import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeStreamLinkHandlerFactory
import org.schabi.newpipe.extractor.stream.VideoStream import org.schabi.newpipe.extractor.stream.VideoStream
class YoutubeExtractor : ExtractorApi() { class YoutubeShortLinkExtractor : YoutubeExtractor() {
override val mainUrl = "https://youtu.be"
override fun getExtractorUrl(id: String): String {
return "$mainUrl/$id"
}
}
open class YoutubeExtractor : ExtractorApi() {
override val mainUrl = "https://www.youtube.com" override val mainUrl = "https://www.youtube.com"
override val requiresReferer = false override val requiresReferer = false
override val name = "YouTube" override val name = "YouTube"
@ -20,7 +28,7 @@ class YoutubeExtractor : ExtractorApi() {
} }
override fun getExtractorUrl(id: String): String { override fun getExtractorUrl(id: String): String {
return "https://www.youtube.com/watch?v=$id" return "$mainUrl/watch?v=$id"
} }
override suspend fun getUrl(url: String, referer: String?): List<ExtractorLink>? { override suspend fun getUrl(url: String, referer: String?): List<ExtractorLink>? {

View file

@ -61,7 +61,7 @@ class MultiAnimeProvider : MainAPI() {
plot = res.synopsis plot = res.synopsis
tags = res.genres tags = res.genres
rating = res.publicScore rating = res.publicScore
addTrailer(res.trailerUrl) addTrailer(res.trailers)
addAniListId(res.id.toIntOrNull()) addAniListId(res.id.toIntOrNull())
recommendations = res.recommendations recommendations = res.recommendations
} }

View file

@ -67,7 +67,7 @@ interface SyncAPI : OAuth2API {
var studio: List<String>? = null, var studio: List<String>? = null,
var genres: List<String>? = null, var genres: List<String>? = null,
var synonyms: List<String>? = null, var synonyms: List<String>? = null,
var trailerUrl: String? = null, var trailers: List<String>? = null,
var isAdult : Boolean? = null, var isAdult : Boolean? = null,
var posterUrl: String? = null, var posterUrl: String? = null,
var backgroundPosterUrl : String? = null, var backgroundPosterUrl : String? = null,

View file

@ -142,6 +142,10 @@ class AniListApi(index: Int) : AccountManager(index), SyncAPI {
getUrlFromId(recMedia.id), getUrlFromId(recMedia.id),
recMedia.coverImage?.large ?: recMedia.coverImage?.medium recMedia.coverImage?.large ?: recMedia.coverImage?.medium
) )
},
trailers = when (season.trailer?.site?.lowercase()?.trim()) {
"youtube" -> listOf("https://www.youtube.com/watch?v=${season.trailer.id}")
else -> null
} }
//TODO REST //TODO REST
) )

View file

@ -195,7 +195,7 @@ class MALApi(index: Int) : AccountManager(index), SyncAPI {
).text ).text
return mapper.readValue<MalAnime>(res).let { malAnime -> return mapper.readValue<MalAnime>(res).let { malAnime ->
SyncAPI.SyncResult( SyncAPI.SyncResult(
id = malAnime.id?.toString()!!, id = internalId.toString(),
totalEpisodes = malAnime.numEpisodes, totalEpisodes = malAnime.numEpisodes,
title = malAnime.title, title = malAnime.title,
publicScore = malAnime.mean?.toFloat()?.times(1000)?.toInt(), publicScore = malAnime.mean?.toFloat()?.times(1000)?.toInt(),
@ -209,7 +209,7 @@ class MALApi(index: Int) : AccountManager(index), SyncAPI {
nextAiring = null, nextAiring = null,
studio = malAnime.studios?.mapNotNull { it.name }, studio = malAnime.studios?.mapNotNull { it.name },
genres = malAnime.genres?.map { it.name }, genres = malAnime.genres?.map { it.name },
trailerUrl = null, trailers = null,
startDate = parseDate(malAnime.startDate), startDate = parseDate(malAnime.startDate),
endDate = parseDate(malAnime.endDate), endDate = parseDate(malAnime.endDate),
recommendations = malAnime.recommendations?.mapNotNull { rec -> recommendations = malAnime.recommendations?.mapNotNull { rec ->

View file

@ -41,6 +41,7 @@ import com.google.android.material.button.MaterialButton
import com.lagradost.cloudstream3.* import com.lagradost.cloudstream3.*
import com.lagradost.cloudstream3.APIHolder.getApiFromName import com.lagradost.cloudstream3.APIHolder.getApiFromName
import com.lagradost.cloudstream3.APIHolder.getId import com.lagradost.cloudstream3.APIHolder.getId
import com.lagradost.cloudstream3.APIHolder.updateHasTrailers
import com.lagradost.cloudstream3.AcraApplication.Companion.setKey import com.lagradost.cloudstream3.AcraApplication.Companion.setKey
import com.lagradost.cloudstream3.CommonActivity.getCastSession import com.lagradost.cloudstream3.CommonActivity.getCastSession
import com.lagradost.cloudstream3.CommonActivity.showToast import com.lagradost.cloudstream3.CommonActivity.showToast
@ -644,15 +645,10 @@ class ResultFragment : ResultTrailerPlayer() {
} }
private fun setTrailers(trailers: List<ExtractorLink>?) { private fun setTrailers(trailers: List<ExtractorLink>?) {
context?.let { ctx -> context?.updateHasTrailers()
if (ctx.isTvSettings()) return if (!LoadResponse.isTrailersEnabled) return
val settingsManager = PreferenceManager.getDefaultSharedPreferences(ctx) currentTrailers = trailers?.sortedBy { -it.quality } ?: emptyList()
val showTrailers = loadTrailer()
settingsManager.getBoolean(ctx.getString(R.string.show_trailers_key), true)
if (!showTrailers) return
currentTrailers = trailers?.sortedBy { -it.quality } ?: emptyList()
loadTrailer()
}
} }
private fun setActors(actors: List<ActorData>?) { private fun setActors(actors: List<ActorData>?) {
@ -776,6 +772,7 @@ class ResultFragment : ResultTrailerPlayer() {
activity?.window?.decorView?.clearFocus() activity?.window?.decorView?.clearFocus()
hideKeyboard() hideKeyboard()
context?.updateHasTrailers()
activity?.loadCache() activity?.loadCache()
activity?.fixPaddingStatusbar(result_top_bar) activity?.fixPaddingStatusbar(result_top_bar)

View file

@ -24,6 +24,7 @@ import com.lagradost.cloudstream3.ui.WatchType
import com.lagradost.cloudstream3.ui.player.IGenerator import com.lagradost.cloudstream3.ui.player.IGenerator
import com.lagradost.cloudstream3.ui.player.RepoLinkGenerator import com.lagradost.cloudstream3.ui.player.RepoLinkGenerator
import com.lagradost.cloudstream3.ui.player.SubtitleData import com.lagradost.cloudstream3.ui.player.SubtitleData
import com.lagradost.cloudstream3.utils.Coroutines.ioWork
import com.lagradost.cloudstream3.utils.DOWNLOAD_HEADER_CACHE import com.lagradost.cloudstream3.utils.DOWNLOAD_HEADER_CACHE
import com.lagradost.cloudstream3.utils.DataStoreHelper import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.DataStoreHelper.getBookmarkedData import com.lagradost.cloudstream3.utils.DataStoreHelper.getBookmarkedData
@ -70,7 +71,6 @@ class ResultViewModel : ViewModel() {
val dubStatus: LiveData<DubStatus> get() = _dubStatus val dubStatus: LiveData<DubStatus> get() = _dubStatus
private val _dubStatus: MutableLiveData<DubStatus> = MutableLiveData() private val _dubStatus: MutableLiveData<DubStatus> = MutableLiveData()
private val page: MutableLiveData<LoadResponse> = MutableLiveData()
val id: MutableLiveData<Int> = MutableLiveData() val id: MutableLiveData<Int> = MutableLiveData()
val selectedSeason: MutableLiveData<Int> = MutableLiveData(-2) val selectedSeason: MutableLiveData<Int> = MutableLiveData(-2)
val seasonSelections: MutableLiveData<List<Int?>> = MutableLiveData() val seasonSelections: MutableLiveData<List<Int?>> = MutableLiveData()
@ -88,11 +88,12 @@ class ResultViewModel : ViewModel() {
fun updateWatchStatus(status: WatchType) = viewModelScope.launch { fun updateWatchStatus(status: WatchType) = viewModelScope.launch {
val currentId = id.value ?: return@launch val currentId = id.value ?: return@launch
_watchStatus.postValue(status) _watchStatus.postValue(status)
val resultPage = page.value val resultPage = _resultResponse.value
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
setResultWatchState(currentId, status.internalId) setResultWatchState(currentId, status.internalId)
if (resultPage != null) { if (resultPage != null && resultPage is Resource.Success) {
val resultPageData = resultPage.value
val current = getBookmarkedData(currentId) val current = getBookmarkedData(currentId)
val currentTime = System.currentTimeMillis() val currentTime = System.currentTimeMillis()
setBookmarkedData( setBookmarkedData(
@ -101,12 +102,12 @@ class ResultViewModel : ViewModel() {
currentId, currentId,
current?.bookmarkedTime ?: currentTime, current?.bookmarkedTime ?: currentTime,
currentTime, currentTime,
resultPage.name, resultPageData.name,
resultPage.url, resultPageData.url,
resultPage.apiName, resultPageData.apiName,
resultPage.type, resultPageData.type,
resultPage.posterUrl, resultPageData.posterUrl,
resultPage.year resultPageData.year
) )
) )
} }
@ -120,7 +121,6 @@ class ResultViewModel : ViewModel() {
var lastMeta: SyncAPI.SyncResult? = null var lastMeta: SyncAPI.SyncResult? = null
private suspend fun applyMeta(resp: LoadResponse, meta: SyncAPI.SyncResult?): LoadResponse { private suspend fun applyMeta(resp: LoadResponse, meta: SyncAPI.SyncResult?): LoadResponse {
if (meta == null) return resp if (meta == null) return resp
lastMeta = meta
return resp.apply { return resp.apply {
Log.i(TAG, "applyMeta") Log.i(TAG, "applyMeta")
@ -128,7 +128,7 @@ class ResultViewModel : ViewModel() {
rating = rating ?: meta.publicScore rating = rating ?: meta.publicScore
tags = tags ?: meta.genres tags = tags ?: meta.genres
plot = if (plot.isNullOrBlank()) meta.synopsis else plot plot = if (plot.isNullOrBlank()) meta.synopsis else plot
addTrailer(meta.trailerUrl) addTrailer(meta.trailers)
posterUrl = posterUrl ?: meta.posterUrl ?: meta.backgroundPosterUrl posterUrl = posterUrl ?: meta.posterUrl ?: meta.backgroundPosterUrl
actors = actors ?: meta.actors actors = actors ?: meta.actors
@ -142,13 +142,20 @@ class ResultViewModel : ViewModel() {
recommendations = recommendations?.union(realRecommendations)?.toList() recommendations = recommendations?.union(realRecommendations)?.toList()
?: realRecommendations ?: realRecommendations
println("THIS:$this")
} }
} }
fun setMeta(meta: SyncAPI.SyncResult) = viewModelScope.launch { fun setMeta(meta: SyncAPI.SyncResult) = viewModelScope.launch {
Log.i(TAG, "setMeta") Log.i(TAG, "setMeta")
(result.value as? Resource.Success<LoadResponse>?)?.value?.let { resp -> lastMeta = meta
_resultResponse.postValue(Resource.Success(applyMeta(resp, meta))) ioWork {
(result.value as? Resource.Success<LoadResponse>?)?.value?.let { resp ->
val value = Resource.Success(applyMeta(resp, meta))
println("POSTED: $value")
_resultResponse.postValue(value)
}
} }
} }
@ -356,8 +363,10 @@ class ResultViewModel : ViewModel() {
when (data) { when (data) {
is Resource.Success -> { is Resource.Success -> {
val loadResponse = applyMeta(data.value, lastMeta) val loadResponse = if (lastMeta != null) ioWork {
page.postValue(loadResponse) applyMeta(data.value, lastMeta)
} else data.value
_resultResponse.postValue(Resource.Success(loadResponse))
val mainId = loadResponse.getId() val mainId = loadResponse.getId()
id.postValue(mainId) id.postValue(mainId)
loadWatchStatus(mainId) loadWatchStatus(mainId)

View file

@ -3,28 +3,31 @@ package com.lagradost.cloudstream3.utils
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import com.lagradost.cloudstream3.mvvm.logError import com.lagradost.cloudstream3.mvvm.logError
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
object Coroutines { object Coroutines {
fun main(work: suspend (() -> Unit)) : Job { fun main(work: suspend (() -> Unit)): Job {
return CoroutineScope(Dispatchers.Main).launch { return CoroutineScope(Dispatchers.Main).launch {
work() work()
} }
} }
fun ioSafe(work: suspend (() -> Unit)) : Job { fun ioSafe(work: suspend (() -> Unit)): Job {
return CoroutineScope(Dispatchers.IO).launch { return CoroutineScope(Dispatchers.IO).launch {
try { try {
work() work()
} catch (e : Exception) { } catch (e: Exception) {
logError(e) logError(e)
} }
} }
} }
suspend fun <T> ioWork(work: suspend (() -> T)): T {
return withContext(Dispatchers.IO) {
work()
}
}
fun runOnMainThread(work: (() -> Unit)) { fun runOnMainThread(work: (() -> Unit)) {
val mainHandler = Handler(Looper.getMainLooper()) val mainHandler = Handler(Looper.getMainLooper())
mainHandler.post { mainHandler.post {

View file

@ -218,7 +218,9 @@ val extractorApis: Array<ExtractorApi> = arrayOf(
KotakAnimeid(), KotakAnimeid(),
Neonime8n(), Neonime8n(),
Neonime7n(), Neonime7n(),
YoutubeExtractor(), YoutubeExtractor(),
YoutubeShortLinkExtractor(),
) )
fun getExtractorApiFromName(name: String): ExtractorApi { fun getExtractorApiFromName(name: String): ExtractorApi {