Initial commit

This commit is contained in:
almightyhak 2024-06-20 11:54:12 +07:00
commit 98ed7e8839
2263 changed files with 108711 additions and 0 deletions

View file

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity
android:name="eu.kanade.tachiyomi.multisrc.animestream.AnimeStreamUrlActivity"
android:excludeFromRecents="true"
android:exported="true"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="${SOURCEHOST}"
android:pathPattern="/..*"
android:scheme="${SOURCESCHEME}" />
</intent-filter>
</activity>
</application>
</manifest>

View file

@ -0,0 +1,5 @@
plugins {
id("lib-multisrc")
}
baseVersionCode = 2

View file

@ -0,0 +1,431 @@
package eu.kanade.tachiyomi.multisrc.animestream
import android.app.Application
import android.util.Base64
import android.util.Log
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource
import eu.kanade.tachiyomi.multisrc.animestream.AnimeStreamFilters.GenresFilter
import eu.kanade.tachiyomi.multisrc.animestream.AnimeStreamFilters.OrderFilter
import eu.kanade.tachiyomi.multisrc.animestream.AnimeStreamFilters.SeasonFilter
import eu.kanade.tachiyomi.multisrc.animestream.AnimeStreamFilters.StatusFilter
import eu.kanade.tachiyomi.multisrc.animestream.AnimeStreamFilters.StudioFilter
import eu.kanade.tachiyomi.multisrc.animestream.AnimeStreamFilters.SubFilter
import eu.kanade.tachiyomi.multisrc.animestream.AnimeStreamFilters.TypeFilter
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.awaitSuccess
import eu.kanade.tachiyomi.util.asJsoup
import eu.kanade.tachiyomi.util.parallelCatchingFlatMapBlocking
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import okhttp3.Response
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.text.SimpleDateFormat
import java.util.Locale
abstract class AnimeStream(
override val lang: String,
override val name: String,
override val baseUrl: String,
) : ConfigurableAnimeSource, ParsedAnimeHttpSource() {
override val supportsLatest = true
protected open val preferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
companion object {
const val PREFIX_SEARCH = "path:"
}
protected open val prefQualityDefault = "720p"
protected open val prefQualityKey = "preferred_quality"
protected open val prefQualityTitle = when (lang) {
"pt-BR" -> "Qualidade preferida"
else -> "Preferred quality"
}
protected open val prefQualityValues = arrayOf("1080p", "720p", "480p", "360p")
protected open val prefQualityEntries = prefQualityValues
protected open val videoSortPrefKey = prefQualityKey
protected open val videoSortPrefDefault = prefQualityDefault
protected open val dateFormatter by lazy {
val locale = when (lang) {
"pt-BR" -> Locale("pt", "BR")
else -> Locale.ENGLISH
}
SimpleDateFormat("MMMM d, yyyy", locale)
}
protected open val animeListUrl = "$baseUrl/anime"
// ============================== Popular ===============================
override suspend fun getPopularAnime(page: Int): AnimesPage {
fetchFilterList()
return super.getPopularAnime(page)
}
override fun popularAnimeRequest(page: Int) = GET("$animeListUrl/?page=$page&order=popular")
override fun popularAnimeSelector() = searchAnimeSelector()
override fun popularAnimeFromElement(element: Element) = searchAnimeFromElement(element)
override fun popularAnimeNextPageSelector(): String? = searchAnimeNextPageSelector()
// =============================== Latest ===============================
override suspend fun getLatestUpdates(page: Int): AnimesPage {
fetchFilterList()
return super.getLatestUpdates(page)
}
override fun latestUpdatesRequest(page: Int) = GET("$animeListUrl/?page=$page&order=update")
override fun latestUpdatesSelector() = searchAnimeSelector()
override fun latestUpdatesFromElement(element: Element) = searchAnimeFromElement(element)
override fun latestUpdatesNextPageSelector(): String? = searchAnimeNextPageSelector()
// =============================== Search ===============================
override suspend fun getSearchAnime(page: Int, query: String, filters: AnimeFilterList): AnimesPage {
return if (query.startsWith(PREFIX_SEARCH)) { // URL intent handler
val path = query.removePrefix(PREFIX_SEARCH)
client.newCall(GET("$baseUrl/$path"))
.awaitSuccess()
.use(::searchAnimeByPathParse)
} else {
super.getSearchAnime(page, query, filters)
}
}
protected open fun searchAnimeByPathParse(response: Response): AnimesPage {
val details = animeDetailsParse(response.asJsoup())
return AnimesPage(listOf(details), false)
}
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request {
val params = AnimeStreamFilters.getSearchParameters(filters)
return if (query.isNotEmpty()) {
GET("$baseUrl/page/$page/?s=$query")
} else {
val multiString = buildString {
if (params.genres.isNotEmpty()) append(params.genres + "&")
if (params.seasons.isNotEmpty()) append(params.seasons + "&")
if (params.studios.isNotEmpty()) append(params.studios + "&")
}
GET("$animeListUrl/?page=$page&$multiString&status=${params.status}&type=${params.type}&sub=${params.sub}&order=${params.order}")
}
}
override fun searchAnimeSelector() = "div.listupd article a.tip"
override fun searchAnimeFromElement(element: Element): SAnime {
return SAnime.create().apply {
setUrlWithoutDomain(element.attr("abs:href"))
title = element.selectFirst("div.tt, div.ttl")!!.ownText()
thumbnail_url = element.selectFirst("img")?.getImageUrl()
}
}
override fun searchAnimeNextPageSelector(): String? = "div.pagination a.next, div.hpage > a.r"
// ============================== Filters ===============================
/**
* Disable it if you don't want the filters to be automatically fetched.
*/
protected open val fetchFilters = true
protected open val filtersSelector = "span.sec1 > div.filter > ul"
private fun fetchFilterList() {
if (fetchFilters && !AnimeStreamFilters.filterInitialized()) {
AnimeStreamFilters.filterElements = runBlocking {
withContext(Dispatchers.IO) {
client.newCall(GET(animeListUrl)).execute()
.asJsoup()
.select(filtersSelector)
}
}
}
}
protected open val filtersHeader = when (lang) {
"pt-BR" -> "NOTA: Filtros serão ignorados se usar a pesquisa por nome!"
else -> "NOTE: Filters are going to be ignored if using search text!"
}
protected open val filtersMissingWarning: String = when (lang) {
"pt-BR" -> "Aperte 'Redefinir' para tentar mostrar os filtros"
else -> "Press 'Reset' to attempt to show the filters"
}
protected open val genresFilterText = when (lang) {
"pt-BR" -> "Gêneros"
else -> "Genres"
}
protected open val seasonsFilterText = when (lang) {
"pt-BR" -> "Temporadas"
else -> "Seasons"
}
protected open val studioFilterText = when (lang) {
"pt-BR" -> "Estúdios"
else -> "Studios"
}
protected open val statusFilterText = "Status"
protected open val typeFilterText = when (lang) {
"pt-BR" -> "Tipo"
else -> "Type"
}
protected open val subFilterText = when (lang) {
"pt-BR" -> "Legenda"
else -> "Subtitle"
}
protected open val orderFilterText = when (lang) {
"pt-BR" -> "Ordem"
else -> "Order"
}
override fun getFilterList(): AnimeFilterList {
return if (fetchFilters && AnimeStreamFilters.filterInitialized()) {
AnimeFilterList(
GenresFilter(genresFilterText),
SeasonFilter(seasonsFilterText),
StudioFilter(studioFilterText),
AnimeFilter.Separator(),
StatusFilter(statusFilterText),
TypeFilter(typeFilterText),
SubFilter(subFilterText),
OrderFilter(orderFilterText),
)
} else if (fetchFilters) {
AnimeFilterList(AnimeFilter.Header(filtersMissingWarning))
} else {
AnimeFilterList()
}
}
// =========================== Anime Details ============================
protected open val animeDetailsSelector = "div.info-content, div.right ul.data"
protected open val animeAltNameSelector = ".alter"
protected open val animeTitleSelector = "h1.entry-title"
protected open val animeThumbnailSelector = "div.thumb > img, div.limage > img"
protected open val animeGenresSelector = "div.genxed > a, li:contains(Genre:) a"
protected open val animeDescriptionSelector = ".entry-content[itemprop=description], .desc"
protected open val animeAdditionalInfoSelector = "div.spe > span, li:has(b)"
protected open val animeStatusText = "Status"
protected open val animeAuthorText = "Fansub"
protected open val animeArtistText = when (lang) {
"pt-BR" -> "Estudio"
else -> "Studio"
}
protected open val animeAltNamePrefix = when (lang) {
"pt-BR" -> "Nome(s) alternativo(s): "
else -> "Alternative name(s): "
}
protected open fun getAnimeDescription(document: Document) =
document.selectFirst(animeDescriptionSelector)?.text()
override fun animeDetailsParse(document: Document): SAnime {
return SAnime.create().apply {
setUrlWithoutDomain(document.location())
title = document.selectFirst(animeTitleSelector)!!.text()
thumbnail_url = document.selectFirst(animeThumbnailSelector)?.getImageUrl()
val infos = document.selectFirst(animeDetailsSelector)!!
genre = infos.select(animeGenresSelector).eachText().joinToString()
status = parseStatus(infos.getInfo(animeStatusText))
artist = infos.getInfo(animeArtistText)
author = infos.getInfo(animeAuthorText)
description = buildString {
getAnimeDescription(document)?.also {
append("$it\n\n")
}
document.selectFirst(animeAltNameSelector)?.text()
?.takeIf(String::isNotBlank)
?.also { append("$animeAltNamePrefix$it\n") }
infos.select(animeAdditionalInfoSelector).eachText().forEach {
append("$it\n")
}
}
}
}
// ============================== Episodes ==============================
override fun episodeListParse(response: Response): List<SEpisode> {
val doc = response.asJsoup()
return doc.select(episodeListSelector()).map(::episodeFromElement)
}
override fun episodeListSelector() = "div.eplister > ul > li > a"
protected open val episodePrefix = when (lang) {
"pt-BR" -> "Episódio"
else -> "Episode"
}
@Suppress("unused_parameter")
protected open fun getEpisodeName(element: Element, epNum: String) = "$episodePrefix $epNum"
override fun episodeFromElement(element: Element): SEpisode {
return SEpisode.create().apply {
setUrlWithoutDomain(element.attr("href"))
element.selectFirst(".epl-num")!!.text().let {
name = getEpisodeName(element, it)
episode_number = it.substringBefore(" ").toFloatOrNull() ?: 0F
}
element.selectFirst(".epl-sub")?.text()?.let { scanlator = it }
date_upload = element.selectFirst(".epl-date")?.text().toDate()
}
}
// ============================ Video Links =============================
override fun videoListSelector() = "select.mirror > option[data-index], ul.mirror a[data-em]"
override fun videoListParse(response: Response): List<Video> {
val items = response.asJsoup().select(videoListSelector())
return items.parallelCatchingFlatMapBlocking { element ->
val name = element.text()
val url = getHosterUrl(element)
getVideoList(url, name)
}
}
protected open fun getHosterUrl(element: Element): String {
val encodedData = when (element.tagName()) {
"option" -> element.attr("value")
"a" -> element.attr("data-em")
else -> throw Exception()
}
return getHosterUrl(encodedData)
}
// Taken from LuciferDonghua
protected open fun getHosterUrl(encodedData: String): String {
val doc = if (encodedData.toHttpUrlOrNull() == null) {
Base64.decode(encodedData, Base64.DEFAULT)
.let(::String) // bytearray -> string
.let(Jsoup::parse) // string -> document
} else {
client.newCall(GET(encodedData, headers)).execute().asJsoup()
}
return doc.selectFirst("iframe[src~=.]")?.safeUrl()
?: doc.selectFirst("meta[content~=.][itemprop=embedUrl]")!!.safeUrl("content")
}
private fun Element.safeUrl(attribute: String = "src"): String {
val value = attr(attribute)
return when {
value.startsWith("http") -> value
value.startsWith("//") -> "https:$value"
else -> absUrl(attribute).ifEmpty { value }
}
}
protected open fun getVideoList(url: String, name: String): List<Video> {
Log.i(name, "getVideoList -> URL => $url || Name => $name")
return emptyList()
}
override fun videoFromElement(element: Element) = throw UnsupportedOperationException()
override fun videoUrlParse(document: Document) = throw UnsupportedOperationException()
// ============================== Settings ==============================
override fun setupPreferenceScreen(screen: PreferenceScreen) {
val videoQualityPref = ListPreference(screen.context).apply {
key = prefQualityKey
title = prefQualityTitle
entries = prefQualityEntries
entryValues = prefQualityValues
setDefaultValue(prefQualityDefault)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}
screen.addPreference(videoQualityPref)
}
// ============================= Utilities ==============================
override fun List<Video>.sort(): List<Video> {
val quality = preferences.getString(videoSortPrefKey, videoSortPrefDefault)!!
return sortedWith(
compareBy { it.quality.contains(quality, true) },
).reversed()
}
protected open fun parseStatus(statusString: String?): Int {
return when (statusString?.trim()?.lowercase()) {
"completed", "completo" -> SAnime.COMPLETED
"ongoing", "lançamento" -> SAnime.ONGOING
else -> SAnime.UNKNOWN
}
}
protected open fun Element.getInfo(text: String): String? {
return selectFirst("span:contains($text)")
?.run {
selectFirst("a")?.text() ?: ownText()
}
}
protected open fun String?.toDate(): Long {
return this?.let {
runCatching {
dateFormatter.parse(trim())?.time
}.getOrNull()
} ?: 0L
}
/**
* Tries to get the image url via various possible attributes.
* Taken from Tachiyomi's Madara multisrc.
*/
protected open fun Element.getImageUrl(): String? {
return when {
hasAttr("data-src") -> attr("abs:data-src")
hasAttr("data-lazy-src") -> attr("abs:data-lazy-src")
hasAttr("srcset") -> attr("abs:srcset").substringBefore(" ")
else -> attr("abs:src")
}.substringBefore("?resize")
}
}

