Compare commits

..

No commits in common. "cbfdd982ff36189776a03cf38e7e652dd6243d46" and "fc828972d840c285e0796ef425b64733af51e111" have entirely different histories.

1135 changed files with 10660 additions and 12871 deletions

View File

@ -5,9 +5,7 @@
"schedule": ["on sunday"],
"includePaths": [
"buildSrc/gradle/**",
"buildSrc/*.gradle.kts",
"gradle/**",
"*.gradle.kts",
".github/**"
],
"ignoreDeps": ["keiyoushi/issue-moderator-action"],

View File

@ -79,7 +79,6 @@ for apk in REPO_APK_DIR.iterdir():
"lang": source["lang"],
"id": source["id"],
"baseUrl": source["baseUrl"],
"versionId": source["versionId"],
}
)

View File

@ -12,7 +12,7 @@ MULTISRC_LIB_REGEX = re.compile(r"^lib-multisrc/(?P<multisrc>\w+)")
LIB_REGEX = re.compile(r"^lib/(?P<lib>\w+)")
MODULE_REGEX = re.compile(r"^:src:(?P<lang>\w+):(?P<extension>\w+)$")
CORE_FILES_REGEX = re.compile(
r"^(buildSrc/|core/|gradle/|build\.gradle\.kts|common\.gradle|gradle\.properties|settings\.gradle\.kts|.github/scripts)"
r"^(buildSrc/|core/|gradle/|build\.gradle\.kts|common\.gradle|gradle\.properties|settings\.gradle\.kts)"
)
def run_command(command: str) -> str:

View File

@ -22,7 +22,7 @@ for module in to_delete:
shutil.copytree(src=LOCAL_REPO.joinpath("apk"), dst=REMOTE_REPO.joinpath("apk"), dirs_exist_ok = True)
shutil.copytree(src=LOCAL_REPO.joinpath("icon"), dst=REMOTE_REPO.joinpath("icon"), dirs_exist_ok = True)
with REMOTE_REPO.joinpath("index.json").open() as remote_index_file:
with REMOTE_REPO.joinpath("index.min.json").open() as remote_index_file:
remote_index = json.load(remote_index_file)
with LOCAL_REPO.joinpath("index.min.json").open() as local_index_file:
@ -38,10 +38,6 @@ index.sort(key=lambda x: x["pkg"])
with REMOTE_REPO.joinpath("index.json").open("w", encoding="utf-8") as index_file:
json.dump(index, index_file, ensure_ascii=False, indent=2)
for item in index:
for source in item["sources"]:
source.pop("versionId", None)
with REMOTE_REPO.joinpath("index.min.json").open("w", encoding="utf-8") as index_min_file:
json.dump(index, index_min_file, ensure_ascii=False, separators=(",", ":"))

View File

