|
| 1 | +import { fetchApi } from '@libs/fetch'; |
| 2 | +import { Plugin } from '@/types/plugin'; |
| 3 | +import { Filters, FilterTypes } from '@libs/filterInputs'; |
| 4 | +import { load as loadCheerio } from 'cheerio'; |
| 5 | +import { defaultCover } from '@libs/defaultCover'; |
| 6 | +import { NovelStatus } from '@libs/novelStatus'; |
| 7 | + |
| 8 | +const PAGE_SIZE = 20; |
| 9 | +const SEARCH_PAGE_SIZE = 100; |
| 10 | +// WordPress categories used by the site. |
| 11 | +const CATEGORY_LIGHT_NOVEL = 28; |
| 12 | +const CATEGORY_WEB_NOVEL = 13; |
| 13 | +// Only some novels can be read on the site; the others are PDF/EPUB downloads. |
| 14 | +// Searching the post content for the chapter URLs finds the readable ones. |
| 15 | +const READABLE_MARKER = 'capitulo-online'; |
| 16 | +// "Atelier Tanaka Novela ligera en Español", "Arioto - Novela Ligera +18 en Español" |
| 17 | +const TITLE_SUFFIX = |
| 18 | + /\s*[-–—]?\s*Novela(?:\s+(?:ligera|web))?(?:\s*\+\s*18)?\s+en\s+espa[ñn]ol\s*$/i; |
| 19 | +const SITE_NAME_SUFFIX = /\s*[-–—|]\s*MiraiK\s*$/i; |
| 20 | + |
| 21 | +type RestPost = { |
| 22 | + link: string; |
| 23 | + title: { rendered: string }; |
| 24 | + _embedded?: { |
| 25 | + 'wp:featuredmedia'?: { |
| 26 | + source_url?: string; |
| 27 | + media_details?: { sizes?: { medium?: { source_url?: string } } }; |
| 28 | + }[]; |
| 29 | + }; |
| 30 | +}; |
| 31 | + |
| 32 | +class MiraiKNovelsPlugin implements Plugin.PluginBase { |
| 33 | + id = 'miraiknovels'; |
| 34 | + name = 'MiraiK Novels'; |
| 35 | + icon = 'src/es/miraiknovels/icon.png'; |
| 36 | + site = 'https://miraik.nextnovels.com'; |
| 37 | + version = '1.0.0'; |
| 38 | + |
| 39 | + filters = { |
| 40 | + type: { |
| 41 | + label: 'Tipo', |
| 42 | + value: 'all', |
| 43 | + options: [ |
| 44 | + { label: 'Todas', value: 'all' }, |
| 45 | + { label: 'Novela ligera', value: String(CATEGORY_LIGHT_NOVEL) }, |
| 46 | + { label: 'Novela web', value: String(CATEGORY_WEB_NOVEL) }, |
| 47 | + ], |
| 48 | + type: FilterTypes.Picker, |
| 49 | + }, |
| 50 | + order: { |
| 51 | + label: 'Ordenar por', |
| 52 | + value: 'modified', |
| 53 | + options: [ |
| 54 | + { label: 'Última actualización', value: 'modified' }, |
| 55 | + { label: 'Más recientes', value: 'date' }, |
| 56 | + { label: 'A-Z', value: 'title' }, |
| 57 | + ], |
| 58 | + type: FilterTypes.Picker, |
| 59 | + }, |
| 60 | + } satisfies Filters; |
| 61 | + |
| 62 | + private async request(url: string) { |
| 63 | + const response = await fetchApi(url); |
| 64 | + if (!response.ok) { |
| 65 | + throw Object.assign( |
| 66 | + new Error(`MiraiK Novels: HTTP ${response.status}.`), |
| 67 | + { |
| 68 | + status: response.status, |
| 69 | + }, |
| 70 | + ); |
| 71 | + } |
| 72 | + return response; |
| 73 | + } |
| 74 | + |
| 75 | + private cleanText(text: string): string { |
| 76 | + return text.replace(/\s+/g, ' ').trim(); |
| 77 | + } |
| 78 | + |
| 79 | + private decode(html: string): string { |
| 80 | + return this.cleanText(loadCheerio(`<p>${html}</p>`).text()); |
| 81 | + } |
| 82 | + |
| 83 | + private cleanTitle(title: string): string { |
| 84 | + return ( |
| 85 | + this.decode(title) |
| 86 | + .replace(SITE_NAME_SUFFIX, '') |
| 87 | + .replace(TITLE_SUFFIX, '') |
| 88 | + .trim() || title |
| 89 | + ); |
| 90 | + } |
| 91 | + |
| 92 | + private toPath(url: string): string { |
| 93 | + return new URL(url, this.site).pathname; |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Chapter links are normalised to `/capitulo-online/<slug>/`: some lists |
| 98 | + * carry tracking parameters, a missing or doubled trailing slash or a |
| 99 | + * mistyped folder ("/capitulo.../slug"). |
| 100 | + */ |
| 101 | + private chapterPath(href: string | undefined): string | undefined { |
| 102 | + if (!href) return undefined; |
| 103 | + let url: URL; |
| 104 | + try { |
| 105 | + url = new URL(href, this.site); |
| 106 | + } catch { |
| 107 | + return undefined; |
| 108 | + } |
| 109 | + if (url.origin !== this.site) return undefined; |
| 110 | + const segments = url.pathname.split('/').filter(Boolean); |
| 111 | + return segments.length > 1 && segments[0].startsWith('capitulo') |
| 112 | + ? `/${READABLE_MARKER}/${segments[segments.length - 1]}/` |
| 113 | + : undefined; |
| 114 | + } |
| 115 | + |
| 116 | + private toNovelItems(posts: RestPost[]): Plugin.NovelItem[] { |
| 117 | + return posts.map(post => { |
| 118 | + const media = post._embedded?.['wp:featuredmedia']?.[0]; |
| 119 | + return { |
| 120 | + name: this.cleanTitle(post.title.rendered), |
| 121 | + path: this.toPath(post.link), |
| 122 | + cover: |
| 123 | + media?.media_details?.sizes?.medium?.source_url || |
| 124 | + media?.source_url || |
| 125 | + defaultCover, |
| 126 | + }; |
| 127 | + }); |
| 128 | + } |
| 129 | + |
| 130 | + /** Lists novel posts that have chapters on the site (WordPress REST API). */ |
| 131 | + private async listNovels(query: string): Promise<RestPost[]> { |
| 132 | + const response = await fetchApi( |
| 133 | + `${this.site}/wp-json/wp/v2/posts?${query}&_embed=wp:featuredmedia&_fields=id,link,title,_links,_embedded`, |
| 134 | + ); |
| 135 | + // WordPress answers 400 for a page number past the last one. |
| 136 | + if (response.status === 400) return []; |
| 137 | + if (!response.ok) { |
| 138 | + throw new Error(`MiraiK Novels: HTTP ${response.status}.`); |
| 139 | + } |
| 140 | + return response.json(); |
| 141 | + } |
| 142 | + |
| 143 | + async popularNovels( |
| 144 | + pageNo: number, |
| 145 | + { |
| 146 | + showLatestNovels, |
| 147 | + filters, |
| 148 | + }: Plugin.PopularNovelsOptions<typeof this.filters>, |
| 149 | + ): Promise<Plugin.NovelItem[]> { |
| 150 | + const type = filters?.type?.value; |
| 151 | + const order = showLatestNovels ? 'modified' : filters?.order?.value; |
| 152 | + const categories = |
| 153 | + type && type !== 'all' |
| 154 | + ? type |
| 155 | + : `${CATEGORY_LIGHT_NOVEL},${CATEGORY_WEB_NOVEL}`; |
| 156 | + const orderby = order || 'modified'; |
| 157 | + const direction = orderby === 'title' ? 'asc' : 'desc'; |
| 158 | + const posts = await this.listNovels( |
| 159 | + `categories=${categories}&search=${READABLE_MARKER}&per_page=${PAGE_SIZE}&page=${pageNo}&orderby=${orderby}&order=${direction}`, |
| 160 | + ); |
| 161 | + return this.toNovelItems(posts); |
| 162 | + } |
| 163 | + |
| 164 | + async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> { |
| 165 | + const $ = loadCheerio( |
| 166 | + await (await this.request(this.resolveUrl(novelPath))).text(), |
| 167 | + ); |
| 168 | + const content = $('article .entry-content').first(); |
| 169 | + |
| 170 | + const name = |
| 171 | + this.cleanTitle( |
| 172 | + $('meta[property="og:title"]').attr('content') || $('title').text(), |
| 173 | + ) || 'Sin título'; |
| 174 | + |
| 175 | + const cover = |
| 176 | + $('meta[property="og:image"]').attr('content') || |
| 177 | + content.find('.et_pb_image_0 img').first().attr('data-src') || |
| 178 | + defaultCover; |
| 179 | + |
| 180 | + // The text module that follows a label ("Estado:", "Géneros:", "Sinópsis"). |
| 181 | + const modules = content.find('.et_pb_text_inner').toArray(); |
| 182 | + const afterLabel = (label: RegExp) => { |
| 183 | + const index = modules.findIndex(el => |
| 184 | + label.test(this.cleanText($(el).text())), |
| 185 | + ); |
| 186 | + return index >= 0 ? $(modules[index + 1]) : undefined; |
| 187 | + }; |
| 188 | + |
| 189 | + const statusText = this.cleanText( |
| 190 | + afterLabel(/^Estado\s*:?\s*$/i)?.text() || '', |
| 191 | + ); |
| 192 | + let status: string = NovelStatus.Unknown; |
| 193 | + if (/abandon|cancel|dropped/i.test(statusText)) { |
| 194 | + status = NovelStatus.Cancelled; |
| 195 | + } else if (/paus|hiato|hiatus/i.test(statusText)) { |
| 196 | + status = NovelStatus.OnHiatus; |
| 197 | + } else if (/finaliz|complet|terminad/i.test(statusText)) { |
| 198 | + status = NovelStatus.Completed; |
| 199 | + } else if (/progreso|curso/i.test(statusText)) { |
| 200 | + status = NovelStatus.Ongoing; |
| 201 | + } |
| 202 | + |
| 203 | + const genres = afterLabel(/^G[ée]neros\s*:?\s*$/i) |
| 204 | + ?.find('a') |
| 205 | + .map((_, a) => this.cleanText($(a).text())) |
| 206 | + .get() |
| 207 | + .filter(Boolean) |
| 208 | + .join(', '); |
| 209 | + |
| 210 | + const synopsis = afterLabel(/^Sin[óo]psis$/i); |
| 211 | + const summary = synopsis |
| 212 | + ? synopsis |
| 213 | + .find('p, li') |
| 214 | + .map((_, el) => this.cleanText($(el).text())) |
| 215 | + .get() |
| 216 | + .filter(Boolean) |
| 217 | + .join('\n\n') || this.cleanText(synopsis.text()) |
| 218 | + : undefined; |
| 219 | + |
| 220 | + // "Autor: X" / "Ilustrador: Y" live in the (non-chapter) details tabs. |
| 221 | + const details = content |
| 222 | + .find('.et_pb_tab_content') |
| 223 | + .toArray() |
| 224 | + .map(el => |
| 225 | + ($(el).html() || '') |
| 226 | + .replace(/<\/p>|<br\s*\/?>/gi, '\n') |
| 227 | + .replace(/<[^>]+>/g, ''), |
| 228 | + ) |
| 229 | + .join('\n'); |
| 230 | + const detail = (label: RegExp) => |
| 231 | + this.decode(label.exec(details)?.[1] || '') || undefined; |
| 232 | + const author = detail(/^\s*Autor(?:es)?\s*:\s*(.+)$/im); |
| 233 | + const artist = detail(/^\s*Ilustrador(?:es)?\s*:\s*(.+)$/im); |
| 234 | + |
| 235 | + // The "Lectura online" block has one tab per volume with the chapter links. |
| 236 | + const chapters: Plugin.ChapterItem[] = []; |
| 237 | + const seen = new Set<string>(); |
| 238 | + const readingTabs = content |
| 239 | + .find('.et_pb_tabs') |
| 240 | + .filter((_, el) => $(el).find('a[href*="/capitulo"]').length > 0) |
| 241 | + .first(); |
| 242 | + const volumes = readingTabs |
| 243 | + .find('.et_pb_tabs_controls li') |
| 244 | + .map((_, li) => this.cleanText($(li).text())) |
| 245 | + .get(); |
| 246 | + readingTabs.find('.et_pb_all_tabs > .et_pb_tab').each((index, pane) => { |
| 247 | + $(pane) |
| 248 | + .find('a[href*="/capitulo"]') |
| 249 | + .each((_, link) => { |
| 250 | + const path = this.chapterPath($(link).attr('href')); |
| 251 | + if (!path || seen.has(path)) return; |
| 252 | + seen.add(path); |
| 253 | + const title = |
| 254 | + this.cleanText($(link).text()) || |
| 255 | + decodeURIComponent(path.split('/').filter(Boolean).pop() || ''); |
| 256 | + const volume = volumes.length > 1 ? volumes[index] : ''; |
| 257 | + chapters.push({ |
| 258 | + name: volume ? `${volume} - ${title}` : title, |
| 259 | + path, |
| 260 | + }); |
| 261 | + }); |
| 262 | + }); |
| 263 | + |
| 264 | + if (!chapters.length) { |
| 265 | + throw new Error( |
| 266 | + 'MiraiK Novels: esta novela no tiene capítulos para leer en línea (el sitio solo ofrece descargas o enlaces externos).', |
| 267 | + ); |
| 268 | + } |
| 269 | + |
| 270 | + return { |
| 271 | + path: novelPath, |
| 272 | + name, |
| 273 | + cover, |
| 274 | + author, |
| 275 | + artist, |
| 276 | + genres: genres || undefined, |
| 277 | + status, |
| 278 | + summary, |
| 279 | + chapters, |
| 280 | + }; |
| 281 | + } |
| 282 | + |
| 283 | + async parseChapter(chapterPath: string): Promise<string> { |
| 284 | + const $ = loadCheerio( |
| 285 | + await (await this.request(this.resolveUrl(chapterPath))).text(), |
| 286 | + ); |
| 287 | + // The first section holds the chapter; the second one is "related posts". |
| 288 | + const section = $('article .entry-content .et_pb_section').first(); |
| 289 | + const modules = section.find('.et_pb_text_inner').toArray(); |
| 290 | + // A short first module is only the chapter heading banner, which the |
| 291 | + // chapter text repeats (or replaces) in the next module. |
| 292 | + const body = modules.length > 1 ? modules.slice(1) : modules; |
| 293 | + |
| 294 | + const chapter = loadCheerio('<div></div>'); |
| 295 | + const root = chapter('div'); |
| 296 | + for (const el of body) root.append($(el).clone()); |
| 297 | + |
| 298 | + root.find('script, style, noscript, iframe, form').remove(); |
| 299 | + root.find('img').each((_, img) => { |
| 300 | + const image = chapter(img); |
| 301 | + const lazy = image.attr('data-src'); |
| 302 | + if (lazy) image.attr('src', lazy); |
| 303 | + // Use the original upload instead of the generated "-201x300" thumbnail. |
| 304 | + const src = image.attr('src'); |
| 305 | + if (src && /^https?:/.test(src)) { |
| 306 | + image.attr('src', src.replace(/-\d+x\d+(\.\w+)$/, '$1')); |
| 307 | + } |
| 308 | + }); |
| 309 | + // Footnote markers link to anchors that do not exist in the app: unwrap |
| 310 | + // the links but keep their contents (text, formatting and linked images). |
| 311 | + root.find('a').each((_, link) => { |
| 312 | + chapter(link).replaceWith(chapter(link).contents()); |
| 313 | + }); |
| 314 | + root.find('*').each((_, el) => { |
| 315 | + const element = chapter(el); |
| 316 | + const keep = element.is('img') ? ['src', 'alt'] : []; |
| 317 | + for (const attr of Object.keys(el.attribs || {})) { |
| 318 | + if (!keep.includes(attr)) element.removeAttr(attr); |
| 319 | + } |
| 320 | + }); |
| 321 | + root.find('p').each((_, p) => { |
| 322 | + const paragraph = chapter(p); |
| 323 | + if (!this.cleanText(paragraph.text()) && !paragraph.find('img').length) { |
| 324 | + paragraph.remove(); |
| 325 | + } |
| 326 | + }); |
| 327 | + |
| 328 | + const html = root.html()?.trim() || ''; |
| 329 | + if (this.cleanText(loadCheerio(html).text()).length < 100) { |
| 330 | + throw new Error('MiraiK Novels: no se encontró el texto del capítulo.'); |
| 331 | + } |
| 332 | + return html; |
| 333 | + } |
| 334 | + |
| 335 | + async searchNovels( |
| 336 | + searchTerm: string, |
| 337 | + pageNo: number, |
| 338 | + ): Promise<Plugin.NovelItem[]> { |
| 339 | + const term = searchTerm.trim(); |
| 340 | + if (!term) return []; |
| 341 | + const categories = `${CATEGORY_LIGHT_NOVEL},${CATEGORY_WEB_NOVEL}`; |
| 342 | + const found = await this.listNovels( |
| 343 | + `categories=${categories}&search=${encodeURIComponent(term)}&per_page=${SEARCH_PAGE_SIZE}&page=${pageNo}`, |
| 344 | + ); |
| 345 | + // Only keep novels that can be read online (see READABLE_MARKER). |
| 346 | + let readable: Set<string> | undefined; |
| 347 | + try { |
| 348 | + const posts = await this.listNovels( |
| 349 | + `categories=${categories}&search=${READABLE_MARKER}&per_page=${SEARCH_PAGE_SIZE}`, |
| 350 | + ); |
| 351 | + readable = new Set(posts.map(post => post.link)); |
| 352 | + } catch { |
| 353 | + readable = undefined; |
| 354 | + } |
| 355 | + return this.toNovelItems( |
| 356 | + readable ? found.filter(post => readable!.has(post.link)) : found, |
| 357 | + ); |
| 358 | + } |
| 359 | + |
| 360 | + resolveUrl = (path: string) => new URL(path, this.site).href; |
| 361 | +} |
| 362 | + |
| 363 | +export default new MiraiKNovelsPlugin(); |
0 commit comments