View file

@ -0,0 +1,94 @@
package eu.kanade.tachiyomi.multisrc.animestream
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import org.jsoup.select.Elements
object AnimeStreamFilters {
open class QueryPartFilter(
displayName: String,
val vals: Array<Pair<String, String>>,
) : AnimeFilter.Select<String>(
displayName,
vals.map { it.first }.toTypedArray(),
) {
fun toQueryPart() = vals[state].second
}
open class CheckBoxFilterList(name: String, val pairs: Array<Pair<String, String>>) :
AnimeFilter.Group<AnimeFilter.CheckBox>(name, pairs.map { CheckBoxVal(it.first, false) })
private class CheckBoxVal(name: String, state: Boolean = false) : AnimeFilter.CheckBox(name, state)
inline fun <reified R> AnimeFilterList.asQueryPart(): String {
return (getFirst<R>() as QueryPartFilter).toQueryPart()
}
inline fun <reified R> AnimeFilterList.getFirst(): R {
return first { it is R } as R
}
inline fun <reified R> AnimeFilterList.parseCheckbox(
options: Array<Pair<String, String>>,
name: String,
): String {
return (getFirst<R>() as CheckBoxFilterList).state
.filter { it.state }
.map { checkbox -> options.find { it.first == checkbox.name }!!.second }
.filter(String::isNotBlank)
.joinToString("&") { "$name[]=$it" }
}
internal class GenresFilter(name: String) : CheckBoxFilterList(name, GENRES_LIST)
internal class SeasonFilter(name: String) : CheckBoxFilterList(name, SEASON_LIST)
internal class StudioFilter(name: String) : CheckBoxFilterList(name, STUDIO_LIST)
internal class StatusFilter(name: String) : QueryPartFilter(name, STATUS_LIST)
internal class TypeFilter(name: String) : QueryPartFilter(name, TYPE_LIST)
internal class SubFilter(name: String) : QueryPartFilter(name, SUB_LIST)
internal class OrderFilter(name: String) : QueryPartFilter(name, ORDER_LIST)
internal data class FilterSearchParams(
val genres: String = "",
val seasons: String = "",
val studios: String = "",
val status: String = "",
val type: String = "",
val sub: String = "",
val order: String = "",
)
internal fun getSearchParameters(filters: AnimeFilterList): FilterSearchParams {
if (filters.isEmpty() || !filterInitialized()) return FilterSearchParams()
return FilterSearchParams(
filters.parseCheckbox<GenresFilter>(GENRES_LIST, "genre"),
filters.parseCheckbox<SeasonFilter>(SEASON_LIST, "season"),
filters.parseCheckbox<StudioFilter>(STUDIO_LIST, "studio"),
filters.asQueryPart<StatusFilter>(),
filters.asQueryPart<TypeFilter>(),
filters.asQueryPart<SubFilter>(),
filters.asQueryPart<OrderFilter>(),
)
}
lateinit var filterElements: Elements
fun filterInitialized() = ::filterElements.isInitialized
fun getPairListByIndex(index: Int) = filterElements.get(index)
.select("li")
.map { element ->
val key = element.selectFirst("label")!!.text()
val value = element.selectFirst("input")!!.attr("value")
Pair(key, value)
}.toTypedArray()
private val GENRES_LIST by lazy { getPairListByIndex(0) }
private val SEASON_LIST by lazy { getPairListByIndex(1) }
private val STUDIO_LIST by lazy { getPairListByIndex(2) }
private val STATUS_LIST by lazy { getPairListByIndex(3) }
private val TYPE_LIST by lazy { getPairListByIndex(4) }
private val SUB_LIST by lazy { getPairListByIndex(5) }
private val ORDER_LIST by lazy { getPairListByIndex(6) }
}

View file