@ -54,7 +54,6 @@ that existing contributors will not actively teach them to you.
- [Android Studio](https://developer.android.com/studio)
- Emulator or phone with developer options enabled and a recent version of Tachiyomi installed
- [Icon Generator](https://as280093.github.io/AndroidAssetStudio/icons-launcher.html)
- [Try jsoup](https://try.jsoup.org/)
### Cloning the repository

View File

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

View File

@ -13,7 +13,9 @@ android {
namespace = "eu.kanade.tachiyomi.lib.${project.name}"
androidResources.enable = false
buildFeatures {
androidResources = false
}
}
dependencies {

View File

@ -17,7 +17,7 @@ android {
namespace "eu.kanade.tachiyomi.extension"
sourceSets {
main {
manifest.srcFile layout.buildDirectory.file('tempAndroidManifest.xml')
manifest.srcFile "AndroidManifest.xml"
java.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
@ -105,31 +105,21 @@ dependencies {
compileOnly(libs.bundles.common)
}
tasks.register("copyManifestFile", Copy) {
from 'AndroidManifest.xml'
rename { 'tempAndroidManifest.xml' }
into layout.buildDirectory
}
tasks.register("writeManifestFile") {
dependsOn(copyManifestFile)
doLast {
File tempFile = android.sourceSets.getByName('main').manifest.srcFile
if (!tempFile.exists()) {
tempFile.write('<?xml version="1.0" encoding="utf-8"?>\n<manifest />\n')
def manifest = android.sourceSets.getByName("main").manifest
if (!manifest.srcFile.exists()) {
File tempFile = layout.buildDirectory.get().file("tempAndroidManifest.xml").getAsFile()
if (!tempFile.exists()) {
tempFile.withWriter {
it.write('<?xml version="1.0" encoding="utf-8"?>\n<manifest />\n')
}
}
manifest.srcFile(tempFile.path)
}
}
}
afterEvaluate {
tasks.withType(com.android.build.gradle.tasks.PackageAndroidArtifact).configureEach {
// need to be in afterEvaluate to overwrite default value
createdBy = ""
// https://stackoverflow.com/a/77745844
doFirst { appMetadata.asFile.getOrNull()?.write('') }
}
}
preBuild.dependsOn(writeManifestFile, lintKotlin)
if (System.getenv("CI") != "true") {
lintKotlin.dependsOn(formatKotlin)

View File

@ -1,22 +1,22 @@
[versions]
kotlin = "1.7.21"
coroutines = "1.6.4"
serialization = "1.4.0"
kotlin_version = "1.7.21"
coroutines_version = "1.6.4"
serialization_version = "1.4.0"
[libraries]
gradle-agp = { module = "com.android.tools.build:gradle", version = "8.13.0" }
gradle-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
gradle-serialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin" }
gradle-agp = { module = "com.android.tools.build:gradle", version = "8.6.1" }
gradle-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin_version" }
gradle-serialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin_version" }
gradle-kotlinter = { module = "org.jmailen.gradle:kotlinter-gradle", version = "3.13.0" }
tachiyomi-lib = { module = "com.github.keiyoushi:extensions-lib", version = "v1.4.2.1" }
kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "kotlin" }
kotlin-protobuf = { module = "org.jetbrains.kotlinx:kotlinx-serialization-protobuf", version.ref = "serialization" }
kotlin-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "kotlin_version" }
kotlin-protobuf = { module = "org.jetbrains.kotlinx:kotlinx-serialization-protobuf", version.ref = "serialization_version" }
kotlin-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization_version" }
coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" }
coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines_version" }
coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines_version" }
injekt-core = { module = "com.github.null2264.injekt:injekt-core", version = "4135455a2a" }
rxjava = { module = "io.reactivex:rxjava", version = "1.3.8" }

View File

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

View File

@ -2,4 +2,4 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 8
baseVersionCode = 6

View File

@ -14,8 +14,6 @@ import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import keiyoushi.utils.parseAs
import keiyoushi.utils.tryParse
import kotlinx.serialization.SerializationException
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
@ -36,6 +34,7 @@ import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import kotlin.math.floor
@ -45,7 +44,6 @@ abstract class GigaViewer(
override val baseUrl: String,
override val lang: String,
private val cdnUrl: String = "",
private val isPaginated: Boolean = false,
) : ParsedHttpSource() {
override val supportsLatest = true
@ -136,7 +134,7 @@ abstract class GigaViewer(
.attr("data-src")
}
protected fun chapterListParseSinglePage(response: Response): List<SChapter> {
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
val aggregateId = document.selectFirst("script.js-valve")!!.attr("data-giga_series")
@ -182,61 +180,6 @@ abstract class GigaViewer(
return chapters
}
protected fun paginatedChaptersRequest(referer: String, aggregateId: String, offset: Int): Response {
val headers = headers.newBuilder()
.set("Referer", referer)
.build()
val apiUrl = baseUrl.toHttpUrl().newBuilder()
.addPathSegment("api")
.addPathSegment("viewer")
.addPathSegment("pagination_readable_products")
.addQueryParameter("type", "episode")
.addQueryParameter("aggregate_id", aggregateId)
.addQueryParameter("sort_order", "desc")
.addQueryParameter("offset", offset.toString())
.build()
.toString()
val request = GET(apiUrl, headers)
return client.newCall(request).execute()
}
protected fun chapterListParsePaginated(response: Response): List<SChapter> {
val document = response.asJsoup()
val referer = response.request.url.toString()
val aggregateId = document.selectFirst("script.js-valve")!!.attr("data-giga_series")
val chapters = mutableListOf<SChapter>()
var offset = 0
// repeat until the offset is too large to return any chapters, resulting in an empty list
while (true) {
// make request
val result = paginatedChaptersRequest(referer, aggregateId, offset)
val resultData = result.parseAs<List<GigaViewerPaginationReadableProduct>>()
if (resultData.isEmpty()) {
break
}
resultData.mapTo(chapters) { element ->
element.toSChapter(chapterListMode, publisher)
}
// increase offset
offset += resultData.size
}
return chapters
}
override fun chapterListParse(response: Response): List<SChapter> {
return if (isPaginated) {
chapterListParsePaginated(response)
} else {
chapterListParseSinglePage(response)
}
}
override fun chapterListSelector() = "li.episode"
protected open val chapterListMode = CHAPTER_LIST_PAID
@ -252,7 +195,9 @@ abstract class GigaViewer(
} else if (chapterListMode == CHAPTER_LIST_LOCKED && element.hasClass("private")) {
name = LOCK + name
}
date_upload = DATE_PARSER_SIMPLE.tryParse(info.selectFirst("span.series-episode-list-date")?.text().orEmpty())
date_upload = info.selectFirst("span.series-episode-list-date")
?.text().orEmpty()
.toDate()
scanlator = publisher
setUrlWithoutDomain(if (info.tagName() == "a") info.attr("href") else mangaUrl)
}
@ -269,18 +214,13 @@ abstract class GigaViewer(
}
}
val isScrambled = episode.readableProduct.pageStructure.choJuGiga == "baku"
return episode.readableProduct.pageStructure.pages
.filter { it.type == "main" }
.mapIndexed { i, page ->
val imageUrl = page.src.toHttpUrl().newBuilder().apply {
addQueryParameter("width", page.width.toString())
addQueryParameter("height", page.height.toString())
if (isScrambled) {
addQueryParameter("baku", "true")
}
}.toString()
val imageUrl = page.src.toHttpUrl().newBuilder()
.addQueryParameter("width", page.width.toString())
.addQueryParameter("height", page.height.toString())
.toString()
Page(i, document.location(), imageUrl)
}
}
@ -314,7 +254,7 @@ abstract class GigaViewer(
protected open fun imageIntercept(chain: Interceptor.Chain): Response {
var request = chain.request()
if (!request.url.toString().startsWith(cdnUrl) || request.url.queryParameter("baku") != "true") {
if (!request.url.toString().startsWith(cdnUrl)) {
return chain.proceed(request)
}
@ -324,7 +264,6 @@ abstract class GigaViewer(
val newUrl = request.url.newBuilder()
.removeAllQueryParameters("width")
.removeAllQueryParameters("height")
.removeAllQueryParameters("baku")
.build()
request = request.newBuilder().url(newUrl).build()
@ -375,7 +314,14 @@ abstract class GigaViewer(
}
}
private fun String.toDate(): Long {
return runCatching { DATE_PARSER.parse(this)?.time }
.getOrNull() ?: 0L
}
companion object {
private val DATE_PARSER by lazy { SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH) }
private const val DIVIDE_NUM = 4
private const val MULTIPLE = 8
private val jpegMediaType = "image/jpeg".toMediaType()
@ -383,7 +329,7 @@ abstract class GigaViewer(
const val CHAPTER_LIST_PAID = 0
const val CHAPTER_LIST_LOCKED = 1
const val YEN_BANKNOTE = "💴 "
const val LOCK = "🔒 "
private const val YEN_BANKNOTE = "💴 "
private const val LOCK = "🔒 "
}
}

View File

@ -1,14 +1,6 @@
package eu.kanade.tachiyomi.multisrc.gigaviewer
import eu.kanade.tachiyomi.multisrc.gigaviewer.GigaViewer.Companion.CHAPTER_LIST_LOCKED
import eu.kanade.tachiyomi.multisrc.gigaviewer.GigaViewer.Companion.CHAPTER_LIST_PAID
import eu.kanade.tachiyomi.multisrc.gigaviewer.GigaViewer.Companion.LOCK
import eu.kanade.tachiyomi.multisrc.gigaviewer.GigaViewer.Companion.YEN_BANKNOTE
import eu.kanade.tachiyomi.source.model.SChapter
import keiyoushi.utils.tryParse
import kotlinx.serialization.Serializable
import java.text.SimpleDateFormat
import java.util.Locale
@Serializable
data class GigaViewerEpisodeDto(
@ -23,7 +15,6 @@ data class GigaViewerReadableProduct(
@Serializable
data class GigaViewerPageStructure(
val pages: List<GigaViewerPage> = emptyList(),
val choJuGiga: String,
)
@Serializable
@ -33,31 +24,3 @@ data class GigaViewerPage(
val type: String = "",
val width: Int = 0,
)
@Serializable
class GigaViewerPaginationReadableProduct(
private val display_open_at: String?,
private val readable_product_id: String = "",
private val status: GigaViewerPaginationReadableProductStatus?,
private val title: String = "",
) {
fun toSChapter(chapterListMode: Int, publisher: String) = SChapter.create().apply {
name = title
if (chapterListMode == CHAPTER_LIST_PAID && status?.label != "is_free") {
name = YEN_BANKNOTE + name
} else if (chapterListMode == CHAPTER_LIST_LOCKED && status?.label == "unpublished") {
name = LOCK + name
}
date_upload = DATE_PARSER_COMPLEX.tryParse(display_open_at)
scanlator = publisher
url = "/episode/$readable_product_id"
}
}
@Serializable
class GigaViewerPaginationReadableProductStatus(
val label: String?, // is_free, is_rentable, is_purchasable, unpublished
)
val DATE_PARSER_SIMPLE = SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
val DATE_PARSER_COMPLEX = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH)

View File

@ -2,4 +2,4 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 34
baseVersionCode = 33

View File

@ -373,8 +373,8 @@ abstract class GroupLe(
}
val readerMark = when {
html.contains("rm_h.readerInit(") -> "rm_h.readerInit("
html.contains("rm_h.readerDoInit(") -> "rm_h.readerDoInit("
html.contains("rm_h.readerDoInit([") -> "rm_h.readerDoInit(["
html.contains("rm_h.readerInit([") -> "rm_h.readerInit(["
!response.request.url.toString().contains(baseUrl) -> {
throw Exception("Не удалось загрузить главу. Url: ${response.request.url}")
}

View File

@ -2,8 +2,4 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 23
dependencies {
compileOnly("com.squareup.okhttp3:okhttp-brotli:5.0.0-alpha.11")
}
baseVersionCode = 22

View File

@ -1,6 +1,5 @@
package eu.kanade.tachiyomi.multisrc.kemono
import android.app.Application
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreferenceCompat
@ -16,19 +15,14 @@ import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import keiyoushi.utils.getPreferences
import keiyoushi.utils.parseAs
import okhttp3.Cache
import okhttp3.CacheControl
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import okhttp3.Request
import okhttp3.Response
import okhttp3.brotli.BrotliInterceptor
import rx.Observable
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.File
import uy.kohesive.injekt.injectLazy
import java.lang.Thread.sleep
import java.util.TimeZone
import java.util.concurrent.TimeUnit
import kotlin.math.min
open class Kemono(
@ -38,35 +32,13 @@ open class Kemono(
) : HttpSource(), ConfigurableSource {
override val supportsLatest = true
override val client = network.cloudflareClient.newBuilder()
.rateLimit(1)
.addInterceptor { chain ->
val request = chain.request()
if (request.url.pathSegments.first() == "api") {
chain.proceed(request.newBuilder().header("Accept", "text/css").build())
} else {
chain.proceed(request)
}
}
.apply {
val index = networkInterceptors().indexOfFirst { it is BrotliInterceptor }
if (index >= 0) interceptors().add(networkInterceptors().removeAt(index))
}
.cache(
Cache(
directory = File(Injekt.get<Application>().externalCacheDir, "network_cache_${name.lowercase()}"),
maxSize = 50L * 1024 * 1024, // 50 MiB
),
)
.build()
private val creatorsClient = client.newBuilder()
.readTimeout(5, TimeUnit.MINUTES)
.build()
override val client = network.cloudflareClient.newBuilder().rateLimit(1).build()
override fun headersBuilder() = super.headersBuilder()
.add("Referer", "$baseUrl/")
private val json: Json by injectLazy()
private val preferences = getPreferences()
private val apiPath = "api/v1"
@ -75,6 +47,8 @@ open class Kemono(
private val imgCdnUrl = baseUrl.replace("//", "//img.")
private var mangasCache: List<KemonoCreatorDto> = emptyList()
private fun String.formatAvatarUrl(): String = removePrefix("https://").replaceBefore('/', imgCdnUrl)
override fun popularMangaRequest(page: Int) = throw UnsupportedOperationException()
@ -111,7 +85,6 @@ open class Kemono(
is SortFilter -> {
sort = filter.getValue() to if (filter.state!!.ascending) "asc" else "desc"
}
is TypeFilter -> {
filter.state.filter { state -> state.isIncluded() }.forEach { tri ->
typeIncluded.add(tri.value)
@ -121,60 +94,44 @@ open class Kemono(
typeExcluded.add(tri.value)
}
}
is FavoritesFilter -> {
is FavouritesFilter -> {
fav = when (filter.state[0].state) {
0 -> null
1 -> true
else -> false
}
}
else -> {}
}
}
val mangas = run {
val favorites = if (fav != null) {
val response = client.newCall(GET("$baseUrl/$apiPath/account/favorites", headers)).execute()
var mangas = mangasCache
if (page == 1 || mangasCache.isEmpty()) {
var favourites: List<KemonoFavouritesDto> = emptyList()
if (fav != null) {
val favores = client.newCall(GET("$baseUrl/$apiPath/account/favorites", headers)).execute()
if (response.isSuccessful) {
response.parseAs<List<KemonoFavoritesDto>>().filterNot { it.service.lowercase() == "discord" }
} else {
response.close()
val message = if (response.code == 401) "You are not logged in" else "HTTP error ${response.code}"
throw Exception("Failed to fetch favorites: $message")
}
} else {
emptyList()
if (favores.code == 401) throw Exception("You are not Logged In")
favourites = favores.parseAs<List<KemonoFavouritesDto>>().filterNot { it.service.lowercase() == "discord" }
}
val request = GET(
"$baseUrl/$apiPath/creators",
headers,
CacheControl.Builder().maxStale(30, TimeUnit.MINUTES).build(),
)
val response = creatorsClient.newCall(request).execute()
if (!response.isSuccessful) {
response.close()
throw Exception("HTTP error ${response.code}")
}
val response = client.newCall(GET("$baseUrl/$apiPath/creators", headers)).execute()
val allCreators = response.parseAs<List<KemonoCreatorDto>>().filterNot { it.service.lowercase() == "discord" }
allCreators.filter {
mangas = allCreators.filter {
val includeType = typeIncluded.isEmpty() || typeIncluded.contains(it.service.serviceName().lowercase())
val excludeType = typeExcluded.isNotEmpty() && typeExcluded.contains(it.service.serviceName().lowercase())
val regularSearch = it.name.contains(title, true)
val isFavorited = when (fav) {
true -> favorites.any { f -> f.id == it.id.also { _ -> it.fav = f.faved_seq } }
false -> favorites.none { f -> f.id == it.id }
val isFavourited = when (fav) {
true -> favourites.any { f -> f.id == it.id.also { _ -> it.fav = f.faved_seq } }
false -> favourites.none { f -> f.id == it.id }
else -> true
}
includeType && !excludeType && isFavorited &&
includeType && !excludeType && isFavourited &&
regularSearch
}
}.also { mangasCache = it }
}
val sorted = when (sort.first) {
@ -185,7 +142,6 @@ open class Kemono(
mangas.sortedBy { it.favorited }
}
}
"tit" -> {
if (sort.second == "desc") {
mangas.sortedByDescending { it.name }
@ -193,7 +149,6 @@ open class Kemono(
mangas.sortedBy { it.name }
}
}
"new" -> {
if (sort.second == "desc") {
mangas.sortedByDescending { it.id }
@ -201,16 +156,14 @@ open class Kemono(
mangas.sortedBy { it.id }
}
}
"fav" -> {
if (fav != true) throw Exception("Please check 'Favorites Only' Filter")
if (fav != true) throw Exception("Please check 'Favourites Only' Filter")
if (sort.second == "desc") {
mangas.sortedByDescending { it.fav }
} else {
mangas.sortedBy { it.fav }
}
}
else -> {
if (sort.second == "desc") {
mangas.sortedByDescending { it.updatedDate }
@ -250,7 +203,7 @@ open class Kemono(
var hasNextPage = true
val result = ArrayList<SChapter>()
while (offset < prefMaxPost && hasNextPage) {
val request = GET("$baseUrl/$apiPath${manga.url}/posts?o=$offset", headers)
val request = GET("$baseUrl/$apiPath${manga.url}?o=$offset", headers)
val page: List<KemonoPostDto> = retry(request).parseAs()
page.forEach { post -> if (post.images.isNotEmpty()) result.add(post.toSChapter()) }
offset += PAGE_POST_LIMIT
@ -299,6 +252,10 @@ open class Kemono(
override fun imageUrlParse(response: Response) = throw UnsupportedOperationException()
private inline fun <reified T> Response.parseAs(): T = use {
json.decodeFromStream(it.body.byteStream())
}
override fun setupPreferenceScreen(screen: PreferenceScreen) {
ListPreference(screen.context).apply {
key = POST_PAGES_PREF
@ -327,7 +284,7 @@ open class Kemono(
getSortsList,
),
TypeFilter("Types", getTypes),
FavoritesFilter(),
FavouritesFilter(),
)
open val getTypes: List<String> = emptyList()
@ -338,7 +295,7 @@ open class Kemono(
Pair("Date Updated", "lat"),
Pair("Alphabetical Order", "tit"),
Pair("Service", "serv"),
Pair("Date Favorited", "fav"),
Pair("Date Favourited", "fav"),
)
internal open class TypeFilter(name: String, vals: List<String>) :
@ -347,19 +304,17 @@ open class Kemono(
vals.map { TriFilter(it, it.lowercase()) },
)
internal class FavoritesFilter() :
internal class FavouritesFilter() :
Filter.Group<TriFilter>(
"Favorites",
listOf(TriFilter("Favorites Only", "fav")),
"Favourites",
listOf(TriFilter("Favourites Only", "fav")),
)
internal open class TriFilter(name: String, val value: String) : Filter.TriState(name)
internal open class SortFilter(name: String, selection: Selection, private val vals: List<Pair<String, String>>) :
Filter.Sort(name, vals.map { it.first }.toTypedArray(), selection) {
fun getValue() = vals[state!!.index].second
}
companion object {
private const val PAGE_POST_LIMIT = 50
private const val PAGE_CREATORS_LIMIT = 50

View File

@ -10,7 +10,7 @@ import java.text.SimpleDateFormat
import java.util.Locale
@Serializable
class KemonoFavoritesDto(
class KemonoFavouritesDto(
val id: String,
val name: String,
val service: String,

View File

@ -2,4 +2,4 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 37
baseVersionCode = 36

View File

@ -589,7 +589,7 @@ abstract class LibGroup(
private const val API_DOMAIN_PREF = "MangaLibApiDomain"
private const val API_DOMAIN_TITLE = "Выбор домена API"
private const val API_DOMAIN_DEFAULT = "https://api.cdnlibs.org"
private const val API_DOMAIN_DEFAULT = "https://api.imglib.info"
private const val TOKEN_STORE = "TokenStore"
@ -652,8 +652,8 @@ abstract class LibGroup(
val domainApiPref = ListPreference(screen.context).apply {
key = API_DOMAIN_PREF
title = API_DOMAIN_TITLE
entries = arrayOf("Основной (api.cdnlibs.org)", "Резервный (api2.mangalib.me)", "Резервный (hapi.hentaicdn.org)", "Резервный (api.imglib.info)")
entryValues = arrayOf(API_DOMAIN_DEFAULT, "https://api2.mangalib.me", "https://hapi.hentaicdn.org", "https://api.imglib.info")
entries = arrayOf("Официальное приложение (api.imglib.info)", "Основной (api.lib.social)", "Резервный (api.mangalib.me)", "Резервный 2 (api2.mangalib.me)")
entryValues = arrayOf(API_DOMAIN_DEFAULT, "https://api.lib.social", "https://api.mangalib.me", "https://api2.mangalib.me")
summary = "%s" +
"\n\nВыбор домена API, используемого для работы приложения." +
"\n\nПо умолчанию «Официальное приложение»" +

View File

@ -3,7 +3,7 @@
<application>
<activity
android:name="eu.kanade.tachiyomi.extension.en.kmanga.KMangaUrlActivity"
android:name="eu.kanade.tachiyomi.multisrc.machinetranslations.MachineTranslationsUrlActivity"
android:excludeFromRecents="true"
android:exported="true"
android:theme="@android:style/Theme.NoDisplay">
@ -13,9 +13,9 @@
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="kmanga.kodansha.com"
android:pathPrefix="/title/"
android:scheme="https" />
android:host="${SOURCEHOST}"
android:pathPattern="/.*/..*"
android:scheme="${SOURCESCHEME}" />
</intent-filter>
</activity>
</application>

View File

@ -1,202 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,6 @@
font_size_title=Font size
font_size_summary=Font changes will not be applied to downloaded or cached chapters. The font size will be adjusted according to the size of the dialog box.
font_size_message=Font size changed to %s
default_font_size=Default
disable_website_setting_title=Disable source settings
disable_website_setting_summary=Site fonts will be disabled and your device's fonts will be applied. This does not apply to downloaded or cached chapters.

View File

@ -0,0 +1,6 @@
font_size_title=Tamanho da fonte
font_size_summary=As alterações de fonte não serão aplicadas aos capítulos baixados ou armazenados em cache. O tamanho da fonte será ajustado de acordo com o tamanho da caixa de diálogo.
font_size_message=Tamanho da fonte foi alterada para %s
default_font_size=Padrão
disable_website_setting_title=Desativar configurações do site
disable_website_setting_summary=As fontes do site serão desativadas e as fontes de seu dispositivo serão aplicadas. Isso não se aplica a capítulos baixados ou armazenados em cache.

View File

@ -0,0 +1,9 @@
plugins {
id("lib-multisrc")
}
baseVersionCode = 5
dependencies {
api(project(":lib:i18n"))
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

View File

@ -0,0 +1,345 @@
package eu.kanade.tachiyomi.multisrc.machinetranslations
import android.content.SharedPreferences
import android.os.Build
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreferenceCompat
import eu.kanade.tachiyomi.lib.i18n.Intl
import eu.kanade.tachiyomi.multisrc.machinetranslations.interceptors.ComposedImageInterceptor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import keiyoushi.utils.getPreferencesLazy
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.TimeUnit
@RequiresApi(Build.VERSION_CODES.O)
abstract class MachineTranslations(
override val name: String,
override val baseUrl: String,
private val language: Language,
) : ParsedHttpSource(), ConfigurableSource {
override val supportsLatest = true
private val json: Json by injectLazy()
override val lang = language.lang
protected val preferences: SharedPreferences by getPreferencesLazy()
/**
* A flag that tracks whether the settings have been changed. It is used to indicate if
* any configuration change has occurred. Once the value is accessed, it resets to `false`.
* This is useful for tracking whether a preference has been modified, and ensures that
* the change status is cleared after it has been accessed, to prevent multiple triggers.
*/
private var isSettingsChanged: Boolean = false
get() {
val current = field
field = false
return current
}
protected var fontSize: Int
get() = preferences.getString(FONT_SIZE_PREF, DEFAULT_FONT_SIZE)!!.toInt()
set(value) = preferences.edit().putString(FONT_SIZE_PREF, value.toString()).apply()
protected var disableSourceSettings: Boolean
get() = preferences.getBoolean(DISABLE_SOURCE_SETTINGS_PREF, language.disableSourceSettings)
set(value) = preferences.edit().putBoolean(DISABLE_SOURCE_SETTINGS_PREF, value).apply()
private val intl = Intl(
language = language.lang,
baseLanguage = "en",
availableLanguages = setOf("en", "es", "fr", "id", "it", "pt-BR"),
classLoader = this::class.java.classLoader!!,
)
private val settings get() = language.apply {
fontSize = this@MachineTranslations.fontSize
}
open val useDefaultComposedImageInterceptor: Boolean = true
override val client: OkHttpClient get() = clientInstance!!
/**
* This ensures that the `OkHttpClient` instance is only created when required, and it is rebuilt
* when there are configuration changes to ensure that the client uses the most up-to-date settings.
*/
private var clientInstance: OkHttpClient? = null
get() {
if (field == null || isSettingsChanged) {
field = clientBuilder().build()
}
return field
}
protected open fun clientBuilder() = network.cloudflareClient.newBuilder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
.addInterceptorIf(useDefaultComposedImageInterceptor, ComposedImageInterceptor(baseUrl, settings))
private fun OkHttpClient.Builder.addInterceptorIf(condition: Boolean, interceptor: Interceptor): OkHttpClient.Builder {
return this.takeIf { condition.not() } ?: this.addInterceptor(interceptor)
}
// ============================== Popular ===============================
private val popularFilter = FilterList(SelectionList("", listOf(Option(value = "views", query = "sort_by"))))
override fun popularMangaRequest(page: Int) = searchMangaRequest(page, "", popularFilter)
override fun popularMangaSelector() = searchMangaSelector()
override fun popularMangaFromElement(element: Element) = searchMangaFromElement(element)
override fun popularMangaNextPageSelector() = searchMangaNextPageSelector()
// =============================== Latest ===============================
private val latestFilter = FilterList(SelectionList("", listOf(Option(value = "recent", query = "sort_by"))))
override fun latestUpdatesRequest(page: Int) = searchMangaRequest(page, "", latestFilter)
override fun latestUpdatesSelector() = searchMangaSelector()
override fun latestUpdatesFromElement(element: Element) = searchMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = searchMangaNextPageSelector()
// =========================== Search ============================
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$baseUrl/search".toHttpUrl().newBuilder()
.addQueryParameter("page", page.toString())
if (query.isNotBlank()) {
url.addQueryParameter("query", query)
}
filters.forEach { filter ->
when (filter) {
is SelectionList -> {
val selected = filter.selected()
if (selected.value.isBlank()) {
return@forEach
}
url.addQueryParameter(selected.query, selected.value)
}
is GenreList -> {
filter.state.filter(GenreCheckBox::state).forEach { genre ->
url.addQueryParameter("genres", genre.id)
}
}
else -> {}
}
}
return GET(url.build(), headers)
}
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
if (query.startsWith(PREFIX_SEARCH)) {
val slug = query.removePrefix(PREFIX_SEARCH)
return fetchMangaDetails(SManga.create().apply { url = "/comics/$slug" }).map { manga ->
MangasPage(listOf(manga), false)
}
}
return super.fetchSearchManga(page, query, filters)
}
override fun searchMangaSelector() = "section h2 + div > div"
override fun searchMangaFromElement(element: Element) = SManga.create().apply {
title = element.selectFirst("h3")!!.text()
thumbnail_url = element.selectFirst("img")?.absUrl("src")
setUrlWithoutDomain(element.selectFirst("a")!!.absUrl("href"))
}
override fun searchMangaNextPageSelector() = "a[href*=search]:contains(Next)"
// =========================== Manga Details ============================
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
title = document.selectFirst("h1")!!.text()
description = document.selectFirst("p:has(span:contains(Synopsis))")?.ownText()
author = document.selectFirst("p:has(span:contains(Author))")?.ownText()
genre = document.select("h2:contains(Genres) + div span").joinToString { it.text() }
thumbnail_url = document.selectFirst("img.object-cover")?.absUrl("src")
document.selectFirst("p:has(span:contains(Status))")?.ownText()?.let {
status = when (it.lowercase()) {
"ongoing" -> SManga.ONGOING
"complete" -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
}
setUrlWithoutDomain(document.location())
}
// ============================== Chapters ==============================
override fun chapterListSelector() = "section li"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
element.selectFirst("a")!!.let {
name = it.ownText()
setUrlWithoutDomain(it.absUrl("href"))
}
date_upload = parseChapterDate(element.selectFirst("span")?.text())
}
// =============================== Pages ================================
override fun pageListParse(document: Document): List<Page> {
val pages = document.selectFirst("div#json-data")
?.ownText()?.parseAs<List<PageDto>>()
?: throw Exception("Pages not found")
return pages.mapIndexed { index, dto ->
val imageUrl = when {
dto.imageUrl.startsWith("http") -> dto.imageUrl
else -> "https://${dto.imageUrl}"
}
val fragment = json.encodeToString<List<Dialog>>(
dto.dialogues.filter { it.getTextBy(language).isNotBlank() },
)
Page(index, imageUrl = "$imageUrl#$fragment")
}
}
override fun imageUrlParse(document: Document): String = ""
// ============================= Utilities ==============================
private fun parseChapterDate(date: String?): Long {
date ?: return 0
return try { dateFormat.parse(date)!!.time } catch (_: Exception) { parseRelativeDate(date) }
}
private fun parseRelativeDate(date: String): Long {
val number = Regex("""(\d+)""").find(date)?.value?.toIntOrNull() ?: return 0
val cal = Calendar.getInstance()
return when {
date.contains("day", true) -> cal.apply { add(Calendar.DAY_OF_MONTH, -number) }.timeInMillis
date.contains("hour", true) -> cal.apply { add(Calendar.HOUR, -number) }.timeInMillis
date.contains("minute", true) -> cal.apply { add(Calendar.MINUTE, -number) }.timeInMillis
date.contains("second", true) -> cal.apply { add(Calendar.SECOND, -number) }.timeInMillis
date.contains("week", true) -> cal.apply { add(Calendar.DAY_OF_MONTH, -number * 7) }.timeInMillis
else -> 0
}
}
private inline fun <reified T> String.parseAs(): T {
return json.decodeFromString(this)
}
// =============================== Filters ================================
override fun getFilterList(): FilterList {
val filters = mutableListOf<Filter<*>>(
SelectionList("Sort", sortByList),
Filter.Separator(),
GenreList(title = "Genres", genres = genreList),
)
return FilterList(filters)
}
override fun setupPreferenceScreen(screen: PreferenceScreen) {
// Some libreoffice font sizes
val sizes = arrayOf(
"24", "26", "28",
"32", "36", "40",
"42", "44", "48",
"54", "60", "72",
"80", "88", "96",
)
ListPreference(screen.context).apply {
key = FONT_SIZE_PREF
title = intl["font_size_title"]
entries = sizes.map {
"${it}pt" + if (it == DEFAULT_FONT_SIZE) " - ${intl["default_font_size"]}" else ""
}.toTypedArray()
entryValues = sizes
summary = intl["font_size_summary"]
setOnPreferenceChange { _, newValue ->
val selected = newValue as String
val index = this.findIndexOfValue(selected)
val entry = entries[index] as String
fontSize = selected.toInt()
Toast.makeText(
screen.context,
intl["font_size_message"].format(entry),
Toast.LENGTH_LONG,
).show()
true // It's necessary to update the user interface
}
}.also(screen::addPreference)
if (language.disableSourceSettings.not()) {
SwitchPreferenceCompat(screen.context).apply {
key = DISABLE_SOURCE_SETTINGS_PREF
title = "${intl["disable_website_setting_title"]}"
summary = intl["disable_website_setting_summary"]
setDefaultValue(false)
setOnPreferenceChange { _, newValue ->
disableSourceSettings = newValue as Boolean
true
}
}.also(screen::addPreference)
}
}
/**
* Sets an `OnPreferenceChangeListener` for the preference, and before triggering the original listener,
* marks that the configuration has changed by setting `isSettingsChanged` to `true`.
* This behavior is useful for applying runtime configurations in the HTTP client,
* ensuring that the preference change is registered before invoking the original listener.
*/
protected fun Preference.setOnPreferenceChange(onPreferenceChangeListener: Preference.OnPreferenceChangeListener) {
setOnPreferenceChangeListener { preference, newValue ->
isSettingsChanged = true
onPreferenceChangeListener.onPreferenceChange(preference, newValue)
}
}
companion object {
val PAGE_REGEX = Regex(".*?\\.(webp|png|jpg|jpeg)#\\[.*?]", RegexOption.IGNORE_CASE)
const val PREFIX_SEARCH = "id:"
private const val FONT_SIZE_PREF = "fontSizePref"
private const val DISABLE_SOURCE_SETTINGS_PREF = "disableSourceSettingsPref"
private const val DEFAULT_FONT_SIZE = "24"
private val dateFormat: SimpleDateFormat = SimpleDateFormat("dd MMMM yyyy", Locale.US)
}
}

View File

@ -1,5 +1,6 @@
package eu.kanade.tachiyomi.extension.all.manhuarm
package eu.kanade.tachiyomi.multisrc.machinetranslations
import android.graphics.Color
import android.os.Build
import androidx.annotation.RequiresApi
import kotlinx.serialization.SerialName
@ -18,10 +19,10 @@ import java.io.IOException
@Serializable
class PageDto(
@SerialName("image")
@SerialName("img_url")
val imageUrl: String,
@SerialName("texts")
@SerialName("translations")
@Serializable(with = DialogListSerializer::class)
val dialogues: List<Dialog> = emptyList(),
)
@ -29,25 +30,37 @@ class PageDto(
@Serializable
@RequiresApi(Build.VERSION_CODES.O)
data class Dialog(
val x: Float,
val y: Float,
private val _width: Float,
private val _height: Float,
val x1: Float,
val y1: Float,
val x2: Float,
val y2: Float,
val angle: Float = 0f,
val isBold: Boolean = false,
val isNewApi: Boolean = false,
val textByLanguage: Map<String, String> = emptyMap(),
val type: String = "normal",
private val fbColor: List<Int> = emptyList(),
private val bgColor: List<Int> = emptyList(),
) {
var scale: Float = 1F
val height: Float get() = scale * _height
val width: Float get() = scale * _width
val text: String get() = textByLanguage["text"] ?: throw Exception("Dialog not found")
fun getTextBy(language: Language) = when {
!language.disableTranslator -> textByLanguage[language.origin]
else -> textByLanguage[language.target]
} ?: text
val centerY get() = height / 2 + y
val centerX get() = width / 2 + x
fun getTextBy(language: Language) = textByLanguage[language.target] ?: text
val width get() = x2 - x1
val height get() = y2 - y1
val centerY get() = (y2 + y1) / 2f
val centerX get() = (x2 + x1) / 2f
val foregroundColor: Int get() {
val color = fbColor.takeIf { it.isNotEmpty() }
?: return Color.BLACK
return Color.rgb(color[0], color[1], color[2])
}
val backgroundColor: Int get() {
val color = bgColor.takeIf { it.isNotEmpty() }
?: return Color.WHITE
return Color.rgb(color[0], color[1], color[2])
}
}
private object DialogListSerializer :
@ -59,11 +72,24 @@ private object DialogListSerializer :
val textByLanguage = getDialogs(jsonElement)
buildJsonObject {
put("x", coordinates[0])
put("y", coordinates[1])
put("_width", coordinates[2])
put("_height", coordinates[3])
put("x1", coordinates[0])
put("y1", coordinates[1])
put("x2", coordinates[2])
put("y2", coordinates[3])
put("textByLanguage", textByLanguage)
if (jsonElement.isArray) {
return@buildJsonObject
}
jsonElement.jsonObject.let { obj ->
obj["fg_color"]?.let { put("fbColor", it) }
obj["bg_color"]?.let { put("bgColor", it) }
obj["angle"]?.let { put("angle", it) }
obj["type"]?.let { put("type", it) }
obj["is_bold"]?.let { put("isBold", it) }
put("isNewApi", true)
}
}
},
)
@ -72,7 +98,7 @@ private object DialogListSerializer :
private fun getCoordinates(element: JsonElement): JsonArray {
return when (element) {
is JsonArray -> element.jsonArray[0].jsonArray
else -> element.jsonObject["box"]?.jsonArray
else -> element.jsonObject["bbox"]?.jsonArray
?: throw IOException("Dialog box position not found")
}
}

View File

@ -0,0 +1,19 @@
package eu.kanade.tachiyomi.multisrc.machinetranslations
class MachineTranslationsFactoryUtils
interface Language {
val lang: String
val target: String
val origin: String
var fontSize: Int
var disableSourceSettings: Boolean
}
data class LanguageImpl(
override val lang: String,
override val target: String = lang,
override val origin: String = "en",
override var fontSize: Int = 24,
override var disableSourceSettings: Boolean = false,
) : Language

View File

@ -0,0 +1,59 @@
package eu.kanade.tachiyomi.multisrc.machinetranslations
import eu.kanade.tachiyomi.source.model.Filter
class SelectionList(displayName: String, private val vals: List<Option>, state: Int = 0) :
Filter.Select<String>(displayName, vals.map { it.name }.toTypedArray(), state) {
fun selected() = vals[state]
}
data class Option(val name: String = "", val value: String = "", val query: String = "")
class GenreList(title: String, genres: List<Genre>) :
Filter.Group<GenreCheckBox>(title, genres.map { GenreCheckBox(it.name, it.id) })
class GenreCheckBox(name: String, val id: String = name) : Filter.CheckBox(name)
class Genre(val name: String, val id: String = name)
val genreList: List<Genre> = listOf(
Genre("Action"),
Genre("Adult"),
Genre("Adventure"),
Genre("Comedy"),
Genre("Drama"),
Genre("Ecchi"),
Genre("Fantasy"),
Genre("Gender Bender"),
Genre("Harem"),
Genre("Historical"),
Genre("Horror"),
Genre("Josei"),
Genre("Lolicon"),
Genre("Martial Arts"),
Genre("Mature"),
Genre("Mecha"),
Genre("Mystery"),
Genre("Psychological"),
Genre("Romance"),
Genre("School Life"),
Genre("Sci-fi"),
Genre("Seinen"),
Genre("Shoujo"),
Genre("Shoujo Ai"),
Genre("Shounen"),
Genre("Shounen Ai"),
Genre("Slice of Life"),
Genre("Smut"),
Genre("Sports"),
Genre("Supernatural"),
Genre("Tragedy"),
Genre("Yaoi"),
Genre("Yuri"),
)
val sortByList = listOf(
Option("All"),
Option("Most Views", "views"),
Option("Most Recent", "recent"),
).map { it.copy(query = "sort_by") }

View File

@ -1,24 +1,26 @@
package eu.kanade.tachiyomi.extension.tr.eldermanga
package eu.kanade.tachiyomi.multisrc.machinetranslations
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.annotation.RequiresApi
import kotlin.system.exitProcess
class ElderMangaUrlActivity : Activity() {
@RequiresApi(Build.VERSION_CODES.O)
class MachineTranslationsUrlActivity : Activity() {
private val tag = javaClass.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 2) {
val item = "${pathSegments[1]}/${pathSegments[2]}"
if (pathSegments != null && pathSegments.size > 1) {
val item = pathSegments[1]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${ElderManga.URL_SEARCH_PREFIX}$item")
putExtra("query", "${MachineTranslations.PREFIX_SEARCH}$item")
putExtra("filter", packageName)
}

View File

@ -1,4 +1,4 @@
package eu.kanade.tachiyomi.extension.all.manhuarm.interceptors
package eu.kanade.tachiyomi.multisrc.machinetranslations.interceptors
import android.graphics.Bitmap
import android.graphics.BitmapFactory
@ -12,14 +12,17 @@ import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import androidx.annotation.RequiresApi
import eu.kanade.tachiyomi.extension.all.manhuarm.Dialog
import eu.kanade.tachiyomi.extension.all.manhuarm.Language
import eu.kanade.tachiyomi.extension.all.manhuarm.Manhuarm.Companion.PAGE_REGEX
import keiyoushi.utils.parseAs
import eu.kanade.tachiyomi.multisrc.machinetranslations.Dialog
import eu.kanade.tachiyomi.multisrc.machinetranslations.Language
import eu.kanade.tachiyomi.multisrc.machinetranslations.MachineTranslations.Companion.PAGE_REGEX
import eu.kanade.tachiyomi.network.GET
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import uy.kohesive.injekt.injectLazy
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
@ -28,9 +31,18 @@ import java.io.InputStream
// The Interceptor joins the dialogues and pages of the manga.
@RequiresApi(Build.VERSION_CODES.O)
class ComposedImageInterceptor(
val language: Language,
baseUrl: String,
var language: Language,
) : Interceptor {
private val json: Json by injectLazy()
private val fontFamily: MutableMap<String, Pair<String, Typeface?>> = mutableMapOf(
"sub" to Pair<String, Typeface?>("$baseUrl/images/sub.ttf", null),
"sfx" to Pair<String, Typeface?>("$baseUrl/images/sfx.ttf", null),
"normal" to Pair<String, Typeface?>("$baseUrl/images/normal.ttf", null),
)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val url = request.url.toString()
@ -46,6 +58,12 @@ class ComposedImageInterceptor(
.url(url)
.build()
// Load the fonts before opening the connection to load the image,
// so there aren't two open connections inside the interceptor.
if (language.disableSourceSettings.not()) {
loadAllFont(chain)
}
val response = chain.proceed(imageRequest)
if (response.isSuccessful.not()) {
@ -58,11 +76,10 @@ class ComposedImageInterceptor(
val canvas = Canvas(bitmap)
dialogues.forEach { dialog ->
dialog.scale = language.dialogBoxScale
val textPaint = createTextPaint(selectFontFamily())
val textPaint = createTextPaint(selectFontFamily(dialog.type))
val dialogBox = createDialogBox(dialog, textPaint)
val y = getYAxis(textPaint, dialog, dialogBox)
canvas.draw(textPaint, dialogBox, dialog, dialog.x, y)
canvas.draw(textPaint, dialogBox, dialog, dialog.x1, y)
}
val output = ByteArrayOutputStream()
@ -97,11 +114,30 @@ class ComposedImageInterceptor(
}
}
private fun selectFontFamily(): Typeface? {
if (language.disableFontSettings) {
private fun selectFontFamily(type: String): Typeface? {
if (language.disableSourceSettings) {
return null
}
return loadFont("${language.fontName}.ttf")
if (type in fontFamily) {
return fontFamily[type]?.second
}
return when (type) {
"inside", "outside" -> fontFamily["sfx"]?.second
else -> fontFamily["normal"]?.second
}
}
private fun loadAllFont(chain: Interceptor.Chain) {
val fallback = loadFont("coming_soon_regular.ttf")
fontFamily.keys.forEach { key ->
val font = fontFamily[key] ?: return@forEach
if (font.second != null) {
return@forEach
}
fontFamily[key] = key to (loadRemoteFont(font.first, chain) ?: fallback)
}
}
/**
@ -125,6 +161,31 @@ class ComposedImageInterceptor(
}
}
/**
* Loads a remote font and converts it into a usable font object.
*
* This function makes an HTTP request to download a font from a specified remote URL.
* It then converts the response into a usable font object.
*/
private fun loadRemoteFont(fontUrl: String, chain: Interceptor.Chain): Typeface? {
return try {
val request = GET(fontUrl, chain.request().headers)
val response = chain.proceed(request)
if (response.isSuccessful.not()) {
response.close()
return null
}
val fontName = request.url.pathSegments.last()
response.body.use {
it.byteStream().toTypeface(fontName)
}
} catch (e: Exception) {
null
}
}
private fun InputStream.toTypeface(fontName: String): Typeface? {
val fontFile = File.createTempFile(fontName, fontName.substringAfter("."))
this.copyTo(FileOutputStream(fontFile))
@ -144,7 +205,7 @@ class ComposedImageInterceptor(
*/
return when {
dialogBox.lineCount < dialogBoxLineCount -> dialog.centerY - dialogBox.lineCount / 2f * fontHeight
else -> dialog.y
else -> dialog.y1
}
}
@ -170,19 +231,18 @@ class ComposedImageInterceptor(
return StaticLayout.Builder.obtain(text, 0, text.length, textPaint, dialog.width.toInt()).apply {
setAlignment(Layout.Alignment.ALIGN_CENTER)
setIncludePad(language.disableFontSettings)
setIncludePad(false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (language.disableWordBreak) {
setBreakStrategy(LineBreaker.BREAK_STRATEGY_SIMPLE)
setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NONE)
return@apply
}
setBreakStrategy(LineBreaker.BREAK_STRATEGY_BALANCED)
setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_FULL)
}
}.build()
}
private inline fun <reified T> String.parseAs(): T {
return json.decodeFromString(this)
}
private fun Canvas.draw(textPaint: TextPaint, layout: StaticLayout, dialog: Dialog, x: Float, y: Float) {
save()
translate(x, y)

View File

@ -2,7 +2,7 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 44
baseVersionCode = 42
dependencies {
api(project(":lib:cryptoaes"))

View File

@ -163,7 +163,6 @@ abstract class Madara(
override fun popularMangaSelector() = "div.page-item-detail:not(:has(a[href*='bilibilicomics.com']))$mangaEntrySelector , .manga__item"
open val popularMangaUrlSelector = "div.post-title a"
open val popularMangaUrlSelectorImg = "img"
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
@ -174,7 +173,7 @@ abstract class Madara(
manga.title = it.ownText()
}
selectFirst(popularMangaUrlSelectorImg)?.let {
selectFirst("img")?.let {
manga.thumbnail_url = imageFromElement(it)
}
}
@ -702,11 +701,12 @@ abstract class Madara(
}
}
val genres = select(mangaDetailsSelectorGenre)
.mapTo(ArrayList()) { element -> element.text() }
.map { element -> element.text().lowercase(Locale.ROOT) }
.toMutableSet()
if (mangaDetailsSelectorTag.isNotEmpty()) {
select(mangaDetailsSelectorTag).forEach { element ->
if (
if (genres.contains(element.text()).not() &&
element.text().length <= 25 &&
element.text().contains("read", true).not() &&
element.text().contains(name, true).not() &&
@ -714,19 +714,29 @@ abstract class Madara(
element.text().contains(manga.title, true).not() &&
element.text().contains(altName, true).not()
) {
genres.add(element.text())
genres.add(element.text().lowercase(Locale.ROOT))
}
}
}
// add manga/manhwa/manhua thinggy to genre
document.selectFirst(seriesTypeSelector)?.ownText()?.let {
if (it.isEmpty().not() && it.notUpdating() && it != "-") {
genres.add(it)
if (it.isEmpty().not() && it.notUpdating() && it != "-" && genres.contains(it).not()) {
genres.add(it.lowercase(Locale.ROOT))
}
}
manga.genre = genres.distinctBy(String::lowercase).joinToString()
manga.genre = genres.toList().joinToString { genre ->
genre.replaceFirstChar {
if (it.isLowerCase()) {
it.titlecase(
Locale.ROOT,
)
} else {
it.toString()
}
}
}
// add alternative name to manga description
document.selectFirst(altNameSelector)?.ownText()?.let {
@ -778,7 +788,7 @@ abstract class Madara(
/**
* Get the best image quality available from srcset
*/
protected open fun String.getSrcSetImage(): String? {
protected fun String.getSrcSetImage(): String? {
return this.split(" ")
.filter(URL_REGEX::matches)
.maxOfOrNull(String::toString)
@ -950,11 +960,11 @@ abstract class Madara(
return when {
WordSet("hari", "gün", "jour", "día", "dia", "day", "วัน", "ngày", "giorni", "أيام", "").anyWordIn(date) -> cal.apply { add(Calendar.DAY_OF_MONTH, -number) }.timeInMillis
WordSet("jam", "saat", "heure", "hora", "hour", "ชั่วโมง", "giờ", "ore", "ساعة", "小时").anyWordIn(date) -> cal.apply { add(Calendar.HOUR, -number) }.timeInMillis
WordSet("menit", "dakika", "min", "minute", "minuto", "นาที", "دقائق", "phút").anyWordIn(date) -> cal.apply { add(Calendar.MINUTE, -number) }.timeInMillis
WordSet("detik", "segundo", "second", "วินาที", "giây").anyWordIn(date) -> cal.apply { add(Calendar.SECOND, -number) }.timeInMillis
WordSet("week", "semana", "tuần").anyWordIn(date) -> cal.apply { add(Calendar.DAY_OF_MONTH, -number * 7) }.timeInMillis
WordSet("month", "mes", "tháng").anyWordIn(date) -> cal.apply { add(Calendar.MONTH, -number) }.timeInMillis
WordSet("year", "año", "năm").anyWordIn(date) -> cal.apply { add(Calendar.YEAR, -number) }.timeInMillis
WordSet("menit", "dakika", "min", "minute", "minuto", "นาที", "دقائق").anyWordIn(date) -> cal.apply { add(Calendar.MINUTE, -number) }.timeInMillis
WordSet("detik", "segundo", "second", "วินาที").anyWordIn(date) -> cal.apply { add(Calendar.SECOND, -number) }.timeInMillis
WordSet("week", "semana").anyWordIn(date) -> cal.apply { add(Calendar.DAY_OF_MONTH, -number * 7) }.timeInMillis
WordSet("month", "mes").anyWordIn(date) -> cal.apply { add(Calendar.MONTH, -number) }.timeInMillis
WordSet("year", "año").anyWordIn(date) -> cal.apply { add(Calendar.YEAR, -number) }.timeInMillis
else -> 0
}
}

View File

@ -2,4 +2,4 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 8
baseVersionCode = 7

View File

@ -155,7 +155,7 @@ abstract class MangaBox(
open val simpleQueryPath = "search/story/"
override fun popularMangaSelector() = "div.truyen-list > div.list-truyen-item-wrap, div.comic-list > .list-comic-item-wrap"
override fun popularMangaSelector() = "div.truyen-list > div.list-truyen-item-wrap"
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/$popularUrlPath$page", headers)
@ -211,7 +211,7 @@ abstract class MangaBox(
}
}
override fun searchMangaSelector() = ".panel_story_list .story_item, div.list-truyen-item-wrap, .list-comic-item-wrap .list-story-item"
override fun searchMangaSelector() = ".panel_story_list .story_item, div.list-truyen-item-wrap"
override fun searchMangaFromElement(element: Element) = mangaFromElement(element)

View File

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

View File

@ -96,6 +96,7 @@ abstract class MangaCatalog(
name = "$name1 - $name2"
}
url = element.select(".col-span-4 > a").attr("abs:href")
date_upload = System.currentTimeMillis()
}
// Pages

View File

@ -2,7 +2,7 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 3
baseVersionCode = 1
dependencies {
api(project(":lib:i18n"))

View File

@ -113,11 +113,12 @@ abstract class ManhwaZ(
override fun searchMangaNextPageSelector(): String? = latestUpdatesNextPageSelector()
private val ongoingStatusList = listOf("ongoing", "đang ra")
private val completedStatusList = listOf("completed", "hoàn thành", "Truyện Full")
private val completedStatusList = listOf("completed", "hoàn thành")
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
val statusText = document.selectFirst("div.summary-heading:contains($mangaDetailsStatusHeading) + div.summary-content")
?.text()
?.lowercase()
?: ""
title = document.selectFirst("div.post-title h1")!!.text()
@ -125,8 +126,8 @@ abstract class ManhwaZ(
description = document.selectFirst("div.summary__content")?.text()
genre = document.select("div.genres-content a[rel=tag]").joinToString { it.text() }
status = when {
ongoingStatusList.any { it.contains(statusText, ignoreCase = true) } -> SManga.ONGOING
completedStatusList.any { it.contains(statusText, ignoreCase = true) } -> SManga.COMPLETED
ongoingStatusList.contains(statusText) -> SManga.ONGOING
completedStatusList.contains(statusText) -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
thumbnail_url = document.selectFirst("div.summary_image img")?.imgAttr()

View File

@ -2,7 +2,7 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 2
baseVersionCode = 1
dependencies {
implementation(project(":lib:unpacker"))

View File

@ -95,10 +95,10 @@ open class MMLook(
override fun searchMangaParse(response: Response): MangasPage {
if (response.request.method == "GET") return popularMangaParse(response)
val entries = response.asJsoup().select(".item-data > div").map { element ->
val entries = response.asJsoup().select(".col-auto").map { element ->
SManga.create().apply {
url = element.selectFirst("a")!!.attr("href").mustRemoveSurrounding("/", "/")
title = element.selectFirst(".e-title, .title")!!.text()
title = element.selectFirst(".e-title")!!.text()
author = element.selectFirst(".tip")!!.text()
thumbnail_url = element.selectFirst("img")!!.attr("data-src")
}.formatUrl()

View File

@ -2,4 +2,4 @@ plugins {
id("lib-multisrc")
}
baseVersionCode = 11
baseVersionCode = 10

View File

@ -154,7 +154,6 @@ abstract class ZeistManga(
protected open val mangaDetailsSelectorAuthor = "span#author"
protected open val mangaDetailsSelectorArtist = "span#artist"
protected open val mangaDetailsSelectorAltName = "header > p"
protected open val mangaDetailsSelectorStatus = "span[data-status]"
protected open val mangaDetailsSelectorInfo = ".y6x11p"
protected open val mangaDetailsSelectorInfoTitle = "strong"
protected open val mangaDetailsSelectorInfoDescription = "span.dt"
@ -176,7 +175,6 @@ abstract class ZeistManga(
.joinToString { it.text() }
author = profileManga.selectFirst(mangaDetailsSelectorAuthor)?.text()
artist = profileManga.selectFirst(mangaDetailsSelectorArtist)?.text()
status = parseStatus(profileManga.selectFirst(mangaDetailsSelectorStatus)?.text() ?: "")
val infoElement = profileManga.select(mangaDetailsSelectorInfo)
infoElement.forEach { element ->

View File

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

View File

@ -1,19 +1,16 @@
package eu.kanade.tachiyomi.multisrc.zerotheme
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.interceptor.rateLimit
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.asJsoup
import keiyoushi.utils.parseAs
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Element
import java.io.IOException
abstract class ZeroTheme(
override val name: String,
@ -23,26 +20,15 @@ abstract class ZeroTheme(
override val supportsLatest: Boolean = true
override val client = network.cloudflareClient
override val client = network.cloudflareClient.newBuilder()
.rateLimit(2)
.build()
open val cdnUrl: String = "https://cdn.${baseUrl.substringAfterLast("/")}"
open val imageLocation: String = "/images"
open val imageLocation: String = "images"
open val mangaSubString: String by lazy {
val response = client.newCall(GET(baseUrl, headers)).execute()
val script = response.asJsoup().select("script")
.map(Element::data)
.firstOrNull(MANGA_SUBSTRING_REGEX::containsMatchIn)
?: throw IOException("manga substring não foi localizado")
MANGA_SUBSTRING_REGEX.find(script)?.groups?.get(1)?.value
?: throw IOException("Não foi extrair a substring do manga")
}
open val chapterSubString: String = "chapter"
open val sourceLocation: String get() = "$cdnUrl$imageLocation"
private val sourceLocation: String get() = "$cdnUrl/$imageLocation"
// =========================== Popular ================================
@ -75,30 +61,14 @@ abstract class ZeroTheme(
// =========================== Details =================================
override fun getMangaUrl(manga: SManga) = "$baseUrl/$mangaSubString/${manga.url.substringAfterLast("/")}"
override fun mangaDetailsRequest(manga: SManga): Request {
checkEntry(manga.url)
return GET(getMangaUrl(manga), headers)
}
override fun mangaDetailsParse(response: Response) = response.toDto<MangaDetailsDto>().toSManga(sourceLocation)
// =========================== Chapter =================================
override fun getChapterUrl(chapter: SChapter) = "$baseUrl/$chapterSubString/${chapter.url.substringAfterLast("/")}"
override fun chapterListRequest(manga: SManga) = mangaDetailsRequest(manga)
override fun chapterListParse(response: Response) = response.toDto<MangaDetailsDto>().toSChapterList()
// =========================== Pages ===================================
override fun pageListRequest(chapter: SChapter): Request {
checkEntry(chapter.url)
return GET(getChapterUrl(chapter), headers)
}
override fun pageListParse(response: Response): List<Page> =
response.toDto<PageDto>().toPageList(sourceLocation)
@ -106,18 +76,8 @@ abstract class ZeroTheme(
// =========================== Utilities ===============================
private fun checkEntry(url: String) {
if (listOf(mangaSubString, chapterSubString).any(url::contains)) {
throw IOException("Migre a obra para extensão $name")
}
}
inline fun <reified T> Response.toDto(): T {
val jsonString = asJsoup().selectFirst("[data-page]")!!.attr("data-page")
return jsonString.parseAs<T>()
}
companion object {
val MANGA_SUBSTRING_REGEX = """"(\w+)\\/\{slug\}""".toRegex()
}
}

View File

@ -108,7 +108,7 @@ class MangaDto(
else -> SManga.UNKNOWN
}
genre = genres?.joinToString { it.name }
url = slug
url = "/comic/$slug"
}
@Serializable
@ -130,7 +130,7 @@ class ChapterDto(
name = number.toString()
chapter_number = number
date_upload = dateFormat.tryParse(createdAt)
url = path
url = "/chapter/$path"
}
companion object {

View File

@ -1,7 +1,7 @@
ext {
extName = 'Bato.to'
extClass = '.BatoToFactory'
extVersionCode = 53
extVersionCode = 50
isNsfw = true
}

View File

@ -43,7 +43,6 @@ import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import kotlin.random.Random
open class BatoTo(
final override val lang: String,
@ -53,17 +52,7 @@ open class BatoTo(
private val preferences by getPreferencesLazy { migrateMirrorPref() }
override val name: String = "Bato.to"
override var baseUrl: String = ""
get() {
val current = field
if (current.isNotEmpty()) {
return current
}
field = getMirrorPref()
return field
}
override val baseUrl: String get() = mirror
override val id: Long = when (lang) {
"zh-Hans" -> 2818874445640189582
"zh-Hant" -> 38886079663327225
@ -80,7 +69,7 @@ open class BatoTo(
setDefaultValue(MIRROR_PREF_DEFAULT_VALUE)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
baseUrl = newValue as String
mirror = newValue as String
true
}
}
@ -104,19 +93,20 @@ open class BatoTo(
screen.addPreference(removeOfficialPref)
}
private fun getMirrorPref(): String {
if (System.getenv("CI") == "true") {
return (MIRROR_PREF_ENTRY_VALUES.drop(1) + DEPRECATED_MIRRORS).joinToString("#, ")
private var mirror = ""
get() {
val current = field
if (current.isNotEmpty()) {
return current
}
field = getMirrorPref()
return field
}
private fun getMirrorPref(): String {
return preferences.getString("${MIRROR_PREF_KEY}_$lang", MIRROR_PREF_DEFAULT_VALUE)
?.takeUnless { it == MIRROR_PREF_DEFAULT_VALUE }
?: let {
/* Semi-sticky mirror:
* - Don't randomize on boot
* - Don't randomize per language
* - Fallback for non-Android platform
*/
val seed = runCatching {
val pm = Injekt.get<Application>().packageManager
pm.getPackageInfo(BuildConfig.APPLICATION_ID, 0).lastUpdateTime
@ -124,7 +114,7 @@ open class BatoTo(
BuildConfig.VERSION_NAME.hashCode().toLong()
}
MIRROR_PREF_ENTRY_VALUES.drop(1).random(Random(seed))
MIRROR_PREF_ENTRY_VALUES[1 + (seed % (MIRROR_PREF_ENTRIES.size - 1)).toInt()]
}
}

View File

@ -1,7 +1,7 @@
ext {
extName = 'Buon Dua'
extClass = '.BuonDua'
extVersionCode = 6
extVersionCode = 4
isNsfw = true
}

View File

@ -93,12 +93,7 @@ class BuonDua() : ParsedHttpSource() {
val doc = response.asJsoup()
val dateUploadStr = doc.selectFirst(".article-info > small")?.text()
val dateUpload = DATE_FORMAT.tryParse(dateUploadStr)
// /xiuren-no-10051---10065-1127-photos-467c89d5b3e204eebe33ddbc54d905b1-47452?page=57
val maxPage = doc.select("nav.pagination:first-of-type a.pagination-next").last()
?.absUrl("href")
?.takeIf { it.startsWith("http") }
?.toHttpUrl()
?.queryParameter("page")?.toInt() ?: 1
val maxPage = doc.select("nav.pagination:first-of-type a.pagination-link").last()?.text()?.toInt() ?: 1
val basePageUrl = response.request.url
return (maxPage downTo 1).map { page ->
SChapter.create().apply {

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity
android:name=".all.comickfun.ComickUrlActivity"
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:scheme="https" />
<data android:host="comick.io" />
<data android:host="comick.cc" />
<data android:host="comick.ink" />
<data android:host="comick.app" />
<data android:host="comick.fun" />
<data android:pathPattern="/comic/.*/..*" />
<data android:pathPattern="/comic/..*" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -0,0 +1,27 @@
ignored_groups_title=Ignored Groups
ignored_groups_summary=Chapters from these groups won't be shown.\nOne group name per line (case-insensitive)
ignored_tags_title=Ignored Tags
ignored_tags_summary=Manga with these tags won't show up when browsing.\nOne tag per line (case-insensitive)
show_alternative_titles_title=Show Alternative Titles
show_alternative_titles_on=Adds alternative titles to the description
show_alternative_titles_off=Does not show alternative titles to the description
include_tags_title=Include Tags
include_tags_on=More specific, but might contain spoilers!
include_tags_off=Only the broader genres
group_tags_title=Group Tags (fork must support grouping)
group_tags_on=Will prefix tags with their type
group_tags_off=List all tags together
update_cover_title=Update Covers
update_cover_on=Keep cover updated
update_cover_off=Prefer first cover
local_title_title=Translated Title
local_title_on=if available
local_title_off=Use the default title from the site
score_position_title=Score Position in the Description
score_position_top=Top
score_position_middle=Middle
score_position_bottom=Bottom
score_position_none=Hide Score
chapter_score_filtering_title=Automatically de-duplicate chapters
chapter_score_filtering_on=For each chapter, only displays the scanlator with the highest score
chapter_score_filtering_off=Does not filterout any chapters based on score (any other scanlator filtering will still apply)

View File

@ -0,0 +1,22 @@
ignored_groups_title=Grupos Ignorados
ignored_groups_summary=Capítulos desses grupos não aparecerão.\nUm grupo por linha
show_alternative_titles_title=Mostrar Títulos Alternativos
show_alternative_titles_on=Adiciona títulos alternativos à descrição
show_alternative_titles_off=Não mostra títulos alternativos na descrição
include_tags_title=Incluir Tags
include_tags_on=Mais detalhadas, mas podem conter spoilers
include_tags_off=Apenas os gêneros básicos
group_tags_title=Agrupar Tags (necessário fork compatível)
group_tags_on=Prefixar tags com o respectivo tipo
group_tags_off=Listar todas as tags juntas
update_cover_title=Atualizar Capas
update_cover_on=Manter capas atualizadas
update_cover_off=Usar apenas a primeira capa
local_title_title=Título Traduzido
local_title_on=se disponível
local_title_off=Usar o título padrão do site
score_position_title=Posição da Nota na Descrição
score_position_top=Topo
score_position_middle=Meio
score_position_bottom=Final
score_position_none=Sem Nota

View File

@ -0,0 +1,12 @@
ext {
extName = 'Comick'
extClass = '.ComickFactory'
extVersionCode = 57
isNsfw = true
}
apply from: "$rootDir/common.gradle"
dependencies {
implementation(project(":lib:i18n"))
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1,661 @@
package eu.kanade.tachiyomi.extension.all.comickfun
import android.content.SharedPreferences
import androidx.preference.EditTextPreference
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreferenceCompat
import eu.kanade.tachiyomi.lib.i18n.Intl
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.network.interceptor.rateLimit
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import keiyoushi.utils.getPreferencesLazy
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Headers
import okhttp3.HttpUrl.Builder
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
import java.util.concurrent.TimeUnit
import kotlin.math.min
abstract class Comick(
override val lang: String,
private val comickLang: String,
) : ConfigurableSource, HttpSource() {
override val name = "Comick"
override val baseUrl = "https://comick.io"
private val apiUrl = "https://api.comick.fun"
override val supportsLatest = true
private val json = Json {
ignoreUnknownKeys = true
isLenient = true
coerceInputValues = true
explicitNulls = true
}
private lateinit var searchResponse: List<SearchManga>
private val intl by lazy {
Intl(
language = lang,
baseLanguage = "en",
availableLanguages = setOf("en", "pt-BR"),
classLoader = this::class.java.classLoader!!,
)
}
private val preferences by getPreferencesLazy { newLineIgnoredGroups() }
override fun setupPreferenceScreen(screen: PreferenceScreen) {
EditTextPreference(screen.context).apply {
key = IGNORED_GROUPS_PREF
title = intl["ignored_groups_title"]
summary = intl["ignored_groups_summary"]
setOnPreferenceChangeListener { _, newValue ->
preferences.edit()
.putString(IGNORED_GROUPS_PREF, newValue.toString())
.commit()
}
}.also(screen::addPreference)
EditTextPreference(screen.context).apply {
key = IGNORED_TAGS_PREF
title = intl["ignored_tags_title"]
summary = intl["ignored_tags_summary"]
}.also(screen::addPreference)
SwitchPreferenceCompat(screen.context).apply {
key = SHOW_ALTERNATIVE_TITLES_PREF
title = intl["show_alternative_titles_title"]
summaryOn = intl["show_alternative_titles_on"]
summaryOff = intl["show_alternative_titles_off"]
setDefaultValue(SHOW_ALTERNATIVE_TITLES_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
preferences.edit()
.putBoolean(SHOW_ALTERNATIVE_TITLES_PREF, newValue as Boolean)
.commit()
}
}.also(screen::addPreference)
SwitchPreferenceCompat(screen.context).apply {
key = INCLUDE_MU_TAGS_PREF
title = intl["include_tags_title"]
summaryOn = intl["include_tags_on"]
summaryOff = intl["include_tags_off"]
setDefaultValue(INCLUDE_MU_TAGS_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
preferences.edit()
.putBoolean(INCLUDE_MU_TAGS_PREF, newValue as Boolean)
.commit()
}
}.also(screen::addPreference)
SwitchPreferenceCompat(screen.context).apply {
key = GROUP_TAGS_PREF
title = intl["group_tags_title"]
summaryOn = intl["group_tags_on"]
summaryOff = intl["group_tags_off"]
setDefaultValue(GROUP_TAGS_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
preferences.edit()
.putBoolean(GROUP_TAGS_PREF, newValue as Boolean)
.commit()
}
}.also(screen::addPreference)
SwitchPreferenceCompat(screen.context).apply {
key = FIRST_COVER_PREF
title = intl["update_cover_title"]
summaryOff = intl["update_cover_off"]
summaryOn = intl["update_cover_on"]
setDefaultValue(FIRST_COVER_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
preferences.edit()
.putBoolean(FIRST_COVER_PREF, newValue as Boolean)
.commit()
}
}.also(screen::addPreference)
SwitchPreferenceCompat(screen.context).apply {
key = LOCAL_TITLE_PREF
title = intl["local_title_title"]
summaryOff = intl["local_title_off"]
summaryOn = intl["local_title_on"]
setDefaultValue(LOCAL_TITLE_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
preferences.edit()
.putBoolean(LOCAL_TITLE_PREF, newValue as Boolean)
.commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = SCORE_POSITION_PREF
title = intl["score_position_title"]
summary = "%s"
entries = arrayOf(
intl["score_position_top"],
intl["score_position_middle"],
intl["score_position_bottom"],
intl["score_position_none"],
)
entryValues = arrayOf(SCORE_POSITION_DEFAULT, "middle", "bottom", "none")
setDefaultValue(SCORE_POSITION_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit()
.putString(SCORE_POSITION_PREF, entry)
.commit()
}
}.also(screen::addPreference)
SwitchPreferenceCompat(screen.context).apply {
key = CHAPTER_SCORE_FILTERING_PREF
title = intl["chapter_score_filtering_title"]
summaryOff = intl["chapter_score_filtering_off"]
summaryOn = intl["chapter_score_filtering_on"]
setDefaultValue(CHAPTER_SCORE_FILTERING_DEFAULT)
setOnPreferenceChangeListener { _, newValue ->
preferences.edit()
.putBoolean(CHAPTER_SCORE_FILTERING_PREF, newValue as Boolean)
.commit()
}
}.also(screen::addPreference)
}
private val SharedPreferences.ignoredGroups: Set<String>
get() = getString(IGNORED_GROUPS_PREF, "")
?.lowercase()
?.split("\n")
?.map(String::trim)
?.filter(String::isNotEmpty)
?.sorted()
.orEmpty()
.toSet()
private val SharedPreferences.ignoredTags: String
get() = getString(IGNORED_TAGS_PREF, "")
?.split("\n")
?.map(String::trim)
?.filter(String::isNotEmpty)
.orEmpty()
.joinToString(",")
private val SharedPreferences.showAlternativeTitles: Boolean
get() = getBoolean(SHOW_ALTERNATIVE_TITLES_PREF, SHOW_ALTERNATIVE_TITLES_DEFAULT)
private val SharedPreferences.includeMuTags: Boolean
get() = getBoolean(INCLUDE_MU_TAGS_PREF, INCLUDE_MU_TAGS_DEFAULT)
private val SharedPreferences.groupTags: Boolean
get() = getBoolean(GROUP_TAGS_PREF, GROUP_TAGS_DEFAULT)
private val SharedPreferences.updateCover: Boolean
get() = getBoolean(FIRST_COVER_PREF, FIRST_COVER_DEFAULT)
private val SharedPreferences.localTitle: String
get() = if (getBoolean(
LOCAL_TITLE_PREF,
LOCAL_TITLE_DEFAULT,
)
) {
comickLang.lowercase()
} else {
"all"
}
private val SharedPreferences.scorePosition: String
get() = getString(SCORE_POSITION_PREF, SCORE_POSITION_DEFAULT) ?: SCORE_POSITION_DEFAULT
private val SharedPreferences.chapterScoreFiltering: Boolean
get() = getBoolean(CHAPTER_SCORE_FILTERING_PREF, CHAPTER_SCORE_FILTERING_DEFAULT)
override fun headersBuilder() = Headers.Builder().apply {
add("Referer", "$baseUrl/")
add("User-Agent", "Tachiyomi ${System.getProperty("http.agent")}")
}
override val client = network.cloudflareClient.newBuilder()
.addNetworkInterceptor(::errorInterceptor)
.rateLimit(3, 1, TimeUnit.SECONDS)
.build()
private fun errorInterceptor(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
if (
response.isSuccessful ||
"application/json" !in response.header("Content-Type").orEmpty()
) {
return response
}
val error = try {
response.parseAs<Error>()
} catch (_: Exception) {
null
}
error?.run {
throw Exception("$name error $statusCode: $message")
} ?: throw Exception("HTTP error ${response.code}")
}
/** Popular Manga **/
override fun popularMangaRequest(page: Int): Request {
return searchMangaRequest(
page = page,
query = "",
filters = FilterList(
SortFilter("follow"),
),
)
}
override fun popularMangaParse(response: Response): MangasPage {
val result = response.parseAs<List<SearchManga>>()
return MangasPage(
result.map(SearchManga::toSManga),
hasNextPage = result.size >= LIMIT,
)
}
/** Latest Manga **/
override fun latestUpdatesRequest(page: Int): Request {
return searchMangaRequest(
page = page,
query = "",
filters = FilterList(
SortFilter("uploaded"),
),
)
}
override fun latestUpdatesParse(response: Response) = popularMangaParse(response)
/** Manga Search **/
override fun fetchSearchManga(
page: Int,
query: String,
filters: FilterList,
): Observable<MangasPage> {
return if (query.startsWith(SLUG_SEARCH_PREFIX)) {
// url deep link
val slugOrHid = query.substringAfter(SLUG_SEARCH_PREFIX)
val manga = SManga.create().apply { this.url = "/comic/$slugOrHid#" }
fetchMangaDetails(manga).map {
MangasPage(listOf(it), false)
}
} else if (query.isEmpty()) {
// regular filtering without text search
client.newCall(searchMangaRequest(page, query, filters))
.asObservableSuccess()
.map(::searchMangaParse)
} else {
// text search, no pagination in api
if (page == 1) {
client.newCall(querySearchRequest(query))
.asObservableSuccess()
.map(::querySearchParse)
} else {
Observable.just(paginatedSearchPage(page))
}
}
}
private fun querySearchRequest(query: String): Request {
val url = "$apiUrl/v1.0/search?limit=300&page=1&tachiyomi=true"
.toHttpUrl().newBuilder()
.addQueryParameter("q", query.trim())
.build()
return GET(url, headers)
}
private fun querySearchParse(response: Response): MangasPage {
searchResponse = response.parseAs()
return paginatedSearchPage(1)
}
private fun paginatedSearchPage(page: Int): MangasPage {
val end = min(page * LIMIT, searchResponse.size)
val entries = searchResponse.subList((page - 1) * LIMIT, end)
.map(SearchManga::toSManga)
return MangasPage(entries, end < searchResponse.size)
}
private fun addTagQueryParameters(builder: Builder, tags: String, parameterName: String) {
tags.split(",").filter(String::isNotEmpty).forEach {
builder.addQueryParameter(
parameterName,
it.trim().lowercase().replace(SPACE_AND_SLASH_REGEX, "-")
.replace("'-", "-and-039-").replace("'", "-and-039-"),
)
}
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$apiUrl/v1.0/search".toHttpUrl().newBuilder().apply {
filters.forEach { it ->
when (it) {
is CompletedFilter -> {
if (it.state) {
addQueryParameter("completed", "true")
}
}
is GenreFilter -> {
it.state.filter { it.isIncluded() }.forEach {
addQueryParameter("genres", it.value)
}
it.state.filter { it.isExcluded() }.forEach {
addQueryParameter("excludes", it.value)
}
}
is DemographicFilter -> {
it.state.filter { it.state }.forEach {
addQueryParameter("demographic", it.value)
}
}
is TypeFilter -> {
it.state.filter { it.state }.forEach {
addQueryParameter("country", it.value)
}
}
is SortFilter -> {
addQueryParameter("sort", it.getValue())
}
is StatusFilter -> {
if (it.state > 0) {
addQueryParameter("status", it.getValue())
}
}
is ContentRatingFilter -> {
if (it.state > 0) {
addQueryParameter("content_rating", it.getValue())
}
}
is CreatedAtFilter -> {
if (it.state > 0) {
addQueryParameter("time", it.getValue())
}
}
is MinimumFilter -> {
if (it.state.isNotEmpty()) {
addQueryParameter("minimum", it.state)
}
}
is FromYearFilter -> {
if (it.state.isNotEmpty()) {
addQueryParameter("from", it.state)
}
}
is ToYearFilter -> {
if (it.state.isNotEmpty()) {
addQueryParameter("to", it.state)
}
}
is TagFilter -> {
if (it.state.isNotEmpty()) {
addTagQueryParameters(this, it.state, "tags")
}
}
is ExcludedTagFilter -> {
if (it.state.isNotEmpty()) {
addTagQueryParameters(this, it.state, "excluded-tags")
}
}
else -> {}
}
}
addTagQueryParameters(this, preferences.ignoredTags, "excluded-tags")
addQueryParameter("tachiyomi", "true")
addQueryParameter("limit", "$LIMIT")
addQueryParameter("page", "$page")
}.build()
return GET(url, headers)
}
override fun searchMangaParse(response: Response) = popularMangaParse(response)
/** Manga Details **/
override fun mangaDetailsRequest(manga: SManga): Request {
// Migration from slug based urls to hid based ones
if (!manga.url.endsWith("#")) {
throw Exception("Migrate from Comick to Comick")
}
val mangaUrl = manga.url.removeSuffix("#")
return GET("$apiUrl$mangaUrl?tachiyomi=true", headers)
}
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return client.newCall(mangaDetailsRequest(manga))
.asObservableSuccess()
.map { response ->
mangaDetailsParse(response, manga).apply { initialized = true }
}
}
override fun mangaDetailsParse(response: Response): SManga =
mangaDetailsParse(response, SManga.create())
private fun mangaDetailsParse(response: Response, manga: SManga): SManga {
val mangaData = response.parseAs<Manga>()
if (!preferences.updateCover && manga.thumbnail_url != mangaData.comic.cover) {
val coversUrl =
"$apiUrl/comic/${mangaData.comic.slug ?: mangaData.comic.hid}/covers?tachiyomi=true"
val covers = client.newCall(GET(coversUrl)).execute()
.parseAs<Covers>().mdCovers.reversed()
val firstVol = covers.filter { it.vol == "1" }.ifEmpty { covers }
val originalCovers = firstVol
.filter { mangaData.comic.isoLang.orEmpty().startsWith(it.locale.orEmpty()) }
val localCovers = firstVol
.filter { comickLang.startsWith(it.locale.orEmpty()) }
return mangaData.toSManga(
includeMuTags = preferences.includeMuTags,
scorePosition = preferences.scorePosition,
showAlternativeTitles = preferences.showAlternativeTitles,
covers = localCovers.ifEmpty { originalCovers }.ifEmpty { firstVol },
groupTags = preferences.groupTags,
titleLang = preferences.localTitle,
)
}
return mangaData.toSManga(
includeMuTags = preferences.includeMuTags,
scorePosition = preferences.scorePosition,
showAlternativeTitles = preferences.showAlternativeTitles,
groupTags = preferences.groupTags,
titleLang = preferences.localTitle,
)
}
override fun getMangaUrl(manga: SManga): String {
return "$baseUrl${manga.url.removeSuffix("#")}"
}
/** Manga Chapter List **/
override fun chapterListRequest(manga: SManga): Request {
// Migration from slug based urls to hid based ones
if (!manga.url.endsWith("#")) {
throw Exception("Migrate from Comick to Comick")
}
val mangaUrl = manga.url.removeSuffix("#")
val url = "$apiUrl$mangaUrl".toHttpUrl().newBuilder().apply {
addPathSegment("chapters")
if (comickLang != "all") addQueryParameter("lang", comickLang)
addQueryParameter("tachiyomi", "true")
addQueryParameter("limit", "$CHAPTERS_LIMIT")
}.build()
return GET(url, headers)
}
override fun chapterListParse(response: Response): List<SChapter> {
val chapterListResponse = response.parseAs<ChapterList>()
val mangaUrl = response.request.url.toString()
.substringBefore("/chapters")
.substringAfter(apiUrl)
val currentTimestamp = System.currentTimeMillis()
return chapterListResponse.chapters
.filter {
val publishTime = try {
publishedDateFormat.parse(it.publishedAt)!!.time
} catch (_: ParseException) {
0L
}
val publishedChapter = publishTime <= currentTimestamp
val noGroupBlock = it.groups.map { g -> g.lowercase() }
.intersect(preferences.ignoredGroups)
.isEmpty()
publishedChapter && noGroupBlock
}
.filterOnScore(preferences.chapterScoreFiltering)
.map { it.toSChapter(mangaUrl) }
}
private fun List<Chapter>.filterOnScore(shouldFilter: Boolean): Collection<Chapter> {
if (shouldFilter) {
return groupBy { it.chap }
.map { (_, chapters) -> chapters.maxBy { it.score } }
} else {
return this
}
}
private val publishedDateFormat =
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
override fun getChapterUrl(chapter: SChapter): String {
return "$baseUrl${chapter.url}"
}
/** Chapter Pages **/
override fun pageListRequest(chapter: SChapter): Request {
val chapterHid = chapter.url.substringAfterLast("/").substringBefore("-")
return GET("$apiUrl/chapter/$chapterHid?tachiyomi=true", headers)
}
override fun pageListParse(response: Response): List<Page> {
val result = response.parseAs<PageList>()
val images = result.chapter.images.ifEmpty {
// cache busting
val url = response.request.url.newBuilder()
.addQueryParameter("_", System.currentTimeMillis().toString())
.build()
client.newCall(GET(url, headers)).execute()
.parseAs<PageList>().chapter.images
}
return images.mapIndexedNotNull { index, data ->
if (data.url == null) null else Page(index = index, imageUrl = data.url)
}
}
private inline fun <reified T> Response.parseAs(): T {
return json.decodeFromString(body.string())
}
override fun imageUrlParse(response: Response): String {
throw UnsupportedOperationException()
}
override fun getFilterList() = getFilters()
private fun SharedPreferences.newLineIgnoredGroups() {
if (getBoolean(MIGRATED_IGNORED_GROUPS, false)) return
val ignoredGroups = getString(IGNORED_GROUPS_PREF, "").orEmpty()
edit()
.putString(
IGNORED_GROUPS_PREF,
ignoredGroups
.split(",")
.map(String::trim)
.filter(String::isNotEmpty)
.joinToString("\n"),
)
.putBoolean(MIGRATED_IGNORED_GROUPS, true)
.apply()
}
companion object {
const val SLUG_SEARCH_PREFIX = "id:"
private val SPACE_AND_SLASH_REGEX = Regex("[ /]")
private const val IGNORED_GROUPS_PREF = "IgnoredGroups"
private const val IGNORED_TAGS_PREF = "IgnoredTags"
private const val SHOW_ALTERNATIVE_TITLES_PREF = "ShowAlternativeTitles"
const val SHOW_ALTERNATIVE_TITLES_DEFAULT = false
private const val INCLUDE_MU_TAGS_PREF = "IncludeMangaUpdatesTags"
const val INCLUDE_MU_TAGS_DEFAULT = false
private const val GROUP_TAGS_PREF = "GroupTags"
const val GROUP_TAGS_DEFAULT = false
private const val MIGRATED_IGNORED_GROUPS = "MigratedIgnoredGroups"
private const val FIRST_COVER_PREF = "DefaultCover"
private const val FIRST_COVER_DEFAULT = true
private const val SCORE_POSITION_PREF = "ScorePosition"
const val SCORE_POSITION_DEFAULT = "top"
private const val LOCAL_TITLE_PREF = "LocalTitle"
private const val LOCAL_TITLE_DEFAULT = false
private const val CHAPTER_SCORE_FILTERING_PREF = "ScoreAutoFiltering"
private const val CHAPTER_SCORE_FILTERING_DEFAULT = false
private const val LIMIT = 20
private const val CHAPTERS_LIMIT = 99999
}
}

View File

@ -0,0 +1,62 @@
package eu.kanade.tachiyomi.extension.all.comickfun
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceFactory
// A legacy mapping of language codes to ensure that source IDs don't change
val legacyLanguageMappings = mapOf(
"pt-br" to "pt-BR", // Brazilian Portuguese
"zh-hk" to "zh-Hant", // Traditional Chinese,
"zh" to "zh-Hans", // Simplified Chinese
).withDefault { it } // country code matches language code
class ComickFactory : SourceFactory {
private val idMap = listOf(
"all" to 982606170401027267,
"en" to 2971557565147974499,
"pt-br" to 8729626158695297897,
"ru" to 5846182885417171581,
"fr" to 9126078936214680667,
"es-419" to 3182432228546767958,
"pl" to 7005108854993254607,
"tr" to 7186425300860782365,
"it" to 8807318985460553537,
"es" to 9052019484488287695,
"id" to 5506707690027487154,
"hu" to 7838940669485160901,
"vi" to 9191587139933034493,
"zh-hk" to 3140511316190656180,
"ar" to 8266599095155001097,
"de" to 7552236568334706863,
"zh" to 1071494508319622063,
"ca" to 2159382907508433047,
"bg" to 8981320463367739957,
"th" to 4246541831082737053,
"fa" to 3146252372540608964,
"uk" to 3505068018066717349,
"mn" to 2147260678391898600,
"ro" to 6676949771764486043,
"he" to 5354540502202034685,
"ms" to 4731643595200952045,
"tl" to 8549617092958820123,
"ja" to 8288710818308434509,
"hi" to 5176570178081213805,
"my" to 9199495862098963317,
"ko" to 3493720175703105662,
"cs" to 2651978322082769022,
"pt" to 4153491877797434408,
"nl" to 6104206360977276112,
"sv" to 979314012722687145,
"bn" to 3598159956413889411,
"no" to 5932005504194733317,
"lt" to 1792260331167396074,
"el" to 6190162673651111756,
"sr" to 571668187470919545,
"da" to 7137437402245830147,
).toMap()
override fun createSources(): List<Source> = idMap.keys.map {
object : Comick(legacyLanguageMappings.getValue(it), it) {
override val id: Long = idMap[it]!!
}
}
}

View File

@ -1,4 +1,4 @@
package eu.kanade.tachiyomi.extension.en.kmanga
package eu.kanade.tachiyomi.extension.all.comickfun
import android.app.Activity
import android.content.ActivityNotFoundException
@ -7,25 +7,25 @@ import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
class KMangaUrlActivity : Activity() {
class ComickUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 1) {
val titleId = pathSegments[1]
val slug = pathSegments[1]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${KManga.PREFIX_SEARCH}$titleId")
putExtra("query", "${Comick.SLUG_SEARCH_PREFIX}$slug")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("KMangaUrlActivity", e.toString())
Log.e("ComickFunUrlActivity", e.toString())
}
} else {
Log.e("KMangaUrlActivity", "Could not parse URI from intent $intent")
Log.e("ComickFunUrlActivity", "could not parse uri from intent $intent")
}
finish()

View File

@ -0,0 +1,237 @@
package eu.kanade.tachiyomi.extension.all.comickfun
import eu.kanade.tachiyomi.extension.all.comickfun.Comick.Companion.GROUP_TAGS_DEFAULT
import eu.kanade.tachiyomi.extension.all.comickfun.Comick.Companion.INCLUDE_MU_TAGS_DEFAULT
import eu.kanade.tachiyomi.extension.all.comickfun.Comick.Companion.SCORE_POSITION_DEFAULT
import eu.kanade.tachiyomi.extension.all.comickfun.Comick.Companion.SHOW_ALTERNATIVE_TITLES_DEFAULT
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.math.BigDecimal
import java.math.RoundingMode
@Serializable
class SearchManga(
private val hid: String,
private val title: String,
@SerialName("md_covers") val mdCovers: List<MDcovers> = emptyList(),
@SerialName("cover_url") val cover: String? = null,
) {
fun toSManga() = SManga.create().apply {
// appending # at end as part of migration from slug to hid
url = "/comic/$hid#"
title = this@SearchManga.title
thumbnail_url = parseCover(cover, mdCovers)
}
}
@Serializable
class Manga(
val comic: Comic,
private val artists: List<Name> = emptyList(),
private val authors: List<Name> = emptyList(),
private val genres: List<Genre> = emptyList(),
private val demographic: String? = null,
) {
fun toSManga(
includeMuTags: Boolean = INCLUDE_MU_TAGS_DEFAULT,
scorePosition: String = SCORE_POSITION_DEFAULT,
showAlternativeTitles: Boolean = SHOW_ALTERNATIVE_TITLES_DEFAULT,
covers: List<MDcovers>? = null,
groupTags: Boolean = GROUP_TAGS_DEFAULT,
titleLang: String,
): SManga {
val entryTitle = comic.altTitles.firstOrNull {
titleLang != "all" && !it.lang.isNullOrBlank() && titleLang.startsWith(it.lang)
}?.title ?: comic.title
val titles = listOf(Title(title = comic.title)) + comic.altTitles
return SManga.create().apply {
// appennding # at end as part of migration from slug to hid
url = "/comic/${comic.hid}#"
title = entryTitle
description = buildString {
if (scorePosition == "top") append(comic.fancyScore)
val desc = comic.desc?.beautifyDescription()
if (!desc.isNullOrEmpty()) {
if (this.isNotEmpty()) append("\n\n")
append(desc)
}
if (scorePosition == "middle") {
if (this.isNotEmpty()) append("\n\n")
append(comic.fancyScore)
}
if (showAlternativeTitles && comic.altTitles.isNotEmpty()) {
if (this.isNotEmpty()) append("\n\n")
append("Alternative Titles:\n")
append(
titles.distinctBy { it.title }.filter { it.title != entryTitle }
.mapNotNull { title ->
title.title?.let { "$it" }
}.joinToString("\n"),
)
}
if (scorePosition == "bottom") {
if (this.isNotEmpty()) append("\n\n")
append(comic.fancyScore)
}
}
status = comic.status.parseStatus(comic.translationComplete)
thumbnail_url = parseCover(
comic.cover,
covers ?: comic.mdCovers,
)
artist = artists.joinToString { it.name.trim() }
author = authors.joinToString { it.name.trim() }
genre = buildList {
comic.origination?.let { add(Genre("Origination", it.name)) }
demographic?.let { add(Genre("Demographic", it)) }
addAll(
comic.mdGenres.mapNotNull { it.genre }.sortedBy { it.group }
.sortedBy { it.name },
)
addAll(genres.sortedBy { it.group }.sortedBy { it.name })
if (includeMuTags) {
addAll(
comic.muGenres.categories.mapNotNull { it?.category?.title }.sorted()
.map { Genre("Category", it) },
)
}
}
.distinctBy { it.name }
.filterNot { it.name.isNullOrBlank() || it.group.isNullOrBlank() }
.joinToString { if (groupTags) "${it.group}:${it.name?.trim()}" else "${it.name?.trim()}" }
}
}
}
@Serializable
class Comic(
val hid: String,
val title: String,
private val country: String? = null,
val slug: String? = null,
@SerialName("md_titles") val altTitles: List<Title> = emptyList(),
val desc: String? = null,
val status: Int? = 0,
@SerialName("translation_completed") val translationComplete: Boolean? = true,
@SerialName("md_covers") val mdCovers: List<MDcovers> = emptyList(),
@SerialName("cover_url") val cover: String? = null,
@SerialName("md_comic_md_genres") val mdGenres: List<MdGenres>,
@SerialName("mu_comics") val muGenres: MuComicCategories = MuComicCategories(emptyList()),
@SerialName("bayesian_rating") val score: String? = null,
@SerialName("iso639_1") val isoLang: String? = null,
) {
val origination = when (country) {
"jp" -> Name("Manga")
"kr" -> Name("Manhwa")
"cn" -> Name("Manhua")
else -> null
}
val fancyScore: String = if (score.isNullOrEmpty()) {
""
} else {
val stars = score.toBigDecimal().div(BigDecimal(2))
.setScale(0, RoundingMode.HALF_UP).toInt()
buildString {
append("".repeat(stars))
if (stars < 5) append("".repeat(5 - stars))
append(" $score")
}
}
}
@Serializable
class MdGenres(
@SerialName("md_genres") val genre: Genre? = null,
)
@Serializable
class Genre(
val group: String? = null,
val name: String? = null,
)
@Serializable
class MuComicCategories(
@SerialName("mu_comic_categories") val categories: List<MuCategories?> = emptyList(),
)
@Serializable
class MuCategories(
@SerialName("mu_categories") val category: Title? = null,
)
@Serializable
class Covers(
@SerialName("md_covers") val mdCovers: List<MDcovers> = emptyList(),
)
@Serializable
class MDcovers(
val b2key: String?,
val vol: String? = null,
val locale: String? = null,
)
@Serializable
class Title(
val title: String?,
val lang: String? = null,
)
@Serializable
class Name(
val name: String,
)
@Serializable
class ChapterList(
val chapters: List<Chapter>,
)
@Serializable
class Chapter(
private val hid: String,
private val lang: String = "",
private val title: String = "",
@SerialName("created_at") private val createdAt: String = "",
@SerialName("publish_at") val publishedAt: String = "",
val chap: String = "",
private val vol: String = "",
@SerialName("group_name") val groups: List<String> = emptyList(),
@SerialName("up_count") private val upCount: Int,
@SerialName("down_count") private val downCount: Int,
) {
val score get() = upCount - downCount
fun toSChapter(mangaUrl: String) = SChapter.create().apply {
url = "$mangaUrl/$hid-chapter-$chap-$lang"
name = beautifyChapterName(vol, chap, title)
date_upload = createdAt.parseDate()
scanlator = groups.joinToString().takeUnless { it.isBlank() } ?: "Unknown"
}
}
@Serializable
class PageList(
val chapter: ChapterPageData,
)
@Serializable
class ChapterPageData(
val images: List<Page>,
)
@Serializable
class Page(
val url: String? = null,
)
@Serializable
class Error(
val statusCode: Int,
val message: String,
)

View File

@ -0,0 +1,208 @@
package eu.kanade.tachiyomi.extension.all.comickfun
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
fun getFilters(): FilterList {
return FilterList(
Filter.Header(name = "The filter is ignored when using text search."),
GenreFilter("Genre", getGenresList),
DemographicFilter("Demographic", getDemographicList),
TypeFilter("Type", getTypeList),
SortFilter(),
StatusFilter("Status", getStatusList),
ContentRatingFilter("Content Rating", getContentRatingList),
CompletedFilter("Completely Scanlated?"),
CreatedAtFilter("Created at", getCreatedAtList),
MinimumFilter("Minimum Chapters"),
Filter.Header("From Year, ex: 2010"),
FromYearFilter("From"),
Filter.Header("To Year, ex: 2021"),
ToYearFilter("To"),
Filter.Header("Separate tags with commas"),
TagFilter("Tags"),
ExcludedTagFilter("Excluded Tags"),
)
}
/** Filters **/
internal class GenreFilter(name: String, genreList: List<Pair<String, String>>) :
Filter.Group<TriFilter>(name, genreList.map { TriFilter(it.first, it.second) })
internal class TagFilter(name: String) : TextFilter(name)
internal class ExcludedTagFilter(name: String) : TextFilter(name)
internal class DemographicFilter(name: String, demographicList: List<Pair<String, String>>) :
Filter.Group<CheckBoxFilter>(name, demographicList.map { CheckBoxFilter(it.first, it.second) })
internal class TypeFilter(name: String, typeList: List<Pair<String, String>>) :
Filter.Group<CheckBoxFilter>(name, typeList.map { CheckBoxFilter(it.first, it.second) })
internal class CompletedFilter(name: String) : CheckBoxFilter(name)
internal class CreatedAtFilter(name: String, createdAtList: List<Pair<String, String>>) :
SelectFilter(name, createdAtList)
internal class MinimumFilter(name: String) : TextFilter(name)
internal class FromYearFilter(name: String) : TextFilter(name)
internal class ToYearFilter(name: String) : TextFilter(name)
internal class SortFilter(defaultValue: String? = null, state: Int = 0) :
SelectFilter("Sort", getSortsList, state, defaultValue)
internal class StatusFilter(name: String, statusList: List<Pair<String, String>>, state: Int = 0) :
SelectFilter(name, statusList, state)
internal class ContentRatingFilter(name: String, statusList: List<Pair<String, String>>, state: Int = 0) :
SelectFilter(name, statusList, state)
/** Generics **/
internal open class TriFilter(name: String, val value: String) : Filter.TriState(name)
internal open class TextFilter(name: String) : Filter.Text(name)
internal open class CheckBoxFilter(name: String, val value: String = "") : Filter.CheckBox(name)
internal open class SelectFilter(name: String, private val vals: List<Pair<String, String>>, state: Int = 0, defaultValue: String? = null) :
Filter.Select<String>(name, vals.map { it.first }.toTypedArray(), vals.indexOfFirst { it.second == defaultValue }.takeIf { it != -1 } ?: state) {
fun getValue() = vals[state].second
}
/** Filters Data **/
private val getGenresList: List<Pair<String, String>> = listOf(
Pair("4-Koma", "4-koma"),
Pair("Action", "action"),
Pair("Adaptation", "adaptation"),
Pair("Adult", "adult"),
Pair("Adventure", "adventure"),
Pair("Aliens", "aliens"),
Pair("Animals", "animals"),
Pair("Anthology", "anthology"),
Pair("Award Winning", "award-winning"),
Pair("Comedy", "comedy"),
Pair("Cooking", "cooking"),
Pair("Crime", "crime"),
Pair("Crossdressing", "crossdressing"),
Pair("Delinquents", "delinquents"),
Pair("Demons", "demons"),
Pair("Doujinshi", "doujinshi"),
Pair("Drama", "drama"),
Pair("Ecchi", "ecchi"),
Pair("Fan Colored", "fan-colored"),
Pair("Fantasy", "fantasy"),
Pair("Full Color", "full-color"),
Pair("Gender Bender", "gender-bender"),
Pair("Genderswap", "genderswap"),
Pair("Ghosts", "ghosts"),
Pair("Gore", "gore"),
Pair("Gyaru", "gyaru"),
Pair("Harem", "harem"),
Pair("Historical", "historical"),
Pair("Horror", "horror"),
Pair("Incest", "incest"),
Pair("Isekai", "isekai"),
Pair("Loli", "loli"),
Pair("Long Strip", "long-strip"),
Pair("Mafia", "mafia"),
Pair("Magic", "magic"),
Pair("Magical Girls", "magical-girls"),
Pair("Martial Arts", "martial-arts"),
Pair("Mature", "mature"),
Pair("Mecha", "mecha"),
Pair("Medical", "medical"),
Pair("Military", "military"),
Pair("Monster Girls", "monster-girls"),
Pair("Monsters", "monsters"),
Pair("Music", "music"),
Pair("Mystery", "mystery"),
Pair("Ninja", "ninja"),
Pair("Office Workers", "office-workers"),
Pair("Official Colored", "official-colored"),
Pair("Oneshot", "oneshot"),
Pair("Philosophical", "philosophical"),
Pair("Police", "police"),
Pair("Post-Apocalyptic", "post-apocalyptic"),
Pair("Psychological", "psychological"),
Pair("Reincarnation", "reincarnation"),
Pair("Reverse Harem", "reverse-harem"),
Pair("Romance", "romance"),
Pair("Samurai", "samurai"),
Pair("School Life", "school-life"),
Pair("Sci-Fi", "sci-fi"),
Pair("Sexual Violence", "sexual-violence"),
Pair("Shota", "shota"),
Pair("Shoujo Ai", "shoujo-ai"),
Pair("Shounen Ai", "shounen-ai"),
Pair("Slice of Life", "slice-of-life"),
Pair("Smut", "smut"),
Pair("Sports", "sports"),
Pair("Superhero", "superhero"),
Pair("Supernatural", "supernatural"),
Pair("Survival", "survival"),
Pair("Thriller", "thriller"),
Pair("Time Travel", "time-travel"),
Pair("Traditional Games", "traditional-games"),
Pair("Tragedy", "tragedy"),
Pair("User Created", "user-created"),
Pair("Vampires", "vampires"),
Pair("Video Games", "video-games"),
Pair("Villainess", "villainess"),
Pair("Virtual Reality", "virtual-reality"),
Pair("Web Comic", "web-comic"),
Pair("Wuxia", "wuxia"),
Pair("Yaoi", "yaoi"),
Pair("Yuri", "yuri"),
Pair("Zombies", "zombies"),
)
private val getDemographicList: List<Pair<String, String>> = listOf(
Pair("Shounen", "1"),
Pair("Shoujo", "2"),
Pair("Seinen", "3"),
Pair("Josei", "4"),
Pair("None", "5"),
)
private val getTypeList: List<Pair<String, String>> = listOf(
Pair("Manga", "jp"),
Pair("Manhwa", "kr"),
Pair("Manhua", "cn"),
Pair("Others", "others"),
)
private val getCreatedAtList: List<Pair<String, String>> = listOf(
Pair("", ""),
Pair("3 days", "3"),
Pair("7 days", "7"),
Pair("30 days", "30"),
Pair("3 months", "90"),
Pair("6 months", "180"),
Pair("1 year", "365"),
)
private val getSortsList: List<Pair<String, String>> = listOf(
Pair("Most popular", "follow"),
Pair("Most follows", "user_follow_count"),
Pair("Most views", "view"),
Pair("High rating", "rating"),
Pair("Last updated", "uploaded"),
Pair("Newest", "created_at"),
)
private val getStatusList: List<Pair<String, String>> = listOf(
Pair("All", "0"),
Pair("Ongoing", "1"),
Pair("Completed", "2"),
Pair("Cancelled", "3"),
Pair("Hiatus", "4"),
)
private val getContentRatingList: List<Pair<String, String>> = listOf(
Pair("All", ""),
Pair("Safe", "safe"),
Pair("Suggestive", "suggestive"),
Pair("Erotica", "erotica"),
)

View File

@ -0,0 +1,68 @@
package eu.kanade.tachiyomi.extension.all.comickfun
import eu.kanade.tachiyomi.source.model.SManga
import org.jsoup.parser.Parser
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
private val dateFormat by lazy {
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
}
private val markdownLinksRegex = "\\[([^]]+)]\\(([^)]+)\\)".toRegex()
private val markdownItalicBoldRegex = "\\*+\\s*([^*]*)\\s*\\*+".toRegex()
private val markdownItalicRegex = "_+\\s*([^_]*)\\s*_+".toRegex()
internal fun String.beautifyDescription(): String {
return Parser.unescapeEntities(this, false)
.substringBefore("---")
.replace(markdownLinksRegex, "")
.replace(markdownItalicBoldRegex, "")
.replace(markdownItalicRegex, "")
.trim()
}
internal fun Int?.parseStatus(translationComplete: Boolean?): Int {
return when (this) {
1 -> SManga.ONGOING
2 -> {
if (translationComplete == true) {
SManga.COMPLETED
} else {
SManga.PUBLISHING_FINISHED
}
}
3 -> SManga.CANCELLED
4 -> SManga.ON_HIATUS
else -> SManga.UNKNOWN
}
}
internal fun parseCover(thumbnailUrl: String?, mdCovers: List<MDcovers>): String? {
val b2key = mdCovers.firstOrNull()?.b2key
?: return thumbnailUrl
val vol = mdCovers.firstOrNull()?.vol.orEmpty()
return thumbnailUrl?.replaceAfterLast("/", "$b2key#$vol")
}
internal fun beautifyChapterName(vol: String, chap: String, title: String): String {
return buildString {
if (vol.isNotEmpty()) {
if (chap.isEmpty()) append("Volume $vol") else append("Vol. $vol")
}
if (chap.isNotEmpty()) {
if (vol.isEmpty()) append("Chapter $chap") else append(", Ch. $chap")
}
if (title.isNotEmpty()) {
if (chap.isEmpty()) append(title) else append(": $title")
}
}
}
internal fun String.parseDate(): Long {
return runCatching { dateFormat.parse(this)?.time }
.getOrNull() ?: 0L
}

View File

@ -2,7 +2,7 @@ ext {
extName = 'Coomer'
extClass = '.Coomer'
themePkg = 'kemono'
baseUrl = 'https://coomer.st'
baseUrl = 'https://coomer.su'
overrideVersionCode = 0
isNsfw = true
}

View File

@ -2,7 +2,7 @@ package eu.kanade.tachiyomi.extension.all.coomer
import eu.kanade.tachiyomi.multisrc.kemono.Kemono
class Coomer : Kemono("Coomer", "https://coomer.st", "all") {
class Coomer : Kemono("Coomer", "https://coomer.su", "all") {
override val getTypes = listOf(
"OnlyFans",
"Fansly",

View File

@ -0,0 +1,8 @@
ext {
extName = 'Galaxy'
extClass = '.GalaxyFactory'
extVersionCode = 5
isNsfw = false
}
apply from: "$rootDir/common.gradle"

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1,327 @@
package eu.kanade.tachiyomi.extension.all.galaxy
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.interceptor.rateLimit
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.asJsoup
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import java.util.Calendar
abstract class Galaxy(
override val name: String,
override val baseUrl: String,
override val lang: String,
) : HttpSource() {
override val supportsLatest = true
override val client = network.cloudflareClient.newBuilder()
.rateLimit(2)
.build()
override fun headersBuilder() = super.headersBuilder()
.add("Referer", "$baseUrl/")
override fun popularMangaRequest(page: Int): Request {
return if (page == 1) {
GET("$baseUrl/webtoons/romance/home", headers)
} else {
GET("$baseUrl/webtoons/action/home", headers)
}
}
override fun popularMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
val entries = document.select(
"""div.tabs div[wire:snapshot*=App\\Models\\Serie], main div:has(h2:matches(Today\'s Hot|الرائج اليوم)) a[wire:snapshot*=App\\Models\\Serie]""",
).map { element ->
SManga.create().apply {
setUrlWithoutDomain(
if (element.tagName().equals("a")) {
element.absUrl("href")
} else {
element.selectFirst("a")!!.absUrl("href")
},
)
thumbnail_url = element.selectFirst("img")?.absUrl("src")
title = element.selectFirst("div.text-sm")!!.text()
}
}.distinctBy { it.url }
return MangasPage(entries, response.request.url.pathSegments.getOrNull(1) == "romance")
}
override fun latestUpdatesRequest(page: Int): Request {
val url = "$baseUrl/latest?serie_type=webtoon&main_genres=romance" +
if (page > 1) {
"&page=$page"
} else {
""
}
return GET(url, headers)
}
override fun latestUpdatesParse(response: Response): MangasPage {
val document = response.asJsoup()
val entries = document.select("div[wire:snapshot*=App\\\\Models\\\\Serie]").map { element ->
SManga.create().apply {
setUrlWithoutDomain(element.selectFirst("a")!!.absUrl("href"))
thumbnail_url = element.selectFirst("img")?.absUrl("src")
title = element.select("div.flex a[href*=/series/]").last()!!.text()
}
}
val hasNextPage = document.selectFirst("[role=navigation] button[wire:click*=nextPage]") != null
return MangasPage(entries, hasNextPage)
}
private var filters: List<FilterData> = emptyList()
private val scope = CoroutineScope(Dispatchers.IO)
protected fun launchIO(block: () -> Unit) = scope.launch {
try {
block()
} catch (_: Exception) { }
}
override fun getFilterList(): FilterList {
launchIO {
if (filters.isEmpty()) {
val document = client.newCall(GET("$baseUrl/search", headers)).execute().asJsoup()
val mainGenre = FilterData(
displayName = document.select("label[for$=main_genres]").text(),
options = document.select("select[wire:model.live=main_genres] option").map {
it.text() to it.attr("value")
},
queryParameter = "main_genres",
)
val typeFilter = FilterData(
displayName = document.select("label[for$=type]").text(),
options = document.select("select[wire:model.live=type] option").map {
it.text() to it.attr("value")
},
queryParameter = "type",
)
val statusFilter = FilterData(
displayName = document.select("label[for$=status]").text(),
options = document.select("select[wire:model.live=status] option").map {
it.text() to it.attr("value")
},
queryParameter = "status",
)
val genreFilter = FilterData(
displayName = if (lang == "ar") {
"التصنيفات"
} else {
"Genre"
},
options = document.select("div[x-data*=genre] > div").map {
it.text() to it.attr("wire:key")
},
queryParameter = "genre",
)
filters = listOf(mainGenre, typeFilter, statusFilter, genreFilter)
}
}
val filters: List<Filter<*>> = filters.map {
SelectFilter(
it.displayName,
it.options,
it.queryParameter,
)
}.ifEmpty {
listOf(
Filter.Header("Press 'reset' to load filters"),
)
}
return FilterList(filters)
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$baseUrl/search".toHttpUrl().newBuilder().apply {
addQueryParameter("serie_type", "webtoon")
addQueryParameter("title", query.trim())
filters.filterIsInstance<SelectFilter>().forEach {
it.addFilterParameter(this)
}
if (page > 1) {
addQueryParameter("page", page.toString())
}
}.build()
return GET(url, headers)
}
override fun searchMangaParse(response: Response) = latestUpdatesParse(response)
override fun mangaDetailsParse(response: Response): SManga {
val document = response.asJsoup()
return SManga.create().apply {
title = document.select("#full_model h3").text()
thumbnail_url = document.selectFirst("main img[src*=series/webtoon]")?.absUrl("src")
status = when (document.getQueryParam("status")) {
"ongoing", "soon" -> SManga.ONGOING
"completed", "droped" -> SManga.COMPLETED
"onhold" -> SManga.ON_HIATUS
else -> SManga.UNKNOWN
}
genre = buildList {
document.getQueryParam("type")
?.capitalize()?.let(::add)
document.select("#full_model a[href*=search?genre]")
.eachText().let(::addAll)
}.joinToString()
author = document.select("#full_model [wire:key^=a-]").eachText().joinToString()
artist = document.select("#full_model [wire:key^=r-]").eachText().joinToString()
description = buildString {
append(document.select("#full_model p").text().trim())
append("\n\nAlternative Names:\n")
document.select("#full_model [wire:key^=n-]")
.joinToString("\n") { "${it.text().trim().removeMdEscaped()}" }
.let(::append)
}.trim()
}
}
private fun Document.getQueryParam(queryParam: String): String? {
return selectFirst("#full_model a[href*=search?$queryParam]")
?.absUrl("href")?.toHttpUrlOrNull()?.queryParameter(queryParam)
}
private fun String.capitalize(): String {
val result = StringBuilder(length)
var capitalize = true
for (char in this) {
result.append(
if (capitalize) {
char.uppercase()
} else {
char.lowercase()
},
)
capitalize = char.isWhitespace()
}
return result.toString()
}
private val mdRegex = Regex("""&amp;#(\d+);""")
private fun String.removeMdEscaped(): String {
val char = mdRegex.find(this)?.groupValues?.get(1)?.toIntOrNull()
?: return this
return replaceFirst(mdRegex, Char(char).toString())
}
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
return document.select("a[href*=/read/]:not([type=button])").map { element ->
SChapter.create().apply {
setUrlWithoutDomain(element.absUrl("href"))
name = element.select("span.font-normal").text()
date_upload = element.selectFirst("div:not(:has(> svg)) > span.text-xs")
?.text().parseRelativeDate()
}
}
}
protected open fun String?.parseRelativeDate(): Long {
this ?: return 0L
val number = Regex("""(\d+)""").find(this)?.value?.toIntOrNull() ?: 0
val cal = Calendar.getInstance()
return when {
listOf("second", "ثانية").any { contains(it, true) } -> {
cal.apply { add(Calendar.SECOND, -number) }.timeInMillis
}
contains("دقيقتين", true) -> {
cal.apply { add(Calendar.MINUTE, -2) }.timeInMillis
}
listOf("minute", "دقائق").any { contains(it, true) } -> {
cal.apply { add(Calendar.MINUTE, -number) }.timeInMillis
}
contains("ساعتان", true) -> {
cal.apply { add(Calendar.HOUR, -2) }.timeInMillis
}
listOf("hour", "ساعات").any { contains(it, true) } -> {
cal.apply { add(Calendar.HOUR, -number) }.timeInMillis
}
contains("يوم", true) -> {
cal.apply { add(Calendar.DAY_OF_YEAR, -1) }.timeInMillis
}
contains("يومين", true) -> {
cal.apply { add(Calendar.DAY_OF_YEAR, -2) }.timeInMillis
}
listOf("day", "أيام").any { contains(it, true) } -> {
cal.apply { add(Calendar.DAY_OF_YEAR, -number) }.timeInMillis
}
contains("أسبوع", true) -> {
cal.apply { add(Calendar.WEEK_OF_YEAR, -1) }.timeInMillis
}
contains("أسبوعين", true) -> {
cal.apply { add(Calendar.WEEK_OF_YEAR, -2) }.timeInMillis
}
listOf("week", "أسابيع").any { contains(it, true) } -> {
cal.apply { add(Calendar.WEEK_OF_YEAR, -number) }.timeInMillis
}
contains("شهر", true) -> {
cal.apply { add(Calendar.MONTH, -1) }.timeInMillis
}
contains("شهرين", true) -> {
cal.apply { add(Calendar.MONTH, -2) }.timeInMillis
}
listOf("month", "أشهر").any { contains(it, true) } -> {
cal.apply { add(Calendar.MONTH, -number) }.timeInMillis
}
contains("سنة", true) -> {
cal.apply { add(Calendar.YEAR, -1) }.timeInMillis
}
contains("سنتان", true) -> {
cal.apply { add(Calendar.YEAR, -2) }.timeInMillis
}
listOf("year", "سنوات").any { contains(it, true) } -> {
cal.apply { add(Calendar.YEAR, -number) }.timeInMillis
}
else -> 0L
}
}
override fun pageListParse(response: Response): List<Page> {
val document = response.asJsoup()
return document.select("[wire:key^=image] img").mapIndexed { idx, img ->
Page(idx, imageUrl = img.absUrl("src"))
}
}
override fun imageUrlParse(response: Response) = throw UnsupportedOperationException()
}

View File

@ -0,0 +1,67 @@
package eu.kanade.tachiyomi.extension.all.galaxy
import android.content.SharedPreferences
import android.widget.Toast
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.SourceFactory
import keiyoushi.utils.getPreferencesLazy
class GalaxyFactory : SourceFactory {
class GalaxyWebtoon : Galaxy("Galaxy Webtoon", "https://galaxyaction.net", "en") {
override val id = 2602904659965278831
}
class GalaxyManga :
Galaxy("Galaxy Manga", "https://galaxymanga.net", "ar"),
ConfigurableSource {
override val id = 2729515745226258240
override val baseUrl by lazy { getPrefBaseUrl() }
private val preferences: SharedPreferences by getPreferencesLazy()
companion object {
private const val RESTART_APP = ".لتطبيق الإعدادات الجديدة أعد تشغيل التطبيق"
private const val BASE_URL_PREF_TITLE = "تعديل الرابط"
private const val BASE_URL_PREF = "overrideBaseUrl"
private const val BASE_URL_PREF_SUMMARY = ".للاستخدام المؤقت. تحديث التطبيق سيؤدي الى حذف الإعدادات"
private const val DEFAULT_BASE_URL_PREF = "defaultBaseUrl"
}
override fun setupPreferenceScreen(screen: PreferenceScreen) {
val baseUrlPref = androidx.preference.EditTextPreference(screen.context).apply {
key = BASE_URL_PREF
title = BASE_URL_PREF_TITLE
summary = BASE_URL_PREF_SUMMARY
this.setDefaultValue(super.baseUrl)
dialogTitle = BASE_URL_PREF_TITLE
dialogMessage = "Default: ${super.baseUrl}"
setOnPreferenceChangeListener { _, _ ->
Toast.makeText(screen.context, RESTART_APP, Toast.LENGTH_LONG).show()
true
}
}
screen.addPreference(baseUrlPref)
}
private fun getPrefBaseUrl(): String = preferences.getString(BASE_URL_PREF, super.baseUrl)!!
init {
preferences.getString(DEFAULT_BASE_URL_PREF, null).let { prefDefaultBaseUrl ->
if (prefDefaultBaseUrl != super.baseUrl) {
preferences.edit()
.putString(BASE_URL_PREF, super.baseUrl)
.putString(DEFAULT_BASE_URL_PREF, super.baseUrl)
.apply()
}
}
}
}
override fun createSources() = listOf(
GalaxyWebtoon(),
GalaxyManga(),
)
}

View File

@ -0,0 +1,28 @@
package eu.kanade.tachiyomi.extension.all.galaxy
import eu.kanade.tachiyomi.source.model.Filter
import okhttp3.HttpUrl
class SelectFilter(
name: String,
private val options: List<Pair<String, String>>,
private val queryParam: String,
) : Filter.Select<String>(
name,
buildList {
add("")
addAll(options.map { it.first })
}.toTypedArray(),
) {
fun addFilterParameter(url: HttpUrl.Builder) {
if (state == 0) return
url.addQueryParameter(queryParam, options[state - 1].second)
}
}
class FilterData(
val displayName: String,
val options: List<Pair<String, String>>,
val queryParameter: String,
)

View File

@ -1,7 +1,7 @@
ext {
extName = 'Hentai Cosplay'
extClass = '.HentaiCosplay'
extVersionCode = 6
extVersionCode = 5
isNsfw = true
}

View File

@ -209,7 +209,7 @@ class HentaiCosplay : HttpSource() {
override fun pageListParse(response: Response): List<Page> {
val document = response.asJsoup()
return document.select("amp-img[src*=upload]:not(.related-thumbnail)")
return document.select("amp-img[src*=upload]")
.mapIndexed { index, element ->
Page(
index = index,

View File

@ -1,7 +1,7 @@
ext {
extName = 'izneo (webtoons)'
extClass = '.IzneoFactory'
extVersionCode = 8
extVersionCode = 7
isNsfw = false
}

View File

@ -4,14 +4,14 @@ import android.util.Base64
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Response
import okhttp3.ResponseBody.Companion.asResponseBody
import okio.buffer
import okio.cipherSource
import okhttp3.ResponseBody.Companion.toResponseBody
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
object ImageInterceptor : Interceptor {
private val mediaType = "image/jpeg".toMediaType()
private inline val AES: Cipher
get() = Cipher.getInstance("AES/CBC/PKCS7Padding")
@ -31,7 +31,7 @@ object ImageInterceptor : Interceptor {
private fun Response.decode(key: ByteArray, iv: ByteArray) = AES.let {
it.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv))
newBuilder().body(body.source().cipherSource(it).buffer().asResponseBody("image/jpeg".toMediaType())).build()
newBuilder().body(it.doFinal(body.bytes()).toResponseBody(mediaType)).build()
}
private fun String.atob() = Base64.decode(this, Base64.URL_SAFE)

View File

@ -2,8 +2,8 @@ ext {
extName = 'Kemono'
extClass = '.Kemono'
themePkg = 'kemono'
baseUrl = 'https://kemono.cr'
overrideVersionCode = 1
baseUrl = 'https://kemono.su'
overrideVersionCode = 0
isNsfw = true
}

View File

@ -2,7 +2,7 @@ package eu.kanade.tachiyomi.extension.all.kemono
import eu.kanade.tachiyomi.multisrc.kemono.Kemono
class Kemono : Kemono("Kemono", "https://kemono.cr", "all") {
class Kemono : Kemono("Kemono", "https://kemono.su", "all") {
override val getTypes = listOf(
"Patreon",
"Pixiv Fanbox",

View File

@ -1,7 +1,7 @@
ext {
extName = 'Komga'
extClass = '.KomgaFactory'
extVersionCode = 64
extVersionCode = 63
}
apply from: "$rootDir/common.gradle"

View File

@ -76,8 +76,6 @@ open class Komga(private val suffix: String = "") : ConfigurableSource, Unmetere
private val password by lazy { preferences.getString(PREF_PASSWORD, "")!! }
private val apiKey by lazy { preferences.getString(PREF_API_KEY, "")!! }
private val defaultLibraries
get() = preferences.getStringSet(PREF_DEFAULT_LIBRARIES, emptySet())!!
@ -85,17 +83,12 @@ open class Komga(private val suffix: String = "") : ConfigurableSource, Unmetere
override fun headersBuilder() = super.headersBuilder()
.set("User-Agent", "TachiyomiKomga/${AppInfo.getVersionName()}")
.also { builder ->
if (apiKey.isNotBlank()) {
builder.set("X-API-Key", apiKey)
}
}
override val client: OkHttpClient =
network.cloudflareClient.newBuilder()
.authenticator { _, response ->
if (apiKey.isNotBlank() || response.request.header("Authorization") != null) {
null // Give up if API key is set or we've already failed to authenticate.
if (response.request.header("Authorization") != null) {
null // Give up, we've already failed to authenticate.
} else {
response.request.newBuilder()
.addHeader("Authorization", Credentials.basic(username, password))
@ -384,33 +377,21 @@ open class Komga(private val suffix: String = "") : ConfigurableSource, Unmetere
key = PREF_ADDRESS,
restartRequired = true,
)
// API key preference (takes precedence over username/password)
screen.addEditTextPreference(
title = "API key",
title = "Username",
default = "",
summary = if (apiKey.isBlank()) "Optional: Use an API key for authentication" else "*".repeat(apiKey.length),
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD,
key = PREF_API_KEY,
summary = username.ifBlank { "The user account email" },
key = PREF_USERNAME,
restartRequired = true,
)
screen.addEditTextPreference(
title = "Password",
default = "",
summary = if (password.isBlank()) "The user account password" else "*".repeat(password.length),
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD,
key = PREF_PASSWORD,
restartRequired = true,
)
// Only show username/password if API key is not set
if (apiKey.isBlank()) {
screen.addEditTextPreference(
title = "Username",
default = "",
summary = username.ifBlank { "The user account email" },
key = PREF_USERNAME,
restartRequired = true,
)
screen.addEditTextPreference(
title = "Password",
default = "",
summary = if (password.isBlank()) "The user account password" else "*".repeat(password.length),
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD,
key = PREF_PASSWORD,
restartRequired = true,
)
}
MultiSelectListPreference(screen.context).apply {
key = PREF_DEFAULT_LIBRARIES
@ -548,7 +529,6 @@ private const val PREF_DISPLAY_NAME = "Source display name"
private const val PREF_ADDRESS = "Address"
private const val PREF_USERNAME = "Username"
private const val PREF_PASSWORD = "Password"
private const val PREF_API_KEY = "API key"
private const val PREF_DEFAULT_LIBRARIES = "Default libraries"
private const val PREF_CHAPTER_NAME_TEMPLATE = "Chapter name template"
private const val PREF_CHAPTER_NAME_TEMPLATE_DEFAULT = "{number} - {title} ({size})"

View File

@ -1,7 +1,7 @@
ext {
extName = 'Luscious'
extClass = '.LusciousFactory'
extVersionCode = 22
extVersionCode = 20
isNsfw = true
}

View File

@ -31,11 +31,11 @@ import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.asResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.util.Calendar
@ -63,8 +63,8 @@ abstract class Luscious(
private val rewriteOctetStream: Interceptor = Interceptor { chain ->
val originalResponse: Response = chain.proceed(chain.request())
if (originalResponse.headers("Content-Type").contains("application/octet-stream") && originalResponse.request.url.toString().contains(".webp")) {
val orgBody = originalResponse.body.source()
val newBody = orgBody.asResponseBody("image/webp".toMediaType())
val orgBody = originalResponse.body.bytes()
val newBody = orgBody.toResponseBody("image/webp".toMediaTypeOrNull())
originalResponse.newBuilder()
.body(newBody)
.build()
@ -845,7 +845,7 @@ abstract class Luscious(
private const val MIRROR_PREF_KEY = "MIRROR"
private const val MIRROR_PREF_TITLE = "Mirror"
private val MIRROR_PREF_ENTRIES = arrayOf("Guest", "API", "Members")
private val MIRROR_PREF_ENTRY_VALUES = arrayOf("https://www.luscious.net", "https://apicdn.luscious.net", "https://members.luscious.net")
private val MIRROR_PREF_ENTRY_VALUES = arrayOf("https://www.luscious.net", "https://api.luscious.net", "https://members.luscious.net")
private val MIRROR_PREF_DEFAULT_VALUE = MIRROR_PREF_ENTRY_VALUES[0]
}

View File

@ -1,7 +1,7 @@
ext {
extName = 'MangaDex'
extClass = '.MangaDexFactory'
extVersionCode = 204
extVersionCode = 203
isNsfw = true
}

View File

@ -30,6 +30,7 @@ object MDConstants {
const val apiMangaUrl = "$apiUrl/manga"
const val apiChapterUrl = "$apiUrl/chapter"
const val apiListUrl = "$apiUrl/list"
const val atHomePostUrl = "https://api.mangadex.network/report"
val whitespaceRegex = "\\s".toRegex()
val mdAtHomeTokenLifespan = 5.minutes.inWholeMilliseconds

View File

@ -73,6 +73,7 @@ abstract class MangaDex(final override val lang: String, private val dexLang: St
override val client = network.cloudflareClient.newBuilder()
.rateLimit(3)
.addInterceptor(MdAtHomeReportInterceptor(network.cloudflareClient, headers))
.build()
// Popular manga section

View File

@ -0,0 +1,109 @@
package eu.kanade.tachiyomi.extension.all.mangadex
import android.util.Log
import eu.kanade.tachiyomi.extension.all.mangadex.dto.ImageReportDto
import eu.kanade.tachiyomi.network.POST
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import uy.kohesive.injekt.injectLazy
/**
* Interceptor to post to MD@Home for MangaDex Stats
*/
class MdAtHomeReportInterceptor(
private val client: OkHttpClient,
private val headers: Headers,
) : Interceptor {
private val json: Json by injectLazy()
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val response = chain.proceed(chain.request())
val url = originalRequest.url.toString()
if (!url.contains(MD_AT_HOME_URL_REGEX)) {
return response
}
Log.e("MangaDex", "Connecting to MD@Home node at $url")
val reportRequest = mdAtHomeReportRequest(response)
// Execute the report endpoint network call asynchronously to avoid blocking
// the reader from showing the image once it's fully loaded if the report call
// gets stuck, as it tend to happens sometimes.
client.newCall(reportRequest).enqueue(REPORT_CALLBACK)
if (response.isSuccessful) {
return response
}
response.close()
Log.e("MangaDex", "Error connecting to MD@Home node, fallback to uploads server")
val imagePath = originalRequest.url.pathSegments
.dropWhile { it != "data" && it != "data-saver" }
.joinToString("/")
val fallbackUrl = MDConstants.cdnUrl.toHttpUrl().newBuilder()
.addPathSegments(imagePath)
.build()
val fallbackRequest = originalRequest.newBuilder()
.url(fallbackUrl)
.headers(headers)
.build()
return chain.proceed(fallbackRequest)
}
private fun mdAtHomeReportRequest(response: Response): Request {
val result = ImageReportDto(
url = response.request.url.toString(),
success = response.isSuccessful,
bytes = response.peekBody(Long.MAX_VALUE).bytes().size,
cached = response.headers["X-Cache"] == "HIT",
duration = response.receivedResponseAtMillis - response.sentRequestAtMillis,
)
val payload = json.encodeToString(result)
return POST(
url = MDConstants.atHomePostUrl,
headers = headers,
body = payload.toRequestBody(JSON_MEDIA_TYPE),
)
}
companion object {
private val JSON_MEDIA_TYPE = "application/json".toMediaType()
private val MD_AT_HOME_URL_REGEX =
"""^https://[\w\d]+\.[\w\d]+\.mangadex(\b-test\b)?\.network.*${'$'}""".toRegex()
private val REPORT_CALLBACK = object : Callback {
override fun onFailure(call: Call, e: okio.IOException) {
Log.e("MangaDex", "Error trying to POST report to MD@Home: ${e.message}")
}
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
Log.e("MangaDex", "Error trying to POST report to MD@Home: HTTP error ${response.code}")
}
response.close()
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More