|
| 1 | +package eu.kanade.tachiyomi.animeextension.en.av1encodes |
| 2 | + |
| 3 | +import org.jsoup.Jsoup |
| 4 | +import org.jsoup.nodes.Element |
| 5 | + |
| 6 | +internal fun extractCleanTitle(raw: String): String { |
| 7 | + var cleaned = raw.replace(Regex("""\s*·\s*\d+\s*downloads?.*""", RegexOption.IGNORE_CASE), "") |
| 8 | + cleaned = cleaned.replace(Regex("""^\[[a-zA-Z0-9_\-]+]\s*"""), "") |
| 9 | + cleaned = cleaned.replace(Regex("""\s*\[\d{3,4}p].*""", RegexOption.IGNORE_CASE), "") |
| 10 | + cleaned = cleaned.replace(Regex("""\.(mkv|mp4)$""", RegexOption.IGNORE_CASE), "") |
| 11 | + return cleaned.trim() |
| 12 | +} |
| 13 | + |
| 14 | +internal fun getListImageUrl(anchor: Element, baseUrl: String): String? { |
| 15 | + val img = anchor.selectFirst("img") |
| 16 | + if (img != null) { |
| 17 | + val url = img.attr("abs:data-src").ifBlank { img.attr("abs:data-lazy-src") } |
| 18 | + .ifBlank { img.attr("abs:src") } |
| 19 | + if (url.isNotBlank()) return url |
| 20 | + } |
| 21 | + |
| 22 | + var bg = extractBg(anchor, baseUrl) |
| 23 | + if (bg != null) return bg |
| 24 | + |
| 25 | + for (child in anchor.allElements) { |
| 26 | + bg = extractBg(child, baseUrl) |
| 27 | + if (bg != null) return bg |
| 28 | + } |
| 29 | + return null |
| 30 | +} |
| 31 | + |
| 32 | +internal fun extractBg(el: Element, baseUrl: String): String? { |
| 33 | + val style = el.attr("style") |
| 34 | + if (style.contains("background", ignoreCase = true)) { |
| 35 | + val match = Regex("""url\(['"]?(.*?)['"]?\)""").find(style) |
| 36 | + if (match != null && match.groupValues[1].isNotBlank()) { |
| 37 | + val url = match.groupValues[1] |
| 38 | + return if (url.startsWith("http")) url else "$baseUrl/${url.removePrefix("/")}" |
| 39 | + } |
| 40 | + } |
| 41 | + return null |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Extracts the X-DDL-Token from the episode page's inline JavaScript. |
| 46 | + * |
| 47 | + * The token always appears as one of: |
| 48 | + * 'X-DDL-Token': "VALUE" (fetch header object literal) |
| 49 | + * ddl_token = "VALUE" (variable assignment) |
| 50 | + * |
| 51 | + * Broader fallback patterns (data-token, bare "token" key, any *Token variable) |
| 52 | + * were removed because pattern 5 in particular matched the ?token= query param |
| 53 | + * found in episode download hrefs on the same page, silently returning the |
| 54 | + * wrong value and causing /get_ddl/ calls to fail. |
| 55 | + */ |
| 56 | +internal fun extractDdlToken(html: String): String? { |
| 57 | + val patterns = listOf( |
| 58 | + // 'X-DDL-Token': "VALUE" or "X-DDL-Token": "VALUE" |
| 59 | + Regex("""['"]X-DDL-Token['"]\s*:\s*['"]([A-Za-z0-9+/=_\-]+)['"]"""), |
| 60 | + // ddl_token = "VALUE" / ddltoken = "VALUE" / ddl-token: "VALUE" |
| 61 | + Regex("""ddl[_\-]?token['"\s]*[=:]\s*['"]([A-Za-z0-9+/=_\-]+)['"]""", RegexOption.IGNORE_CASE), |
| 62 | + ) |
| 63 | + for (pattern in patterns) { |
| 64 | + val match = pattern.find(html) |
| 65 | + if (match != null) return match.groupValues[1] |
| 66 | + } |
| 67 | + return null |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Parses the /episodes/{slug}/{season}/{quality} HTML response and returns |
| 72 | + * a list of [EpisodeItem]s. |
| 73 | + * |
| 74 | + * Target structure: |
| 75 | + * ```html |
| 76 | + * <div class="episode-item"> |
| 77 | + * <a href="/episode/attack-on-titan-s01e01-1080p"> |
| 78 | + * <span class="episode-label">Episode 1</span> |
| 79 | + * <span class="audio-badge">Dual Audio</span> |
| 80 | + * </a> |
| 81 | + * </div> |
| 82 | + * ``` |
| 83 | + * |
| 84 | + * Falls back to any <a> whose href contains "/episode/" if the structured |
| 85 | + * class is absent. |
| 86 | + */ |
| 87 | +internal fun parseEpisodeItems(html: String): List<EpisodeItem> { |
| 88 | + val doc = Jsoup.parse(html) |
| 89 | + val items = mutableListOf<EpisodeItem>() |
| 90 | + |
| 91 | + // Primary path: strict .episode-item divs |
| 92 | + val containers = doc.select("div.episode-item, [class~=episode-item]") |
| 93 | + if (containers.isNotEmpty()) { |
| 94 | + for (div in containers) { |
| 95 | + val a = div.selectFirst("a[href]") ?: continue |
| 96 | + val href = a.attr("href").takeIf { it.isNotBlank() } ?: continue |
| 97 | + val label = div.selectFirst("span.episode-label, [class~=episode-label]")?.text()?.trim() |
| 98 | + ?: a.text().trim() |
| 99 | + val audio = div.selectFirst("span.audio-badge, [class~=audio-badge]")?.text()?.trim() ?: "" |
| 100 | + val num = Regex("""\d+""").find(label)?.value?.toIntOrNull() ?: items.size + 1 |
| 101 | + items.add(EpisodeItem(num = num, label = label, audio = audio, href = href)) |
| 102 | + } |
| 103 | + return items |
| 104 | + } |
| 105 | + |
| 106 | + // Fallback: any anchor pointing to an episode detail page |
| 107 | + for (a in doc.select("a[href*='/episode/']")) { |
| 108 | + val href = a.attr("href").takeIf { it.isNotBlank() } ?: continue |
| 109 | + val label = a.selectFirst("[class~=episode-label]")?.text()?.trim() |
| 110 | + ?: a.text().trim() |
| 111 | + val audio = a.selectFirst("[class~=audio-badge]")?.text()?.trim() ?: "" |
| 112 | + val num = Regex("""\d+""").find(label)?.value?.toIntOrNull() ?: items.size + 1 |
| 113 | + items.add(EpisodeItem(num = num, label = label, audio = audio, href = href)) |
| 114 | + } |
| 115 | + return items |
| 116 | +} |
| 117 | + |
| 118 | +/** |
| 119 | + * Extracts the decoded .mkv filename from a /download/…/filename.mkv?token= URL. |
| 120 | + * Used when episode.url is already a direct download link (Path A in getVideoList). |
| 121 | + * |
| 122 | + * Example input: |
| 123 | + * /download/demon-slayer/movie/1920%20x%201080/%5BS01%5D%20Demon%20Slayer%20%5B1080p%5D.mkv?token=… |
| 124 | + * Returns: |
| 125 | + * [S01] Demon Slayer [1080p].mkv |
| 126 | + */ |
| 127 | +internal fun mkvFilenameFromDownloadUrl(downloadUrl: String): String? { |
| 128 | + val path = downloadUrl.substringBefore("?").trimEnd('/') |
| 129 | + val segment = path.substringAfterLast("/") |
| 130 | + if (!segment.endsWith(".mkv", ignoreCase = true)) return null |
| 131 | + return try { |
| 132 | + java.net.URLDecoder.decode(segment, "UTF-8") |
| 133 | + } catch (_: Exception) { |
| 134 | + segment |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +/** |
| 139 | + * Scans the episode page HTML for any anchor whose href contains a /download/ path |
| 140 | + * with a .mkv file segment, then returns the URL-decoded .mkv filename. |
| 141 | + * |
| 142 | + * The site embeds links like: |
| 143 | + * /download/{slug}/{season}/{resolution}/[S01-E04] Title [1080p] [Sub].mkv?token=… |
| 144 | + * |
| 145 | + * We extract the last path segment (before the query string) and decode it, |
| 146 | + * giving us exactly the filename that /get_ddl/ expects — regardless of resolution. |
| 147 | + * If multiple resolutions are present (1080p, 720p, …) we return the first one found; |
| 148 | + * the API response contains all available links anyway. |
| 149 | + */ |
| 150 | +internal fun extractMkvFilenameFromHtml(html: String): String? { |
| 151 | + val doc = Jsoup.parse(html) |
| 152 | + // Match any anchor whose href has /download/ and ends with .mkv (before query) |
| 153 | + val downloadHref = doc.select("a[href*='/download/']") |
| 154 | + .map { it.attr("href") } |
| 155 | + .firstOrNull { href -> |
| 156 | + val path = href.substringBefore("?") |
| 157 | + path.endsWith(".mkv", ignoreCase = true) |
| 158 | + } |
| 159 | + ?: return null |
| 160 | + |
| 161 | + val path = downloadHref.substringBefore("?").trimEnd('/') |
| 162 | + val segment = path.substringAfterLast("/") |
| 163 | + return try { |
| 164 | + java.net.URLDecoder.decode(segment, "UTF-8") |
| 165 | + } catch (_: Exception) { |
| 166 | + segment |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +/** |
| 171 | + * Extracts the filename segment that the /get_ddl/ API expects from an |
| 172 | + * episode detail page URL. |
| 173 | + * |
| 174 | + * Algorithm: |
| 175 | + * 1. Unescape \? → ? and \& → & |
| 176 | + * 2. Drop query string |
| 177 | + * 3. Take the last non-empty path segment |
| 178 | + * 4. Drop everything from '\' onward (Windows path safety) |
| 179 | + * 5. URL-decode the result |
| 180 | + */ |
| 181 | +internal fun filenameFromPageUrl(pageUrl: String): String { |
| 182 | + val unescaped = pageUrl.replace("\\?", "?").replace("\\&", "&") |
| 183 | + val path = unescaped.substringBefore("?") |
| 184 | + val segment = path.trimEnd('/').substringAfterLast("/") |
| 185 | + val noWin = segment.substringBefore("\\") |
| 186 | + return try { |
| 187 | + java.net.URLDecoder.decode(noWin, "UTF-8") |
| 188 | + } catch (_: Exception) { |
| 189 | + noWin |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +internal fun buildEpisodeLabel(item: EpisodeItem, season: String): String { |
| 194 | + val base = if (item.label.isNotBlank()) item.label else "Episode ${item.num}" |
| 195 | + val audioTag = item.audio.ifBlank { null } |
| 196 | + val seasonPrefix = if (season != "1" && season.isNotBlank()) "Season $season " else "" |
| 197 | + return "$seasonPrefix$base${if (audioTag != null) " [$audioTag]" else ""}" |
| 198 | +} |
0 commit comments