@ -0,0 +1,37 @@
package eu.kanade.tachiyomi.multisrc.animestream
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
class AnimeStreamUrlActivity : Activity() {
private val tag by lazy { javaClass.simpleName }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.isNotEmpty()) {
val path = pathSegments.joinToString("/")
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.ANIMESEARCH"
putExtra("query", "${AnimeStream.PREFIX_SEARCH}$path")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e(tag, e.toString())
}
} else {
Log.e(tag, "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}

View file

@ -0,0 +1,5 @@
plugins {
id("lib-multisrc")
}
baseVersionCode = 1

View file

@ -0,0 +1,214 @@
package eu.kanade.tachiyomi.multisrc.datalifeengine
import android.app.Application
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.network.awaitSuccess
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
abstract class DataLifeEngine(
override val name: String,
override val baseUrl: String,
override val lang: String,
) : ConfigurableAnimeSource, ParsedAnimeHttpSource() {
override val supportsLatest = false
private val preferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) }
// ============================== Popular ===============================
override fun popularAnimeSelector(): String = "div#dle-content > div.mov"
override fun popularAnimeNextPageSelector(): String = "span.navigation > span:not(.nav_ext) + a"
override fun popularAnimeFromElement(element: Element): SAnime {
return SAnime.create().apply {
setUrlWithoutDomain(element.selectFirst("a[href]")!!.attr("href").toHttpUrl().encodedPath)
thumbnail_url = element.selectFirst("img[src]")?.absUrl("src") ?: ""
title = "${element.selectFirst("a[href]")!!.text()} ${element.selectFirst("span.block-sai")?.text() ?: ""}"
}
}
// =============================== Latest ===============================
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException()
override fun latestUpdatesSelector(): String = throw UnsupportedOperationException()
override fun latestUpdatesNextPageSelector(): String = throw UnsupportedOperationException()
override fun latestUpdatesFromElement(element: Element): SAnime = throw UnsupportedOperationException()
// =============================== Search ===============================
// TODO: Implement the *actual* search filters from : https://${baseUrl}/index.php?do=search
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request {
val filterList = if (filters.isEmpty()) getFilterList() else filters
val genreFilter = filterList.find { it is GenreFilter } as GenreFilter
val subPageFilter = filterList.find { it is SubPageFilter } as SubPageFilter
return when {
query.isNotBlank() -> {
if (query.length < 4) throw Exception("La recherche est suspendue! La chaîne de recherche est vide ou contient moins de 4 caractères.")
val postHeaders = headers.newBuilder()
.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
.add("Content-Type", "application/x-www-form-urlencoded")
.add("Host", baseUrl.toHttpUrl().host)
.add("Origin", baseUrl)
.add("Referer", "$baseUrl/")
.build()
val cleanQuery = query.replace(" ", "+")
if (page == 1) {
val postBody = "do=search&subaction=search&story=$cleanQuery".toRequestBody("application/x-www-form-urlencoded".toMediaType())
POST("$baseUrl/", body = postBody, headers = postHeaders)
} else {
val postBody = "do=search&subaction=search&search_start=$page&full_search=0&result_from=11&story=$cleanQuery".toRequestBody("application/x-www-form-urlencoded".toMediaType())
POST("$baseUrl/index.php?do=search", body = postBody, headers = postHeaders)
}
}
genreFilter.state != 0 -> {
GET("$baseUrl${genreFilter.toUriPart()}page/$page/")
}
subPageFilter.state != 0 -> {
GET("$baseUrl${subPageFilter.toUriPart()}page/$page/")
}
else -> popularAnimeRequest(page)
}
}
override fun searchAnimeSelector(): String = popularAnimeSelector()
override fun searchAnimeNextPageSelector(): String = popularAnimeNextPageSelector()
override fun searchAnimeFromElement(element: Element): SAnime = popularAnimeFromElement(element)
// ============================== Filters ===============================
abstract val categories: Array<Pair<String, String>>
abstract val genres: Array<Pair<String, String>>
override fun getFilterList(): AnimeFilterList = AnimeFilterList(
AnimeFilter.Header("La recherche de texte ignore les filtres"),
SubPageFilter(categories),
GenreFilter(genres),
)
private class SubPageFilter(categories: Array<Pair<String, String>>) : UriPartFilter(
"Catégories",
categories,
)
private class GenreFilter(genres: Array<Pair<String, String>>) : UriPartFilter(
"Genres",
genres,
)
private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) :
AnimeFilter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) {
fun toUriPart() = vals[state].second
}
// =========================== Anime Details ============================
override suspend fun getAnimeDetails(anime: SAnime): SAnime {
return client.newCall(animeDetailsRequest(anime))
.awaitSuccess()
.let { response ->
animeDetailsParse(response, anime).apply { initialized = true }
}
}
override fun animeDetailsParse(document: Document): SAnime = throw UnsupportedOperationException()
private fun animeDetailsParse(response: Response, baseAnime: SAnime): SAnime {
val document = response.asJsoup()
return SAnime.create().apply {
title = baseAnime.title
thumbnail_url = baseAnime.thumbnail_url
description = document.selectFirst("div.mov-desc span[itemprop=description]")?.text() ?: ""
genre = document.select("div.mov-desc span[itemprop=genre] a").joinToString(", ") {
it.text()
}
}
}
// ============================= Utilities ==============================
@JvmName("sortSEpisode")
fun List<SEpisode>.sort(): List<SEpisode> = this.sortedWith(
compareBy(
{ it.scanlator },
{ it.episode_number },
),
).reversed()
override fun List<Video>.sort(): List<Video> {
val quality = preferences.getString("preferred_quality", "720")!!
val server = preferences.getString("preferred_server", "Upstream")!!
return this.sortedWith(
compareBy(
{ it.quality.contains(quality) },
{ it.quality.contains(server, true) },
),
).reversed()
}
override fun setupPreferenceScreen(screen: PreferenceScreen) {
val videoQualityPref = ListPreference(screen.context).apply {
key = "preferred_quality"
title = "Preferred quality"
entries = arrayOf("1080p", "720p", "480p", "360p")
entryValues = arrayOf("1080", "720", "480", "360")
setDefaultValue("720")
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}
val videoServerPref = ListPreference(screen.context).apply {
key = "preferred_server"
title = "Preferred server"
entries = arrayOf("Upstream", "Vido", "StreamVid", "StreamHide", "Uqload", "Vudeo", "Doodstream", "Sibnet", "Okru")
entryValues = arrayOf("Upstream", "Vido", "StreamVid", "StreamHide", "Uqload", "Vudeo", "dood", "sibnet", "okru")
setDefaultValue("Upstream")
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}
screen.addPreference(videoQualityPref)
screen.addPreference(videoServerPref)
}
}

View file

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity
android:name="eu.kanade.tachiyomi.multisrc.dooplay.DooPlayUrlActivity"
android:excludeFromRecents="true"
android:exported="true"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="${SOURCEHOST}"
android:pathPattern="/.*/..*"
android:scheme="${SOURCESCHEME}" />
</intent-filter>
</activity>
</application>
</manifest>

View file

@ -0,0 +1,5 @@
plugins {
id("lib-multisrc")
}
baseVersionCode = 1

View file

