AnimeHttpSource.kt
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/AnimeHttpSource.kt
1package eu.kanade.tachiyomi.animesource.online23import eu.kanade.tachiyomi.animesource.AnimeCatalogueSource4import eu.kanade.tachiyomi.animesource.model.AnimeFilterList5import eu.kanade.tachiyomi.animesource.model.AnimesPage6import eu.kanade.tachiyomi.animesource.model.SAnime7import eu.kanade.tachiyomi.animesource.model.SEpisode8import eu.kanade.tachiyomi.animesource.model.Video9import eu.kanade.tachiyomi.network.GET10import eu.kanade.tachiyomi.network.NetworkHelper11import eu.kanade.tachiyomi.network.asObservableSuccess12import eu.kanade.tachiyomi.network.awaitSuccess13import eu.kanade.tachiyomi.network.newCachelessCallWithProgress14import eu.kanade.tachiyomi.util.lang.awaitSingle15import okhttp3.Headers16import okhttp3.OkHttpClient17import okhttp3.Request18import okhttp3.Response19import rx.Observable20import uy.kohesive.injekt.injectLazy21import java.net.URI22import java.net.URISyntaxException23import java.security.MessageDigest2425/**26 * A simple implementation for sources from a website.27 */28@Suppress("unused")29abstract class AnimeHttpSource : AnimeCatalogueSource {30 /**31 * Network service.32 */33 val network: NetworkHelper by injectLazy()3435 /**36 * Base url of the website without the trailing slash, like: http://mysite.com37 */38 abstract val baseUrl: String3940 /**41 * Version id used to generate the source id. If the site completely changes and urls are42 * incompatible, you may increase this value and it'll be considered as a new source.43 */44 open val versionId = 14546 /**47 * ID of the source. By default it uses a generated id using the first 16 characters (64 bits)48 * of the MD5 of the string `"${name.lowercase()}/$lang/$versionId"`.49 *50 * The ID is generated by the [generateId] function, which can be reused if needed51 * to generate outdated IDs for cases where the source name or language needs to52 * be changed but migrations can be avoided.53 *54 * Note: the generated ID sets the sign bit to `0`.55 */56 override val id by lazy { generateId(name, lang, versionId) }5758 /**59 * Headers used for requests.60 */61 val headers: Headers by lazy { headersBuilder().build() }6263 /**64 * Default network client for doing requests.65 */66 open val client: OkHttpClient67 get() = network.client6869 /**70 * Generates a unique ID for the source based on the provided [name], [lang] and71 * [versionId]. It will use the first 16 characters (64 bits) of the MD5 of the string72 * `"${name.lowercase()}/$lang/$versionId"`.73 *74 * Note: the generated ID sets the sign bit to `0`.75 *76 * Can be used to generate outdated IDs, such as when the source name or language77 * needs to be changed but migrations can be avoided.78 *79 * @since extensions-lib 1580 * @param name [String] the name of the source81 * @param lang [String] the language of the source82 * @param versionId [Int] the version ID of the source83 * @return a unique ID for the source84 */85 @Suppress("MemberVisibilityCanBePrivate")86 protected fun generateId(87 name: String,88 lang: String,89 versionId: Int,90 ): Long {91 val key = "${name.lowercase()}/$lang/$versionId"92 val bytes = MessageDigest.getInstance("MD5").digest(key.toByteArray())93 return (0..7).map { bytes[it].toLong() and 0xff shl 8 * (7 - it) }.reduce(Long::or) and Long.MAX_VALUE94 }9596 /**97 * Headers builder for requests. Implementations can override this method for custom headers.98 */99 protected open fun headersBuilder() =100 Headers.Builder().apply {101 add("User-Agent", network.defaultUserAgentProvider())102 }103104 /**105 * Visible name of the source.106 */107 override fun toString() = "$name (${lang.uppercase()})"108109 /**110 * Returns an observable containing a page with a list of anime. Normally it's not needed to111 * override this method.112 *113 * @param page the page number to retrieve.114 */115 @Deprecated(116 "Use the non-RxJava API instead",117 ReplaceWith("getPopularAnime"),118 )119 override fun fetchPopularAnime(page: Int): Observable<AnimesPage> =120 client121 .newCall(popularAnimeRequest(page))122 .asObservableSuccess()123 .map(::popularAnimeParse)124125 /**126 * Returns the request for the popular anime given the page.127 *128 * @param page the page number to retrieve.129 */130 protected abstract fun popularAnimeRequest(page: Int): Request131132 /**133 * Parses the response from the site and returns a [AnimesPage] object.134 *135 * @param response the response from the site.136 */137 protected abstract fun popularAnimeParse(response: Response): AnimesPage138139 /**140 * Returns an observable containing a page with a list of anime. Normally it's not needed to141 * override this method.142 *143 * @param page the page number to retrieve.144 * @param query the search query.145 * @param filters the list of filters to apply.146 */147 @Deprecated(148 "Use the non-RxJava API instead",149 ReplaceWith("getSearchAnime"),150 )151 override fun fetchSearchAnime(152 page: Int,153 query: String,154 filters: AnimeFilterList,155 ): Observable<AnimesPage> =156 Observable157 .defer {158 try {159 client.newCall(searchAnimeRequest(page, query, filters)).asObservableSuccess()160 } catch (e: NoClassDefFoundError) {161 // RxJava doesn't handle Errors, which tends to happen during global searches162 // if an old extension using non-existent classes is still around163 throw RuntimeException(e)164 }165 }.map(::searchAnimeParse)166167 /**168 * Returns the request for the search anime given the page.169 *170 * @param page the page number to retrieve.171 * @param query the search query.172 * @param filters the list of filters to apply.173 */174 protected abstract fun searchAnimeRequest(175 page: Int,176 query: String,177 filters: AnimeFilterList,178 ): Request179180 /**181 * Parses the response from the site and returns a [AnimesPage] object.182 *183 * @param response the response from the site.184 */185 protected abstract fun searchAnimeParse(response: Response): AnimesPage186187 /**188 * Returns an observable containing a page with a list of latest anime updates.189 *190 * @param page the page number to retrieve.191 */192 @Deprecated(193 "Use the non-RxJava API instead",194 ReplaceWith("getLatestUpdates"),195 )196 override fun fetchLatestUpdates(page: Int): Observable<AnimesPage> =197 client198 .newCall(latestUpdatesRequest(page))199 .asObservableSuccess()200 .map(::latestUpdatesParse)201202 /**203 * Returns the request for latest anime given the page.204 *205 * @param page the page number to retrieve.206 */207 protected abstract fun latestUpdatesRequest(page: Int): Request208209 /**210 * Parses the response from the site and returns a [AnimesPage] object.211 *212 * @param response the response from the site.213 */214 protected abstract fun latestUpdatesParse(response: Response): AnimesPage215216 /**217 * Get the updated details for a anime.218 * Normally it's not needed to override this method.219 *220 * @param anime the anime to be updated.221 * @return the updated anime.222 */223 @Suppress("DEPRECATION")224 override suspend fun getAnimeDetails(anime: SAnime): SAnime = fetchAnimeDetails(anime).awaitSingle()225226 @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getAnimeDetails"))227 override fun fetchAnimeDetails(anime: SAnime): Observable<SAnime> =228 client229 .newCall(animeDetailsRequest(anime))230 .asObservableSuccess()231 .map { response ->232 animeDetailsParse(response).apply { initialized = true }233 }234235 /**236 * Returns the request for the details of an anime. Override only if it's needed to change the237 * url, send different headers or request method like POST.238 *239 * @param anime the anime to be updated.240 */241 open fun animeDetailsRequest(anime: SAnime): Request = GET(baseUrl + anime.url, headers)242243 /**244 * Parses the response from the site and returns the details of an anime.245 *246 * @param response the response from the site.247 */248 protected abstract fun animeDetailsParse(response: Response): SAnime249250 /**251 * Get all the available episodes for an anime.252 * Normally it's not needed to override this method.253 *254 * @param anime the anime to update.255 * @return the chapters for the manga.256 * @throws LicensedEntryItemsException if a anime is licensed and therefore no episodes are available.257 */258 @Suppress("DEPRECATION")259 override suspend fun getEpisodeList(anime: SAnime): List<SEpisode> {260 if (anime.status == SAnime.LICENSED) {261 throw LicensedEntryItemsException()262 }263264 return fetchEpisodeList(anime).awaitSingle()265 }266267 @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getEpisodeList"))268 override fun fetchEpisodeList(anime: SAnime): Observable<List<SEpisode>> =269 if (anime.status != SAnime.LICENSED) {270 client271 .newCall(episodeListRequest(anime))272 .asObservableSuccess()273 .map(::episodeListParse)274 } else {275 Observable.error(Exception(LicensedEntryItemsException()))276 }277278 /**279 * Returns the request for updating the episode list. Override only if it's needed to override280 * the url, send different headers or request method like POST.281 *282 * @param anime the anime to look for episodes.283 */284 protected open fun episodeListRequest(anime: SAnime): Request = GET(baseUrl + anime.url, headers)285286 /**287 * Parses the response from the site and returns a list of episodes.288 *289 * @param response the response from the site.290 */291 protected abstract fun episodeListParse(response: Response): List<SEpisode>292293 /**294 * Parses the response from the site and returns a SEpisode Object.295 *296 * @param response the response from the site.297 */298 protected abstract fun episodeVideoParse(response: Response): SEpisode299300 /**301 * Get the list of videos a episode has. Videos should be returned302 * in the expected order; the index is ignored.303 *304 * @param episode the episode.305 * @return the videos for the episode.306 */307 @Suppress("DEPRECATION")308 override suspend fun getVideoList(episode: SEpisode): List<Video> = fetchVideoList(episode).awaitSingle()309310 @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getVideoList"))311 override fun fetchVideoList(episode: SEpisode): Observable<List<Video>> =312 client313 .newCall(videoListRequest(episode))314 .asObservableSuccess()315 .map { response ->316 videoListParse(response).sort()317 }318319 /**320 * Returns the request for getting the episode link. Override only if it's needed to override321 * the url, send different headers or request method like POST.322 *323 * @param episode the episode to look for links.324 */325 protected open fun videoListRequest(episode: SEpisode): Request = GET(baseUrl + episode.url, headers)326327 /**328 * Parses the response from the site and returns a list of pages.329 *330 * @param response the response from the site.331 */332 protected abstract fun videoListParse(response: Response): List<Video>333334 /**335 * Sorts the video list. Override this according to the user's preference.336 */337 protected open fun List<Video>.sort(): List<Video> = this338339 /**340 * Returns an observable with the page containing the source url of the image. If there's any341 * error, it will return null instead of throwing an exception.342 *343 * @since extensions-lib 15344 * @param video the video whose source image has to be fetched.345 */346 @Suppress("DEPRECATION")347 open suspend fun getVideoUrl(video: Video): String = fetchVideoUrl(video).awaitSingle()348349 @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getVideoUrl"))350 open fun fetchVideoUrl(video: Video): Observable<String> =351 client352 .newCall(videoUrlRequest(video))353 .asObservableSuccess()354 .map(::videoUrlParse)355356 /**357 * Returns the request for getting the url to the source image. Override only if it's needed to358 * override the url, send different headers or request method like POST.359 *360 * @param video the chapter whose page list has to be fetched361 */362 protected open fun videoUrlRequest(video: Video): Request = GET(video.url, headers)363364 /**365 * Parses the response from the site and returns the absolute url to the source image.366 *367 * @param response the response from the site.368 */369 protected abstract fun videoUrlParse(response: Response): String370371 /**372 * Returns the response of the source video.373 * Typically does not need to be overridden.374 *375 * @since extensions-lib 15376 * @param video the video whose source video has to be downloaded.377 */378 open suspend fun getVideo(video: Video): Response =379 client380 .newCachelessCallWithProgress(videoRequest(video), video)381 .awaitSuccess()382383 /**384 * Returns the request for getting the source image. Override only if it's needed to override385 * the url, send different headers or request method like POST.386 *387 * @param video the video whose link has to be fetched388 */389 protected open fun videoRequest(390 video: Video,391 bytes: Long = 0L,392 ): Request {393 val headers = video.headers ?: headers394 val newHeaders =395 if (bytes > 0L) {396 headers.newBuilder().add("Range", "bytes=$bytes-").build()397 } else {398 headers399 }400 return GET(video.videoUrl ?: video.url, newHeaders)401 }402403 /**404 * Assigns the url of the episode without the scheme and domain. It saves some redundancy from405 * database and the urls could still work after a domain change.406 *407 * @param url the full url to the episode.408 */409 fun SEpisode.setUrlWithoutDomain(url: String) {410 this.url = getUrlWithoutDomain(url)411 }412413 /**414 * Assigns the url of the anime without the scheme and domain. It saves some redundancy from415 * database and the urls could still work after a domain change.416 *417 * @param url the full url to the anime.418 */419 fun SAnime.setUrlWithoutDomain(url: String) {420 this.url = getUrlWithoutDomain(url)421 }422423 /**424 * Returns the url of the given string without the scheme and domain.425 *426 * @param orig the full url.427 */428 private fun getUrlWithoutDomain(orig: String): String =429 try {430 val uri = URI(orig)431 var out = uri.path432 if (uri.query != null) {433 out += "?" + uri.query434 }435 if (uri.fragment != null) {436 out += "#" + uri.fragment437 }438 out439 } catch (e: URISyntaxException) {440 orig441 }442443 /**444 * Returns the url of the provided anime445 *446 * @since extensions-lib 14447 * @param anime the anime448 * @return url of the anime449 */450 open fun getAnimeUrl(anime: SAnime): String = animeDetailsRequest(anime).url.toString()451452 /**453 * Returns the url of the provided episode454 *455 * @since extensions-lib 14456 * @param episode the episode457 * @return url of the episode458 */459 open fun getEpisodeUrl(episode: SEpisode): String = episode.url.toString()460461 /**462 * Called before inserting a new episode into database. Use it if you need to override episode463 * fields, like the title or the episode number. Do not change anything to [anime].464 *465 * @param episode the episode to be added.466 * @param anime the anime of the episode.467 */468 open fun prepareNewEpisode(469 episode: SEpisode,470 anime: SAnime,471 ) {}472473 /**474 * Returns the list of filters for the source.475 */476 override fun getFilterList() = AnimeFilterList()477}478479class LicensedEntryItemsException : Exception("Licensed - No items to show")480