@ -0,0 +1,485 @@
package eu.kanade.tachiyomi.multisrc.dooplay
import android.app.Application
import android.content.SharedPreferences
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.awaitSuccess
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.text.SimpleDateFormat
import java.util.Locale
/**
* Multisrc class for the DooPlay wordpress theme.
* This class takes some inspiration from Tachiyomi's Madara multisrc class.
*/
abstract class DooPlay(
override val lang: String,
override val name: String,
override val baseUrl: String,
) : ConfigurableAnimeSource, ParsedAnimeHttpSource() {
override val supportsLatest = true
override fun headersBuilder() = super.headersBuilder().add("Referer", baseUrl)
protected open val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
companion object {
/**
* Useful for the URL intent handler.
*/
const val PREFIX_SEARCH = "path:"
}
protected open val prefQualityDefault = "720p"
protected open val prefQualityKey = "preferred_quality"
protected open val prefQualityTitle = when (lang) {
"pt-BR" -> "Qualidade preferida"
else -> "Preferred quality"
}
protected open val prefQualityValues = arrayOf("480p", "720p")
protected open val prefQualityEntries = prefQualityValues
protected open val videoSortPrefKey = prefQualityKey
protected open val videoSortPrefDefault = prefQualityDefault
// ============================== Popular ===============================
override fun popularAnimeSelector() = "article.w_item_a > a"
override fun popularAnimeRequest(page: Int) = GET(baseUrl)
override fun popularAnimeFromElement(element: Element): SAnime {
return SAnime.create().apply {
val img = element.selectFirst("img")!!
val url = element.selectFirst("a")?.attr("href") ?: element.attr("href")
setUrlWithoutDomain(url)
title = img.attr("alt")
thumbnail_url = img.getImageUrl()
}
}
override fun popularAnimeNextPageSelector(): String? = null
override fun popularAnimeParse(response: Response): AnimesPage {
fetchGenresList()
return super.popularAnimeParse(response)
}
// ============================== Episodes ==============================
override fun episodeListSelector() = "ul.episodios > li"
protected open val episodeNumberRegex by lazy { "(\\d+)$".toRegex() }
protected open val seasonListSelector = "div#seasons > div"
protected open val episodeDateSelector = ".date"
protected open val episodeMovieText = when (lang) {
"pt-BR" -> "Filme"
else -> "Movie"
}
protected open val episodeSeasonPrefix = when (lang) {
"pt-BR" -> "Temporada"
else -> "Season"
}
override fun episodeListParse(response: Response): List<SEpisode> {
val doc = getRealAnimeDoc(response.asJsoup())
val seasonList = doc.select(seasonListSelector)
return if (seasonList.size < 1) {
SEpisode.create().apply {
setUrlWithoutDomain(doc.location())
episode_number = 1F
name = episodeMovieText
}.let(::listOf)
} else {
seasonList.flatMap(::getSeasonEpisodes).reversed()
}
}
protected open fun getSeasonEpisodes(season: Element): List<SEpisode> {
val seasonName = season.selectFirst("span.se-t")!!.text()
return season.select(episodeListSelector()).mapNotNull { element ->
runCatching {
episodeFromElement(element, seasonName)
}.onFailure { it.printStackTrace() }.getOrNull()
}
}
override fun episodeFromElement(element: Element): SEpisode = throw UnsupportedOperationException()
protected open fun episodeFromElement(element: Element, seasonName: String): SEpisode {
return SEpisode.create().apply {
val epNum = element.selectFirst("div.numerando")!!.text()
.trim()
.let(episodeNumberRegex::find)
?.groupValues
?.last() ?: "0"
val href = element.selectFirst("a[href]")!!
val episodeName = href.ownText()
episode_number = epNum.toFloatOrNull() ?: 0F
date_upload = element.selectFirst(episodeDateSelector)
?.text()
?.toDate() ?: 0L
name = "$episodeSeasonPrefix $seasonName x $epNum - $episodeName"
setUrlWithoutDomain(href.attr("href"))
}
}
// ============================ Video Links =============================
override fun videoListParse(response: Response): List<Video> = throw UnsupportedOperationException()
override fun videoListSelector(): String = throw UnsupportedOperationException()
override fun videoFromElement(element: Element): Video = throw UnsupportedOperationException()
override fun videoUrlParse(document: Document): String = throw UnsupportedOperationException()
// =============================== Search ===============================
private fun searchAnimeByPathParse(response: Response): AnimesPage {
val details = animeDetailsParse(response)
return AnimesPage(listOf(details), false)
}
override fun searchAnimeParse(response: Response): AnimesPage {
val document = response.asJsoup()
val url = response.request.url.toString()
val animes = when {
"/?s=" in url -> { // Search by name.
document.select(searchAnimeSelector()).map { element ->
searchAnimeFromElement(element)
}
}
else -> { // Search by some kind of filter, like genres or popularity.
document.select(latestUpdatesSelector()).map { element ->
popularAnimeFromElement(element)
}
}
}
val hasNextPage = document.selectFirst(searchAnimeNextPageSelector()) != null
return AnimesPage(animes, hasNextPage)
}
override suspend fun getSearchAnime(page: Int, query: String, filters: AnimeFilterList): AnimesPage {
return if (query.startsWith(PREFIX_SEARCH)) {
val path = query.removePrefix(PREFIX_SEARCH)
client.newCall(GET("$baseUrl/$path", headers))
.awaitSuccess()
.use(::searchAnimeByPathParse)
} else {
super.getSearchAnime(page, query, filters)
}
}
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request {
return when {
query.isBlank() -> {
filters
.firstOrNull { it.state != 0 }
?.let {
val filter = it as UriPartFilter
val filterUrl = buildString {
append("$baseUrl/${filter.toUriPart()}")
if (page > 1) append("/page/$page")
}
GET(filterUrl, headers)
} ?: popularAnimeRequest(page)
}
else -> GET("$baseUrl/page/$page/?s=$query", headers)
}
}
override fun searchAnimeFromElement(element: Element): SAnime {
return SAnime.create().apply {
setUrlWithoutDomain(element.attr("href"))
val img = element.selectFirst("img")!!
title = img.attr("alt")
thumbnail_url = img.getImageUrl()
}
}
override fun searchAnimeNextPageSelector() = latestUpdatesNextPageSelector()
override fun searchAnimeSelector() = "div.result-item div.image a"
// =========================== Anime Details ============================
/**
* Selector for the element on the anime details page that have some
* additional info about the anime.
*
* @see [Element.getInfo]
*/
protected open val additionalInfoSelector = "div#info"
protected open val additionalInfoItems = when (lang) {
"pt-BR" -> listOf("Título", "Ano", "Temporadas", "Episódios")
else -> listOf("Original", "First", "Last", "Seasons", "Episodes")
}
protected open fun Document.getDescription(): String {
return selectFirst("$additionalInfoSelector p")
?.let { it.text() + "\n" }
?: ""
}
override fun animeDetailsParse(document: Document): SAnime {
val doc = getRealAnimeDoc(document)
val sheader = doc.selectFirst("div.sheader")!!
return SAnime.create().apply {
setUrlWithoutDomain(doc.location())
sheader.selectFirst("div.poster > img")!!.let {
thumbnail_url = it.getImageUrl()
title = it.attr("alt").ifEmpty {
sheader.selectFirst("div.data > h1")!!.text()
}
}
genre = sheader.select("div.data > div.sgeneros > a")
.eachText()
.joinToString()
doc.selectFirst(additionalInfoSelector)?.let { info ->
description = buildString {
append(doc.getDescription())
additionalInfoItems.forEach {
info.getInfo(it)?.let(::append)
}
}
}
}
}
// =============================== Latest ===============================
override fun latestUpdatesNextPageSelector() = "div.resppages > a > span.fa-chevron-right"
override fun latestUpdatesSelector() = "div.content article > div.poster"
override fun latestUpdatesFromElement(element: Element) = popularAnimeFromElement(element)
protected open val latestUpdatesPath = when (lang) {
"pt-BR" -> "episodio"
else -> "episodes"
}
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/$latestUpdatesPath/page/$page", headers)
override fun latestUpdatesParse(response: Response): AnimesPage {
fetchGenresList()
return super.latestUpdatesParse(response)
}
// ============================== Settings ==============================
override fun setupPreferenceScreen(screen: PreferenceScreen) {
val videoQualityPref = ListPreference(screen.context).apply {
key = prefQualityKey
title = prefQualityTitle
entries = prefQualityEntries
entryValues = prefQualityValues
setDefaultValue(prefQualityDefault)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}
screen.addPreference(videoQualityPref)
}
// ============================== Filters ===============================
/**
* Disable it if you don't want the genres to be fetched.
*/
protected open val fetchGenres = true
/**
* Automatically fetched genres from the source to be used in the filters.
*/
protected open lateinit var genresArray: FilterItems
override fun getFilterList(): AnimeFilterList {
return if (this::genresArray.isInitialized) {
AnimeFilterList(
AnimeFilter.Header(genreFilterHeader),
FetchedGenresFilter(genresListMessage, genresArray),
)
} else if (fetchGenres) {
AnimeFilterList(AnimeFilter.Header(genresMissingWarning))
} else {
AnimeFilterList()
}
}
/**
* Fetch the genres from the source to be used in the filters.
*/
protected open fun fetchGenresList() {
if (!this::genresArray.isInitialized && fetchGenres) {
runCatching {
client.newCall(genresListRequest())
.execute()
.asJsoup()
.let(::genresListParse)
.let { items ->
if (items.isNotEmpty()) {
genresArray = items
}
}
}.onFailure { it.printStackTrace() }
}
}
/**
* The request to the page that have the genres list.
*/
protected open fun genresListRequest() = GET(baseUrl)
/**
* Get the genres from the document.
*/
protected open fun genresListParse(document: Document): FilterItems {
val items = document.select(genresListSelector()).map {
val name = it.text()
val value = it.attr("href").substringAfter("$baseUrl/")
Pair(name, value)
}.toTypedArray()
return if (items.isEmpty()) {
items
} else {
arrayOf(Pair(selectFilterText, "")) + items
}
}
protected open val selectFilterText = when (lang) {
"pt-BR" -> "<Selecione>"
else -> "<Select>"
}
protected open val genreFilterHeader = when (lang) {
"pt-BR" -> "NOTA: Filtros serão ignorados se usar a pesquisa por nome!"
else -> "NOTE: Filters are going to be ignored if using search text!"
}
protected open val genresMissingWarning: String = when (lang) {
"pt-BR" -> "Aperte 'Redefinir' para tentar mostrar os gêneros"
else -> "Press 'Reset' to attempt to show the genres"
}
protected open val genresListMessage = when (lang) {
"pt-BR" -> "Gênero"
else -> "Genre"
}
protected open fun genresListSelector() = "li:contains($genresListMessage) ul.sub-menu li > a"
class FetchedGenresFilter(title: String, items: FilterItems) : UriPartFilter(title, items)
open class UriPartFilter(
displayName: String,
private val vals: FilterItems,
) : AnimeFilter.Select<String>(
displayName,
vals.map { it.first }.toTypedArray(),
) {
fun toUriPart() = vals[state].second
}
@Suppress("UNUSED")
private inline fun <reified R> AnimeFilterList.asUriPart(): String {
return this.first { it is R }.let { it as UriPartFilter }.toUriPart()
}
// ============================= Utilities ==============================
/**
* The selector to the item in the menu (in episodes page) with the
* anime page url.
*/
protected open val animeMenuSelector = "div.pag_episodes div.item a[href] i.fa-bars"
/**
* If the document comes from a episode page, this function will get the
* real/expected document from the anime details page. else, it will return the
* original document.
*
* @return A document from a anime details page.
*/
protected open fun getRealAnimeDoc(document: Document): Document {
val menu = document.selectFirst(animeMenuSelector)
return if (menu != null) {
val originalUrl = menu.parent()!!.attr("href")
val req = client.newCall(GET(originalUrl, headers)).execute()
req.asJsoup()
} else {
document
}
}
/**
* Tries to get additional info from an element at a anime details page,
* like how many seasons it have, the year it was aired, etc.
* Useful for anime description.
*/
protected open fun Element.getInfo(substring: String): String? {
val target = selectFirst("div.custom_fields:contains($substring)")
?: return null
val key = target.selectFirst("b")!!.text()
val value = target.selectFirst("span")!!.text()
return "\n$key: $value"
}
/**
* Tries to get the image url via various possible attributes.
* Taken from Tachiyomi's Madara multisrc.
*/
protected open fun Element.getImageUrl(): String? {
return when {
hasAttr("data-src") -> attr("abs:data-src")
hasAttr("data-lazy-src") -> attr("abs:data-lazy-src")
hasAttr("srcset") -> attr("abs:srcset").substringBefore(" ")
else -> attr("abs:src")
}
}
override fun List<Video>.sort(): List<Video> {
val quality = preferences.getString(videoSortPrefKey, videoSortPrefDefault)!!
return sortedWith(
compareBy { it.quality.lowercase().contains(quality.lowercase()) },
).reversed()
}
protected open val dateFormatter by lazy {
SimpleDateFormat("MMMM. dd, yyyy", Locale.ENGLISH)
}
protected open fun String.toDate(): Long {
return runCatching { dateFormatter.parse(trim())?.time }
.getOrNull() ?: 0L
}
}
typealias FilterItems = Array<Pair<String, String>>

View file

@ -0,0 +1,39 @@
package eu.kanade.tachiyomi.multisrc.dooplay
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
class DooPlayUrlActivity : Activity() {
private val tag = "DooPlayUrlActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 1) {
val path = pathSegments[0]
val slug = pathSegments[1]
val searchQuery = "$path/$slug"
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.ANIMESEARCH"
putExtra("query", "${DooPlay.PREFIX_SEARCH}$searchQuery")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e(tag, e.toString())
}
} else {
Log.e(tag, "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}

View file

@ -0,0 +1,11 @@
plugins {
id("lib-multisrc")
}
baseVersionCode = 20
dependencies {
api(project(":lib:dood-extractor"))
api(project(":lib:cryptoaes"))
api(project(":lib:playlist-utils"))
}

View file

@ -0,0 +1,374 @@
package eu.kanade.tachiyomi.multisrc.dopeflix
import android.app.Application
import android.content.SharedPreferences
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Track
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource
import eu.kanade.tachiyomi.lib.doodextractor.DoodExtractor
import eu.kanade.tachiyomi.lib.playlistutils.PlaylistUtils
import eu.kanade.tachiyomi.multisrc.dopeflix.dto.VideoDto
import eu.kanade.tachiyomi.multisrc.dopeflix.extractors.DopeFlixExtractor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.util.asJsoup
import eu.kanade.tachiyomi.util.parallelCatchingFlatMapBlocking
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
abstract class DopeFlix(
override val name: String,
override val lang: String,
private val domainArray: Array<String>,
private val defaultDomain: String,
) : ConfigurableAnimeSource, ParsedAnimeHttpSource() {
override val baseUrl by lazy {
"https://" + preferences.getString(PREF_DOMAIN_KEY, defaultDomain)!!
}
override val supportsLatest = true
private val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
override fun headersBuilder() = super.headersBuilder().add("Referer", "$baseUrl/")
// ============================== Popular ===============================
override fun popularAnimeSelector(): String = "div.film_list-wrap div.flw-item div.film-poster"
override fun popularAnimeRequest(page: Int): Request {
val type = preferences.getString(PREF_POPULAR_KEY, PREF_POPULAR_DEFAULT)!!
return GET("$baseUrl/$type?page=$page")
}
override fun popularAnimeFromElement(element: Element) = SAnime.create().apply {
val ahref = element.selectFirst("a")!!
setUrlWithoutDomain(ahref.attr("href"))
title = ahref.attr("title")
thumbnail_url = element.selectFirst("img")!!.attr("data-src")
}
override fun popularAnimeNextPageSelector() = "ul.pagination li.page-item a[title=next]"
// =============================== Latest ===============================
override fun latestUpdatesNextPageSelector(): String? = null
override fun latestUpdatesFromElement(element: Element) = popularAnimeFromElement(element)
override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/home/")
override fun latestUpdatesSelector(): String {
val sectionLabel = preferences.getString(PREF_LATEST_KEY, PREF_LATEST_DEFAULT)!!
return "section.block_area:has(h2.cat-heading:contains($sectionLabel)) div.film-poster"
}
// =============================== Search ===============================
override fun searchAnimeFromElement(element: Element) = popularAnimeFromElement(element)
override fun searchAnimeNextPageSelector() = popularAnimeNextPageSelector()
override fun searchAnimeSelector() = popularAnimeSelector()
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request {
val params = DopeFlixFilters.getSearchParameters(filters)
val url = if (query.isNotBlank()) {
val fixedQuery = query.replace(" ", "-")
"$baseUrl/search/$fixedQuery?page=$page"
} else {
"$baseUrl/filter".toHttpUrl().newBuilder()
.addQueryParameter("page", page.toString())
.addQueryParameter("type", params.type)
.addQueryParameter("quality", params.quality)
.addQueryParameter("release_year", params.releaseYear)
.addIfNotBlank("genre", params.genres)
.addIfNotBlank("country", params.countries)
.build()
.toString()
}
return GET(url, headers)
}
override fun getFilterList() = DopeFlixFilters.FILTER_LIST
// =========================== Anime Details ============================
override fun animeDetailsParse(document: Document) = SAnime.create().apply {
thumbnail_url = document.selectFirst("img.film-poster-img")!!.attr("src")
title = document.selectFirst("img.film-poster-img")!!.attr("title")
genre = document.select("div.row-line:contains(Genre) a").eachText().joinToString()
description = document.selectFirst("div.detail_page-watch div.description")!!
.text().replace("Overview:", "")
author = document.select("div.row-line:contains(Production) a").eachText().joinToString()
status = parseStatus(document.selectFirst("li.status span.value")?.text())
}
private fun parseStatus(statusString: String?): Int {
return when (statusString?.trim()) {
"Ongoing" -> SAnime.ONGOING
else -> SAnime.COMPLETED
}
}
// ============================== Episodes ==============================
override fun episodeListSelector() = throw UnsupportedOperationException()
override fun episodeListParse(response: Response): List<SEpisode> {
val document = response.asJsoup()
val infoElement = document.selectFirst("div.detail_page-watch")!!
val id = infoElement.attr("data-id")
val dataType = infoElement.attr("data-type") // Tv = 2 or movie = 1
return if (dataType == "2") {
val seasonUrl = "$baseUrl/ajax/v2/tv/seasons/$id"
val seasonsHtml = client.newCall(
GET(
seasonUrl,
headers = Headers.headersOf("Referer", document.location()),
),
).execute().asJsoup()
seasonsHtml
.select("a.dropdown-item.ss-item")
.flatMap(::parseEpisodesFromSeries)
.reversed()
} else {
val movieUrl = "$baseUrl/ajax/movie/episodes/$id"
SEpisode.create().apply {
name = document.selectFirst("h2.heading-name")!!.text()
episode_number = 1F
setUrlWithoutDomain(movieUrl)
}.let(::listOf)
}
}
override fun episodeFromElement(element: Element): SEpisode = throw UnsupportedOperationException()
private fun parseEpisodesFromSeries(element: Element): List<SEpisode> {
val seasonId = element.attr("data-id")
val seasonName = element.text()
val episodesUrl = "$baseUrl/ajax/v2/season/episodes/$seasonId"
val episodesHtml = client.newCall(GET(episodesUrl)).execute()
.asJsoup()
val episodeElements = episodesHtml.select("div.eps-item")
return episodeElements.map { episodeFromElement(it, seasonName) }
}
private fun episodeFromElement(element: Element, seasonName: String) = SEpisode.create().apply {
val episodeId = element.attr("data-id")
val epNum = element.selectFirst("div.episode-number")!!.text()
val epName = element.selectFirst("h3.film-name a")!!.text()
name = "$seasonName $epNum $epName"
episode_number = "${seasonName.getNumber()}.${epNum.getNumber().padStart(3, '0')}".toFloatOrNull() ?: 1F
setUrlWithoutDomain("$baseUrl/ajax/v2/episode/servers/$episodeId")
}
private fun String.getNumber() = filter(Char::isDigit)
// ============================ Video Links =============================
private val extractor by lazy { DopeFlixExtractor(client) }
private val playlistUtils by lazy { PlaylistUtils(client, headers) }
override fun videoListParse(response: Response): List<Video> {
val doc = response.asJsoup()
val episodeReferer = Headers.headersOf("Referer", response.request.header("referer")!!)
return doc.select("ul.fss-list a.btn-play")
.parallelCatchingFlatMapBlocking { server ->
val name = server.selectFirst("span")!!.text()
val id = server.attr("data-id")
val url = "$baseUrl/ajax/sources/$id"
val reqBody = client.newCall(GET(url, episodeReferer)).execute()
.body.string()
val sourceUrl = reqBody.substringAfter("\"link\":\"")
.substringBefore("\"")
when {
"DoodStream" in name ->
DoodExtractor(client).videoFromUrl(sourceUrl)
?.let(::listOf)
"Vidcloud" in name || "UpCloud" in name -> {
val video = extractor.getVideoDto(sourceUrl)
getVideosFromServer(video, name)
}
else -> null
}.orEmpty()
}
}
private fun getVideosFromServer(video: VideoDto, name: String): List<Video> {
val masterUrl = video.sources.first().file
val subs = video.tracks
?.filter { it.kind == "captions" }
?.mapNotNull { Track(it.file, it.label) }
?.let(::subLangOrder)
?: emptyList<Track>()
if (masterUrl.contains("playlist.m3u8")) {
return playlistUtils.extractFromHls(
masterUrl,
videoNameGen = { "$name - $it" },
subtitleList = subs,
)
}
return listOf(
Video(masterUrl, "$name - Default", masterUrl, subtitleTracks = subs),
)
}
override fun List<Video>.sort(): List<Video> {
val quality = preferences.getString(PREF_QUALITY_KEY, PREF_QUALITY_DEFAULT)!!
return sortedWith(
compareBy(
{ it.quality.contains(quality) }, // preferred quality first
// then group by quality
{ Regex("""(\d+)p""").find(it.quality)?.groupValues?.get(1)?.toIntOrNull() ?: 0 },
),
).reversed()
}
private fun subLangOrder(tracks: List<Track>): List<Track> {
val language = preferences.getString(PREF_SUB_KEY, PREF_SUB_DEFAULT)!!
return tracks.sortedWith(
compareBy { it.lang.contains(language) },
).reversed()
}
override fun videoListSelector() = throw UnsupportedOperationException()
override fun videoFromElement(element: Element) = throw UnsupportedOperationException()
override fun videoUrlParse(document: Document) = throw UnsupportedOperationException()
// ============================== Settings ==============================
override fun setupPreferenceScreen(screen: PreferenceScreen) {
ListPreference(screen.context).apply {
key = PREF_DOMAIN_KEY
title = PREF_DOMAIN_TITLE
entries = domainArray
entryValues = domainArray
setDefaultValue(defaultDomain)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = PREF_QUALITY_KEY
title = PREF_QUALITY_TITLE
entries = PREF_QUALITY_LIST
entryValues = PREF_QUALITY_LIST
setDefaultValue(PREF_QUALITY_DEFAULT)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = PREF_SUB_KEY
title = PREF_SUB_TITLE
entries = PREF_SUB_LANGUAGES
entryValues = PREF_SUB_LANGUAGES
setDefaultValue(PREF_SUB_DEFAULT)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = PREF_LATEST_KEY
title = PREF_LATEST_TITLE
entries = PREF_LATEST_PAGES
entryValues = PREF_LATEST_PAGES
setDefaultValue(PREF_LATEST_DEFAULT)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = PREF_POPULAR_KEY
title = PREF_POPULAR_TITLE
entries = PREF_POPULAR_ENTRIES
entryValues = PREF_POPULAR_VALUES
setDefaultValue(PREF_POPULAR_DEFAULT)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
}
// ============================= Utilities ==============================
private fun HttpUrl.Builder.addIfNotBlank(query: String, value: String): HttpUrl.Builder {
if (value.isNotBlank()) {
addQueryParameter(query, value)
}
return this
}
companion object {
private const val PREF_DOMAIN_KEY = "preferred_domain_new"
private const val PREF_DOMAIN_TITLE = "Preferred domain (requires app restart)"
private const val PREF_QUALITY_KEY = "preferred_quality"
private const val PREF_QUALITY_TITLE = "Preferred quality"
private const val PREF_QUALITY_DEFAULT = "1080p"
private val PREF_QUALITY_LIST = arrayOf("1080p", "720p", "480p", "360p")
private const val PREF_SUB_KEY = "preferred_subLang"
private const val PREF_SUB_TITLE = "Preferred sub language"
private const val PREF_SUB_DEFAULT = "English"
private val PREF_SUB_LANGUAGES = arrayOf(
"Arabic", "English", "French", "German", "Hungarian",
"Italian", "Japanese", "Portuguese", "Romanian", "Russian",
"Spanish",
)
private const val PREF_LATEST_KEY = "preferred_latest_page"
private const val PREF_LATEST_TITLE = "Preferred latest page"
private const val PREF_LATEST_DEFAULT = "Movies"
private val PREF_LATEST_PAGES = arrayOf("Movies", "TV Shows")
private const val PREF_POPULAR_KEY = "preferred_popular_page_new"
private const val PREF_POPULAR_TITLE = "Preferred popular page"
private const val PREF_POPULAR_DEFAULT = "movie"
private val PREF_POPULAR_ENTRIES = PREF_LATEST_PAGES
private val PREF_POPULAR_VALUES = arrayOf("movie", "tv-show")
}
}

View file

@ -0,0 +1,178 @@
package eu.kanade.tachiyomi.multisrc.dopeflix
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
object DopeFlixFilters {
open class QueryPartFilter(
displayName: String,
val vals: Array<Pair<String, String>>,
) : AnimeFilter.Select<String>(
displayName,
vals.map { it.first }.toTypedArray(),
) {
fun toQueryPart() = vals[state].second
}
open class CheckBoxFilterList(name: String, values: List<CheckBox>) : AnimeFilter.Group<AnimeFilter.CheckBox>(name, values)
private class CheckBoxVal(name: String, state: Boolean = false) : AnimeFilter.CheckBox(name, state)
private inline fun <reified R> AnimeFilterList.asQueryPart(): String {
return (getFirst<R>() as QueryPartFilter).toQueryPart()
}
private inline fun <reified R> AnimeFilterList.getFirst(): R {
return first { it is R } as R
}
private inline fun <reified R> AnimeFilterList.parseCheckbox(
options: Array<Pair<String, String>>,
): String {
return (getFirst<R>() as CheckBoxFilterList).state
.filter { it.state }
.map { checkbox -> options.find { it.first == checkbox.name }!!.second }
.joinToString("-") { it.ifBlank { "all" } }
}
class TypeFilter : QueryPartFilter("Type", DopeFlixFiltersData.TYPES)
class QualityFilter : QueryPartFilter("Quality", DopeFlixFiltersData.QUALITIES)
class ReleaseYearFilter : QueryPartFilter("Released at", DopeFlixFiltersData.YEARS)
class GenresFilter : CheckBoxFilterList(
"Genres",
DopeFlixFiltersData.GENRES.map { CheckBoxVal(it.first, false) },
)
class CountriesFilter : CheckBoxFilterList(
"Countries",
DopeFlixFiltersData.COUNTRIES.map { CheckBoxVal(it.first, false) },
)
val FILTER_LIST get() = AnimeFilterList(
TypeFilter(),
QualityFilter(),
ReleaseYearFilter(),
AnimeFilter.Separator(),
GenresFilter(),
CountriesFilter(),
)
data class FilterSearchParams(
val type: String = "",
val quality: String = "",
val releaseYear: String = "",
val genres: String = "",
val countries: String = "",
)
internal fun getSearchParameters(filters: AnimeFilterList): FilterSearchParams {
if (filters.isEmpty()) return FilterSearchParams()
return FilterSearchParams(
filters.asQueryPart<TypeFilter>(),
filters.asQueryPart<QualityFilter>(),
filters.asQueryPart<ReleaseYearFilter>(),
filters.parseCheckbox<GenresFilter>(DopeFlixFiltersData.GENRES),
filters.parseCheckbox<CountriesFilter>(DopeFlixFiltersData.COUNTRIES),
)
}
private object DopeFlixFiltersData {
val ALL = Pair("All", "all")
val TYPES = arrayOf(
ALL,
Pair("Movies", "movies"),
Pair("TV Shows", "tv"),
)
val QUALITIES = arrayOf(
ALL,
Pair("HD", "HD"),
Pair("SD", "SD"),
Pair("CAM", "CAM"),
)
val YEARS = arrayOf(
ALL,
Pair("2024", "2024"),
Pair("2023", "2023"),
Pair("2022", "2022"),
Pair("2021", "2021"),
Pair("2020", "2020"),
Pair("2019", "2019"),
Pair("2018", "2018"),
Pair("Older", "older-2018"),
)
val GENRES = arrayOf(
Pair("Action", "10"),
Pair("Action & Adventure", "24"),
Pair("Adventure", "18"),
Pair("Animation", "3"),
Pair("Biography", "37"),
Pair("Comedy", "7"),
Pair("Crime", "2"),
Pair("Documentary", "11"),
Pair("Drama", "4"),
Pair("Family", "9"),
Pair("Fantasy", "13"),
Pair("History", "19"),
Pair("Horror", "14"),
Pair("Kids", "27"),
Pair("Music", "15"),
Pair("Mystery", "1"),
Pair("News", "34"),
Pair("Reality", "22"),
Pair("Romance", "12"),
Pair("Sci-Fi & Fantasy", "31"),
Pair("Science Fiction", "5"),
Pair("Soap", "35"),
Pair("Talk", "29"),
Pair("Thriller", "16"),
Pair("TV Movie", "8"),
Pair("War", "17"),
Pair("War & Politics", "28"),
Pair("Western", "6"),
)
val COUNTRIES = arrayOf(
Pair("Argentina", "11"),
Pair("Australia", "151"),
Pair("Austria", "4"),
Pair("Belgium", "44"),
Pair("Brazil", "190"),
Pair("Canada", "147"),
Pair("China", "101"),
Pair("Czech Republic", "231"),
Pair("Denmark", "222"),
Pair("Finland", "158"),
Pair("France", "3"),
Pair("Germany", "96"),
Pair("Hong Kong", "93"),
Pair("Hungary", "72"),
Pair("India", "105"),
Pair("Ireland", "196"),
Pair("Israel", "24"),
Pair("Italy", "205"),
Pair("Japan", "173"),
Pair("Luxembourg", "91"),
Pair("Mexico", "40"),
Pair("Netherlands", "172"),
Pair("New Zealand", "122"),
Pair("Norway", "219"),
Pair("Poland", "23"),
Pair("Romania", "170"),
Pair("Russia", "109"),
Pair("South Africa", "200"),
Pair("South Korea", "135"),
Pair("Spain", "62"),
Pair("Sweden", "114"),
Pair("Switzerland", "41"),
Pair("Taiwan", "119"),
Pair("Thailand", "57"),
Pair("United Kingdom", "180"),
Pair("United States of America", "129"),
)
}
}

View file

@ -0,0 +1,23 @@
package eu.kanade.tachiyomi.multisrc.dopeflix.dto
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
@Serializable
data class VideoDto(
val sources: List<VideoLink>,
val tracks: List<TrackDto>? = null,
)
@Serializable
data class SourceResponseDto(
val sources: JsonElement,
val encrypted: Boolean = true,
val tracks: List<TrackDto>? = null,
)
@Serializable
data class VideoLink(val file: String = "")
@Serializable
data class TrackDto(val file: String, val kind: String, val label: String = "")

View file

@ -0,0 +1,112 @@
package eu.kanade.tachiyomi.multisrc.dopeflix.extractors
import eu.kanade.tachiyomi.lib.cryptoaes.CryptoAES
import eu.kanade.tachiyomi.multisrc.dopeflix.dto.SourceResponseDto
import eu.kanade.tachiyomi.multisrc.dopeflix.dto.VideoDto
import eu.kanade.tachiyomi.multisrc.dopeflix.dto.VideoLink
import eu.kanade.tachiyomi.network.GET
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonPrimitive
import okhttp3.Headers
import okhttp3.OkHttpClient
import uy.kohesive.injekt.injectLazy
class DopeFlixExtractor(private val client: OkHttpClient) {
private val json: Json by injectLazy()
companion object {
private const val SOURCES_PATH = "/ajax/embed-4/getSources?id="
private const val SCRIPT_URL = "https://rabbitstream.net/js/player/prod/e4-player.min.js"
private val MUTEX = Mutex()
private var realIndexPairs: List<List<Int>> = emptyList()
private fun <R> runLocked(block: () -> R) = runBlocking(Dispatchers.IO) {
MUTEX.withLock { block() }
}
}
private fun generateIndexPairs(): List<List<Int>> {
val script = client.newCall(GET(SCRIPT_URL)).execute().body.string()
return script.substringAfter("const ")
.substringBefore("()")
.substringBeforeLast(",")
.split(",")
.map {
val value = it.substringAfter("=")
when {
value.contains("0x") -> value.substringAfter("0x").toInt(16)
else -> value.toInt()
}
}
.drop(1)
.chunked(2)
.map(List<Int>::reversed) // just to look more like the original script
}
private fun cipherTextCleaner(data: String): Pair<String, String> {
val (password, ciphertext, _) = indexPairs.fold(Triple("", data, 0)) { previous, item ->
val start = item.first() + previous.third
val end = start + item.last()
val passSubstr = data.substring(start, end)
val passPart = previous.first + passSubstr
val cipherPart = previous.second.replace(passSubstr, "")
Triple(passPart, cipherPart, previous.third + item.last())
}
return Pair(ciphertext, password)
}
private val mutex = Mutex()
private var indexPairs: List<List<Int>>
get() {
return runLocked {
if (realIndexPairs.isEmpty()) {
realIndexPairs = generateIndexPairs()
}
realIndexPairs
}
}
set(value) {
runLocked {
if (realIndexPairs.isNotEmpty()) {
realIndexPairs = value
}
}
}
private fun tryDecrypting(ciphered: String, attempts: Int = 0): String {
if (attempts > 2) throw Exception("PLEASE NUKE DOPEBOX AND SFLIX")
val (ciphertext, password) = cipherTextCleaner(ciphered)
return CryptoAES.decrypt(ciphertext, password).ifEmpty {
indexPairs = emptyList() // force re-creation
tryDecrypting(ciphered, attempts + 1)
}
}
fun getVideoDto(url: String): VideoDto {
val id = url.substringAfter("/embed-4/", "")
.substringBefore("?", "").ifEmpty { throw Exception("I HATE THE ANTICHRIST") }
val serverUrl = url.substringBefore("/embed")
val srcRes = client.newCall(
GET(
serverUrl + SOURCES_PATH + id,
headers = Headers.headersOf("x-requested-with", "XMLHttpRequest"),
),
)
.execute()
.body.string()
val data = json.decodeFromString<SourceResponseDto>(srcRes)
if (!data.encrypted) return json.decodeFromString<VideoDto>(srcRes)
val ciphered = data.sources.jsonPrimitive.content.toString()
val decrypted = json.decodeFromString<List<VideoLink>>(tryDecrypting(ciphered))
return VideoDto(decrypted, data.tracks)
}
}

View file

@ -0,0 +1,10 @@
plugins {
id("lib-multisrc")
}
baseVersionCode = 3
dependencies {
api(project(":lib:megacloud-extractor"))
api(project(":lib:streamtape-extractor"))
}

View file

@ -0,0 +1,444 @@
package eu.kanade.tachiyomi.multisrc.zorotheme
import android.app.Application
import android.content.SharedPreferences
import android.widget.Toast
import androidx.preference.ListPreference
import androidx.preference.MultiSelectListPreference
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreferenceCompat
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource
import eu.kanade.tachiyomi.multisrc.zorotheme.dto.HtmlResponse
import eu.kanade.tachiyomi.multisrc.zorotheme.dto.SourcesResponse
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.util.parallelCatchingFlatMap
import eu.kanade.tachiyomi.util.parallelMapNotNull
import eu.kanade.tachiyomi.util.parseAs
import kotlinx.serialization.json.Json
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
abstract class ZoroTheme(
override val lang: String,
override val name: String,
override val baseUrl: String,
private val hosterNames: List<String>,
) : ConfigurableAnimeSource, ParsedAnimeHttpSource() {
override val supportsLatest = true
private val json: Json by injectLazy()
val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
.clearOldHosts()
}
private val docHeaders = headers.newBuilder().apply {
add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
add("Host", baseUrl.toHttpUrl().host)
add("Referer", "$baseUrl/")
}.build()
protected open val ajaxRoute = ""
private val useEnglish by lazy { preferences.getTitleLang == "English" }
private val markFiller by lazy { preferences.markFiller }
// ============================== Popular ===============================
override fun popularAnimeRequest(page: Int): Request = GET("$baseUrl/most-popular?page=$page", docHeaders)
override fun popularAnimeSelector(): String = "div.flw-item"
override fun popularAnimeFromElement(element: Element) = SAnime.create().apply {
element.selectFirst("div.film-detail a")!!.let {
setUrlWithoutDomain(it.attr("href"))
title = if (useEnglish && it.hasAttr("title")) {
it.attr("title")
} else {
it.attr("data-jname")
}
}
thumbnail_url = element.selectFirst("div.film-poster > img")!!.attr("data-src")
}
override fun popularAnimeNextPageSelector() = "li.page-item a[title=Next]"
// =============================== Latest ===============================
override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/top-airing?page=$page", docHeaders)
override fun latestUpdatesSelector(): String = popularAnimeSelector()
override fun latestUpdatesFromElement(element: Element) = popularAnimeFromElement(element)
override fun latestUpdatesNextPageSelector(): String = popularAnimeNextPageSelector()
// =============================== Search ===============================
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request {
val params = ZoroThemeFilters.getSearchParameters(filters)
val endpoint = if (query.isEmpty()) "filter" else "search"
val url = "$baseUrl/$endpoint".toHttpUrl().newBuilder().apply {
addQueryParameter("page", page.toString())
addIfNotBlank("keyword", query)
addIfNotBlank("type", params.type)
addIfNotBlank("status", params.status)
addIfNotBlank("rated", params.rated)
addIfNotBlank("score", params.score)
addIfNotBlank("season", params.season)
addIfNotBlank("language", params.language)
addIfNotBlank("sort", params.sort)
addIfNotBlank("sy", params.start_year)
addIfNotBlank("sm", params.start_month)
addIfNotBlank("sd", params.start_day)
addIfNotBlank("ey", params.end_year)
addIfNotBlank("em", params.end_month)
addIfNotBlank("ed", params.end_day)
addIfNotBlank("genres", params.genres)
}.build()
return GET(url, docHeaders)
}
override fun searchAnimeSelector() = popularAnimeSelector()
override fun searchAnimeFromElement(element: Element) = popularAnimeFromElement(element)
override fun searchAnimeNextPageSelector() = popularAnimeNextPageSelector()
// ============================== Filters ===============================
override fun getFilterList() = ZoroThemeFilters.FILTER_LIST
// =========================== Anime Details ============================
override fun animeDetailsParse(document: Document) = SAnime.create().apply {
thumbnail_url = document.selectFirst("div.anisc-poster img")!!.attr("src")
document.selectFirst("div.anisc-info")!!.let { info ->
author = info.getInfo("Studios:")
status = parseStatus(info.getInfo("Status:"))
genre = info.getInfo("Genres:", isList = true)
description = buildString {
info.getInfo("Overview:")?.also { append(it + "\n") }
info.getInfo("Aired:", full = true)?.also(::append)
info.getInfo("Premiered:", full = true)?.also(::append)
info.getInfo("Synonyms:", full = true)?.also(::append)
info.getInfo("Japanese:", full = true)?.also(::append)
}
}
}
private fun Element.getInfo(
tag: String,
isList: Boolean = false,
full: Boolean = false,
): String? {
if (isList) {
return select("div.item-list:contains($tag) > a").eachText().joinToString()
}
val value = selectFirst("div.item-title:contains($tag)")
?.selectFirst("*.name, *.text")
?.text()
return if (full && value != null) "\n$tag $value" else value
}
private fun parseStatus(statusString: String?): Int {
return when (statusString) {
"Currently Airing" -> SAnime.ONGOING
"Finished Airing" -> SAnime.COMPLETED
else -> SAnime.UNKNOWN
}
}
// ============================== Episodes ==============================
override fun episodeListRequest(anime: SAnime): Request {
val id = anime.url.substringAfterLast("-")
return GET("$baseUrl/ajax$ajaxRoute/episode/list/$id", apiHeaders(baseUrl + anime.url))
}
override fun episodeListSelector() = "a.ep-item"
override fun episodeListParse(response: Response): List<SEpisode> {
val document = response.parseAs<HtmlResponse>().getHtml()
return document.select(episodeListSelector())
.map(::episodeFromElement)
.reversed()
}
override fun episodeFromElement(element: Element) = SEpisode.create().apply {
episode_number = element.attr("data-number").toFloatOrNull() ?: 1F
name = "Ep. ${element.attr("data-number")}: ${element.attr("title")}"
setUrlWithoutDomain(element.attr("href"))
if (element.hasClass("ssl-item-filler") && markFiller) {
scanlator = "Filler Episode"
}
}
// ============================ Video Links =============================
override fun videoListRequest(episode: SEpisode): Request {
val id = episode.url.substringAfterLast("?ep=")
return GET("$baseUrl/ajax$ajaxRoute/episode/servers?episodeId=$id", apiHeaders(baseUrl + episode.url))
}
data class VideoData(
val type: String,
val link: String,
val name: String,
)
override suspend fun getVideoList(episode: SEpisode): List<Video> {
val response = client.newCall(videoListRequest(episode)).await()
val episodeReferer = response.request.header("referer")!!
val typeSelection = preferences.typeToggle
val hosterSelection = preferences.hostToggle
val serversDoc = response.parseAs<HtmlResponse>().getHtml()
val embedLinks = listOf("servers-sub", "servers-dub", "servers-mixed").map { type ->
if (type !in typeSelection) return@map emptyList()
serversDoc.select("div.$type div.item").parallelMapNotNull {
val id = it.attr("data-id")
val type = it.attr("data-type")
val name = it.text()
if (hosterSelection.contains(name, true).not()) return@parallelMapNotNull null
val link = client.newCall(
GET("$baseUrl/ajax$ajaxRoute/episode/sources?id=$id", apiHeaders(episodeReferer)),
).await().parseAs<SourcesResponse>().link ?: ""
VideoData(type, link, name)
}
}.flatten()
return embedLinks.parallelCatchingFlatMap(::extractVideo)
}
abstract fun extractVideo(server: VideoData): List<Video>
override fun videoListSelector() = throw UnsupportedOperationException()
override fun videoFromElement(element: Element) = throw UnsupportedOperationException()
override fun videoUrlParse(document: Document) = throw UnsupportedOperationException()
// ============================= Utilities ==============================
private fun SharedPreferences.clearOldHosts(): SharedPreferences {
if (hostToggle.all { hosterNames.contains(it) }) {
return this
}
edit()
.remove(PREF_HOSTER_KEY)
.putStringSet(PREF_HOSTER_KEY, hosterNames.toSet())
.remove(PREF_SERVER_KEY)
.putString(PREF_SERVER_KEY, hosterNames.first())
.apply()
return this
}
private fun Set<String>.contains(s: String, ignoreCase: Boolean): Boolean {
return any { it.equals(s, ignoreCase) }
}
private fun apiHeaders(referer: String): Headers = headers.newBuilder().apply {
add("Accept", "*/*")
add("Host", baseUrl.toHttpUrl().host)
add("Referer", referer)
add("X-Requested-With", "XMLHttpRequest")
}.build()
private fun HttpUrl.Builder.addIfNotBlank(query: String, value: String): HttpUrl.Builder {
if (value.isNotBlank()) {
addQueryParameter(query, value)
}
return this
}
override fun List<Video>.sort(): List<Video> {
val quality = preferences.prefQuality
val lang = preferences.prefLang
val server = preferences.prefServer
return this.sortedWith(
compareByDescending<Video> { it.quality.contains(quality) }
.thenByDescending { it.quality.contains(server, true) }
.thenByDescending { it.quality.contains(lang, true) },
)
}
private val SharedPreferences.getTitleLang
get() = getString(PREF_TITLE_LANG_KEY, PREF_TITLE_LANG_DEFAULT)!!
private val SharedPreferences.markFiller
get() = getBoolean(MARK_FILLERS_KEY, MARK_FILLERS_DEFAULT)
private val SharedPreferences.prefQuality
get() = getString(PREF_QUALITY_KEY, PREF_QUALITY_DEFAULT)!!
private val SharedPreferences.prefServer
get() = getString(PREF_SERVER_KEY, hosterNames.first())!!
private val SharedPreferences.prefLang
get() = getString(PREF_LANG_KEY, PREF_LANG_DEFAULT)!!
private val SharedPreferences.hostToggle
get() = getStringSet(PREF_HOSTER_KEY, hosterNames.toSet())!!
private val SharedPreferences.typeToggle
get() = getStringSet(PREF_TYPE_TOGGLE_KEY, PREF_TYPES_TOGGLE_DEFAULT)!!
companion object {
private const val PREF_TITLE_LANG_KEY = "preferred_title_lang"
private const val PREF_TITLE_LANG_DEFAULT = "Romaji"
private val PREF_TITLE_LANG_LIST = arrayOf("Romaji", "English")
private const val MARK_FILLERS_KEY = "mark_fillers"
private const val MARK_FILLERS_DEFAULT = true
private const val PREF_QUALITY_KEY = "preferred_quality"
private const val PREF_QUALITY_DEFAULT = "1080"
private const val PREF_LANG_KEY = "preferred_language"
private const val PREF_LANG_DEFAULT = "Sub"
private const val PREF_SERVER_KEY = "preferred_server"
private const val PREF_HOSTER_KEY = "hoster_selection"
private const val PREF_TYPE_TOGGLE_KEY = "type_selection"
private val TYPES_ENTRIES = arrayOf("Sub", "Dub", "Mixed")
private val TYPES_ENTRY_VALUES = arrayOf("servers-sub", "servers-dub", "servers-mixed")
private val PREF_TYPES_TOGGLE_DEFAULT = TYPES_ENTRY_VALUES.toSet()
}
// ============================== Settings ==============================
override fun setupPreferenceScreen(screen: PreferenceScreen) {
ListPreference(screen.context).apply {
key = PREF_TITLE_LANG_KEY
title = "Preferred title language"
entries = PREF_TITLE_LANG_LIST
entryValues = PREF_TITLE_LANG_LIST
setDefaultValue(PREF_TITLE_LANG_DEFAULT)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
Toast.makeText(screen.context, "Restart Aniyomi to apply new setting.", Toast.LENGTH_LONG).show()
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
SwitchPreferenceCompat(screen.context).apply {
key = MARK_FILLERS_KEY
title = "Mark filler episodes"
setDefaultValue(MARK_FILLERS_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
Toast.makeText(screen.context, "Restart Aniyomi to apply new setting.", Toast.LENGTH_LONG).show()
preferences.edit().putBoolean(key, newValue as Boolean).commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = PREF_QUALITY_KEY
title = "Preferred quality"
entries = arrayOf("1080p", "720p", "480p", "360p")
entryValues = arrayOf("1080", "720", "480", "360")
setDefaultValue(PREF_QUALITY_DEFAULT)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = PREF_SERVER_KEY
title = "Preferred Server"
entries = hosterNames.toTypedArray()
entryValues = hosterNames.toTypedArray()
setDefaultValue(hosterNames.first())
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = PREF_LANG_KEY
title = "Preferred Type"
entries = TYPES_ENTRIES
entryValues = TYPES_ENTRIES
setDefaultValue(PREF_LANG_DEFAULT)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
MultiSelectListPreference(screen.context).apply {
key = PREF_HOSTER_KEY
title = "Enable/Disable Hosts"
entries = hosterNames.toTypedArray()
entryValues = hosterNames.toTypedArray()
setDefaultValue(hosterNames.toSet())
setOnPreferenceChangeListener { _, newValue ->
@Suppress("UNCHECKED_CAST")
preferences.edit().putStringSet(key, newValue as Set<String>).commit()
}
}.also(screen::addPreference)
MultiSelectListPreference(screen.context).apply {
key = PREF_TYPE_TOGGLE_KEY
title = "Enable/Disable Types"
entries = TYPES_ENTRIES
entryValues = TYPES_ENTRY_VALUES
setDefaultValue(PREF_TYPES_TOGGLE_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
@Suppress("UNCHECKED_CAST")
preferences.edit().putStringSet(key, newValue as Set<String>).commit()
}
}.also(screen::addPreference)
}
}

View file

@ -0,0 +1,244 @@
package eu.kanade.tachiyomi.multisrc.zorotheme
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
object ZoroThemeFilters {
open class QueryPartFilter(
displayName: String,
val vals: Array<Pair<String, String>>,
) : AnimeFilter.Select<String>(
displayName,
vals.map { it.first }.toTypedArray(),
) {
fun toQueryPart() = vals[state].second
}
open class CheckBoxFilterList(name: String, values: List<CheckBox>) : AnimeFilter.Group<AnimeFilter.CheckBox>(name, values)
private class CheckBoxVal(name: String, state: Boolean = false) : AnimeFilter.CheckBox(name, state)
private inline fun <reified R> AnimeFilterList.asQueryPart(): String {
return this.filterIsInstance<R>().joinToString("") {
(it as QueryPartFilter).toQueryPart()
}
}
class TypeFilter : QueryPartFilter("Type", ZoroThemeFiltersData.TYPES)
class StatusFilter : QueryPartFilter("Status", ZoroThemeFiltersData.STATUS)
class RatedFilter : QueryPartFilter("Rated", ZoroThemeFiltersData.RATED)
class ScoreFilter : QueryPartFilter("Score", ZoroThemeFiltersData.SCORES)
class SeasonFilter : QueryPartFilter("Season", ZoroThemeFiltersData.SEASONS)
class LanguageFilter : QueryPartFilter("Language", ZoroThemeFiltersData.LANGUAGES)
class SortFilter : QueryPartFilter("Sort by", ZoroThemeFiltersData.SORTS)
class StartYearFilter : QueryPartFilter("Start year", ZoroThemeFiltersData.YEARS)
class StartMonthFilter : QueryPartFilter("Start month", ZoroThemeFiltersData.MONTHS)
class StartDayFilter : QueryPartFilter("Start day", ZoroThemeFiltersData.DAYS)
class EndYearFilter : QueryPartFilter("End year", ZoroThemeFiltersData.YEARS)
class EndMonthFilter : QueryPartFilter("End month", ZoroThemeFiltersData.MONTHS)
class EndDayFilter : QueryPartFilter("End day", ZoroThemeFiltersData.DAYS)
class GenresFilter : CheckBoxFilterList(
"Genres",
ZoroThemeFiltersData.GENRES.map { CheckBoxVal(it.first, false) },
)
val FILTER_LIST get() = AnimeFilterList(
TypeFilter(),
StatusFilter(),
RatedFilter(),
ScoreFilter(),
SeasonFilter(),
LanguageFilter(),
SortFilter(),
AnimeFilter.Separator(),
StartYearFilter(),
StartMonthFilter(),
StartDayFilter(),
EndYearFilter(),
EndMonthFilter(),
EndDayFilter(),
AnimeFilter.Separator(),
GenresFilter(),
)
data class FilterSearchParams(
val type: String = "",
val status: String = "",
val rated: String = "",
val score: String = "",
val season: String = "",
val language: String = "",
val sort: String = "",
val start_year: String = "",
val start_month: String = "",
val start_day: String = "",
val end_year: String = "",
val end_month: String = "",
val end_day: String = "",
val genres: String = "",
)
internal fun getSearchParameters(filters: AnimeFilterList): FilterSearchParams {
if (filters.isEmpty()) return FilterSearchParams()
val genres: String = filters.filterIsInstance<GenresFilter>()
.first()
.state.mapNotNull { format ->
if (format.state) {
ZoroThemeFiltersData.GENRES.find { it.first == format.name }!!.second
} else { null }
}.joinToString(",")
return FilterSearchParams(
filters.asQueryPart<TypeFilter>(),
filters.asQueryPart<StatusFilter>(),
filters.asQueryPart<RatedFilter>(),
filters.asQueryPart<ScoreFilter>(),
filters.asQueryPart<SeasonFilter>(),
filters.asQueryPart<LanguageFilter>(),
filters.asQueryPart<SortFilter>(),
filters.asQueryPart<StartYearFilter>(),
filters.asQueryPart<StartMonthFilter>(),
filters.asQueryPart<StartDayFilter>(),
filters.asQueryPart<EndYearFilter>(),
filters.asQueryPart<EndMonthFilter>(),
filters.asQueryPart<EndDayFilter>(),
genres,
)
}
private object ZoroThemeFiltersData {
val ALL = Pair("All", "")
val TYPES = arrayOf(
ALL,
Pair("Movie", "1"),
Pair("TV", "2"),
Pair("OVA", "3"),
Pair("ONA", "4"),
Pair("Special", "5"),
Pair("Music", "6"),
)
val STATUS = arrayOf(
ALL,
Pair("Finished Airing", "1"),
Pair("Currently Airing", "2"),
Pair("Not yet aired", "3"),
)
val RATED = arrayOf(
ALL,
Pair("G", "1"),
Pair("PG", "2"),
Pair("PG-13", "3"),
Pair("R", "4"),
Pair("R+", "5"),
Pair("Rx", "6"),
)
val SCORES = arrayOf(
ALL,
Pair("(1) Appalling", "1"),
Pair("(2) Horrible", "2"),
Pair("(3) Very Bad", "3"),
Pair("(4) Bad", "4"),
Pair("(5) Average", "5"),
Pair("(6) Fine", "6"),
Pair("(7) Good", "7"),
Pair("(8) Very Good", "8"),
Pair("(9) Great", "9"),
Pair("(10) Masterpiece", "10"),
)
val SEASONS = arrayOf(
ALL,
Pair("Spring", "1"),
Pair("Summer", "2"),
Pair("Fall", "3"),
Pair("Winter", "4"),
)
val LANGUAGES = arrayOf(
ALL,
Pair("SUB", "1"),
Pair("DUB", "2"),
Pair("SUB & DUB", "3"),
)
val SORTS = arrayOf(
Pair("Default", "default"),
Pair("Recently Added", "recently_added"),
Pair("Recently Updated", "recently_updated"),
Pair("Score", "score"),
Pair("Name A-Z", "name_az"),
Pair("Released Date", "released_date"),
Pair("Most Watched", "most_watched"),
)
val YEARS = arrayOf(ALL) + (1917..2024).map {
Pair(it.toString(), it.toString())
}.reversed().toTypedArray()
val MONTHS = arrayOf(ALL) + (1..12).map {
Pair(it.toString(), it.toString())
}.toTypedArray()
val DAYS = arrayOf(ALL) + (1..31).map {
Pair(it.toString(), it.toString())
}.toTypedArray()
val GENRES = arrayOf(
Pair("Action", "1"),
Pair("Adventure", "2"),
Pair("Cars", "3"),
Pair("Comedy", "4"),
Pair("Dementia", "5"),
Pair("Demons", "6"),
Pair("Drama", "8"),
Pair("Ecchi", "9"),
Pair("Fantasy", "10"),
Pair("Game", "11"),
Pair("Harem", "35"),
Pair("Historical", "13"),
Pair("Horror", "14"),
Pair("Isekai", "44"),
Pair("Josei", "43"),
Pair("Kids", "15"),
Pair("Magic", "16"),
Pair("Martial Arts", "17"),
Pair("Mecha", "18"),
Pair("Military", "38"),
Pair("Music", "19"),
Pair("Mystery", "7"),
Pair("Parody", "20"),
Pair("Police", "39"),
Pair("Psychological", "40"),
Pair("Romance", "22"),
Pair("Samurai", "21"),
Pair("School", "23"),
Pair("Sci-Fi", "24"),
Pair("Seinen", "42"),
Pair("Shoujo", "25"),
Pair("Shoujo Ai", "26"),
Pair("Shounen", "27"),
Pair("Shounen Ai", "28"),
Pair("Slice of Life", "36"),
Pair("Space", "29"),
Pair("Sports", "30"),
Pair("Super Power", "31"),
Pair("Supernatural", "37"),
Pair("Thriller", "41"),
Pair("Vampire", "32"),
Pair("Yaoi", "33"),
Pair("Yuri", "34"),
)
}
}

View file

@ -0,0 +1,39 @@
package eu.kanade.tachiyomi.multisrc.zorotheme.dto
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
@Serializable
data class HtmlResponse(
val html: String,
) {
fun getHtml(): Document {
return Jsoup.parseBodyFragment(html)
}
}
@Serializable
data class SourcesResponse(
val link: String? = null,
)
@Serializable
data class VideoDto(
val sources: List<VideoLink>,
val tracks: List<TrackDto>? = null,
)
@Serializable
data class SourceResponseDto(
val sources: JsonElement,
val encrypted: Boolean = true,
val tracks: List<TrackDto>? = null,
)
@Serializable
data class VideoLink(val file: String = "")
@Serializable
data class TrackDto(val file: String, val kind: String, val label: String = "")