|
| 1 | +import { fetchApi } from '@libs/fetch'; |
| 2 | +import { Plugin } from '@/types/plugin'; |
| 3 | +import { load as loadCheerio } from 'cheerio'; |
| 4 | +import { defaultCover } from '@libs/defaultCover'; |
| 5 | +import { NovelStatus } from '@libs/novelStatus'; |
| 6 | + |
| 7 | +// The site is a Blogger blog: the catalogue is a static page, every novel is a |
| 8 | +// static page whose body holds the synopsis and the chapter links, and every |
| 9 | +// chapter is a regular post (/YYYY/MM/slug.html). |
| 10 | +const SITE_HOST = /^animeshoy12\.blogspot\./i; |
| 11 | +const CATALOGUE_PATH = '/p/lista-de-novelas.html'; |
| 12 | +const NOVEL_PATH = /^\/p\/[^/]+\.html$/; |
| 13 | +const CHAPTER_PATH = /^\/\d{4}\/\d{2}\/[^/]+\.html$/; |
| 14 | +// Links to posts that are not chapters (power-level guides and the like) have |
| 15 | +// no number in their text. |
| 16 | +const CHAPTER_TEXT = /\d|pr[oó]logo|ep[ií]logo|extra|especial|prefacio/i; |
| 17 | +// "Anterior - Índice - Siguiente" and the author's donation/sharing lines. |
| 18 | +const NAVIGATION = |
| 19 | + /^[\s\-–—|]*(?:anterior|[ií]ndice|siguiente)(?:[\s\-–—|]+(?:anterior|[ií]ndice|siguiente))*[\s\-–—|]*$/i; |
| 20 | +const DONATION = /patreon|esponsor|anslid/i; |
| 21 | +const SHARING = |
| 22 | + /compart(?:an|ir)(?:lo)?\s+(?:la\s+)?(?:novela|p[aá]gina)\b|compart\w*\s+(?:lo\s+)?\S*\s*ayudar[ií]a mucho|m[aá]s cap[ií]tulos\s+(?:gratis|en|:|\()|muchas gracias por todo/i; |
| 23 | +const isPromotion = (text: string): boolean => |
| 24 | + DONATION.test(text) || (text === text.toUpperCase() && SHARING.test(text)); |
| 25 | +const SEPARATOR = /^[\s\-–—_=.·|~*]*$/; |
| 26 | +// Left over at the very end of a chapter once the links are gone. |
| 27 | +const TRAILING = /^[\s\-–—_=.·|~*]*(?:tambi[eé]n\s*:?)?[\s\-–—_=.·|~*]*$/i; |
| 28 | +const SYNOPSIS_START = |
| 29 | + /^(?:[^:]{0,40}?[-–]\s*)?(?:leer\s+)?sin[oó]psis\s*\d*\s*:?\s*(.*)$/i; |
| 30 | +const SYNOPSIS_STOP = |
| 31 | + /^(?:t[ií]tulos?\b|otros\s+t[ií]tulos|nota\b|todos\s+los\s+vol|vol[uú]menes?\b|volumen\b|sin[oó]psis\s*\d|del mismo autor|g[eé]neros?\s*:|autor\s*:|estado\s*:|tipo\s*:)/i; |
| 32 | +const LABEL = /^(autor|estado|g[eé]neros?|tipo)\s*:\s*(.*)$/i; |
| 33 | +// Two or more consecutive empty blocks (spacing between paragraphs). |
| 34 | +const BLANK_BLOCKS = |
| 35 | + /(?:<(?:div|p)[^>]*>(?:<(?:span|b|i|u)[^>]*>)*(?:<br\s*\/?>| |\s)*(?:<\/(?:span|b|i|u)>)*<\/(?:div|p)>\s*){2,}/gi; |
| 36 | +const SUMMARY_LIMIT = 3000; |
| 37 | +const COVER_SIZE = 's400'; |
| 38 | + |
| 39 | +class NovelasTopcur implements Plugin.PluginBase { |
| 40 | + id = 'novelastopcur'; |
| 41 | + name = 'Novelas Topcur'; |
| 42 | + site = 'https://animeshoy12.blogspot.com'; |
| 43 | + icon = 'src/es/novelastopcur/icon.png'; |
| 44 | + version = '1.0.0'; |
| 45 | + |
| 46 | + private async request(path: string) { |
| 47 | + const response = await fetchApi(this.resolveUrl(path)); |
| 48 | + if (!response.ok) { |
| 49 | + throw new Error(`Novelas Topcur: HTTP ${response.status}.`); |
| 50 | + } |
| 51 | + return response; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Loads a page or post through Blogger's public JSON feed (far less likely to |
| 56 | + * be rate limited than the HTML) and rebuilds the markup the parsers expect. |
| 57 | + * Falls back once to the HTML page when the feed has no usable entry. |
| 58 | + */ |
| 59 | + private async document(path: string) { |
| 60 | + try { |
| 61 | + const kind = path.startsWith('/p/') ? 'pages' : 'posts'; |
| 62 | + const response = await fetchApi( |
| 63 | + `${this.site}/feeds/${kind}/default?alt=json&path=${encodeURIComponent(path)}`, |
| 64 | + ); |
| 65 | + if (response.ok) { |
| 66 | + const entry = (await response.json())?.feed?.entry?.[0]; |
| 67 | + const content: string | undefined = entry?.content?.$t; |
| 68 | + if (content) { |
| 69 | + const title = String(entry.title?.$t || '') |
| 70 | + .replace(/&/g, '&') |
| 71 | + .replace(/</g, '<') |
| 72 | + .replace(/>/g, '>'); |
| 73 | + return loadCheerio( |
| 74 | + `<h3 class="post-title">${title}</h3><div class="post-body">${content}</div>`, |
| 75 | + ); |
| 76 | + } |
| 77 | + } |
| 78 | + } catch { |
| 79 | + // Use the HTML page below. |
| 80 | + } |
| 81 | + return loadCheerio(await (await this.request(path)).text()); |
| 82 | + } |
| 83 | + |
| 84 | + private clean(text: string): string { |
| 85 | + return text.replace(/[\s\u00a0]+/g, ' ').trim(); |
| 86 | + } |
| 87 | + |
| 88 | + /** Turns an href into a site-relative path, or undefined for other sites. */ |
| 89 | + private sitePath(href: string | undefined): string | undefined { |
| 90 | + if (!href) return undefined; |
| 91 | + try { |
| 92 | + const url = new URL(href, this.site); |
| 93 | + return SITE_HOST.test(url.hostname) ? url.pathname : undefined; |
| 94 | + } catch { |
| 95 | + return undefined; |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + /** Blogger serves covers at any size: ask for a sharper one than the grid's. */ |
| 100 | + private cover(src: string | undefined): string { |
| 101 | + if (!src || src.startsWith('data:') || /notavailable/i.test(src)) { |
| 102 | + return defaultCover; |
| 103 | + } |
| 104 | + return src |
| 105 | + .replace(/=(?:[ws]\d+(?:-h\d+)?)(?:-[a-z0-9]+)*$/i, `=${COVER_SIZE}`) |
| 106 | + .replace(/\/(?:w\d+-h\d+|s\d+)(?:-[a-z0-9]+)*\//i, `/${COVER_SIZE}/`); |
| 107 | + } |
| 108 | + |
| 109 | + /** "Nano Machine Novela Español" -> "Nano Machine" */ |
| 110 | + private title(text: string): string { |
| 111 | + return this.clean(text) |
| 112 | + .replace(/^\d+\s*\.\s*/, '') |
| 113 | + .replace(/\s*\bnovela(?:\s+espa[ñn]ol)?\s*$/i, '') |
| 114 | + .replace(/^lista de cap[ií]tulos\s+mga\b/i, 'Martial God Asura') |
| 115 | + .trim(); |
| 116 | + } |
| 117 | + |
| 118 | + /** "NANO MACHINE" -> "Nano Machine"; mixed-case titles are left alone. */ |
| 119 | + private titleCase(text: string): string { |
| 120 | + if (text.length < 5 || text !== text.toUpperCase()) return text; |
| 121 | + return text |
| 122 | + .toLowerCase() |
| 123 | + .replace( |
| 124 | + /(^|\s)(\S)/g, |
| 125 | + (_, space, letter) => space + letter.toUpperCase(), |
| 126 | + ); |
| 127 | + } |
| 128 | + |
| 129 | + private normalize(text: string): string { |
| 130 | + return text.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, ''); |
| 131 | + } |
| 132 | + |
| 133 | + /** |
| 134 | + * The catalogue is one page: every novel appears as a numbered link with its |
| 135 | + * cover image linked to the same novel page, in no fixed order. |
| 136 | + */ |
| 137 | + private async catalogue(): Promise<Plugin.NovelItem[]> { |
| 138 | + const $ = await this.document(CATALOGUE_PATH); |
| 139 | + const entries = new Map< |
| 140 | + string, |
| 141 | + { parts: string[]; cover: string | undefined } |
| 142 | + >(); |
| 143 | + $('.post-body a[href]').each((_, link) => { |
| 144 | + const path = this.sitePath($(link).attr('href')); |
| 145 | + if (!path || !NOVEL_PATH.test(path) || path === CATALOGUE_PATH) return; |
| 146 | + const entry = entries.get(path) || { parts: [], cover: undefined }; |
| 147 | + const text = this.title($(link).text()); |
| 148 | + if (text && !entry.parts.includes(text)) entry.parts.push(text); |
| 149 | + entry.cover ||= $(link).find('img').first().attr('src'); |
| 150 | + entries.set(path, entry); |
| 151 | + }); |
| 152 | + const novels: Plugin.NovelItem[] = []; |
| 153 | + entries.forEach((entry, path) => { |
| 154 | + const name = this.title(entry.parts.join(' ')); |
| 155 | + if (!name) return; |
| 156 | + novels.push({ name, path, cover: this.cover(entry.cover) }); |
| 157 | + }); |
| 158 | + return novels; |
| 159 | + } |
| 160 | + |
| 161 | + async popularNovels(pageNo: number): Promise<Plugin.NovelItem[]> { |
| 162 | + // The catalogue is a single page without pagination. |
| 163 | + if (pageNo > 1) return []; |
| 164 | + return this.catalogue(); |
| 165 | + } |
| 166 | + |
| 167 | + /** Plain-text lines of an HTML fragment, one per block or line break. */ |
| 168 | + private lines(fragment: string): string[] { |
| 169 | + const text = loadCheerio( |
| 170 | + fragment |
| 171 | + .replace(/<br\s*\/?>/gi, '\n') |
| 172 | + .replace(/<\/(?:div|p|li|h\d|tr)>/gi, '\n'), |
| 173 | + ).text(); |
| 174 | + return text |
| 175 | + .split('\n') |
| 176 | + .map(line => this.clean(line)) |
| 177 | + .filter(Boolean); |
| 178 | + } |
| 179 | + |
| 180 | + private status(text: string | undefined): NovelStatus | undefined { |
| 181 | + if (!text) return undefined; |
| 182 | + if (/finaliz|complet|termin/i.test(text)) return NovelStatus.Completed; |
| 183 | + if (/paus|hiatus/i.test(text)) return NovelStatus.OnHiatus; |
| 184 | + if (/cancel|abandon/i.test(text)) return NovelStatus.Cancelled; |
| 185 | + if (/activ|en curso|emisi[oó]n|publicando/i.test(text)) { |
| 186 | + return NovelStatus.Ongoing; |
| 187 | + } |
| 188 | + return undefined; |
| 189 | + } |
| 190 | + |
| 191 | + async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> { |
| 192 | + const $ = await this.document(novelPath); |
| 193 | + const body = $('.post-body').first(); |
| 194 | + if (!body.length) { |
| 195 | + throw new Error('Novelas Topcur: the novel page has no content.'); |
| 196 | + } |
| 197 | + |
| 198 | + const isChapter = (link: ReturnType<typeof $>) => { |
| 199 | + const path = this.sitePath(link.attr('href')); |
| 200 | + return ( |
| 201 | + !!path && CHAPTER_PATH.test(path) && CHAPTER_TEXT.test(link.text()) |
| 202 | + ); |
| 203 | + }; |
| 204 | + |
| 205 | + const seen = new Set<string>(); |
| 206 | + const listed: { name: string; path: string }[] = []; |
| 207 | + body.find('a[href]').each((_, el) => { |
| 208 | + const link = $(el); |
| 209 | + if (!isChapter(link)) return; |
| 210 | + const path = this.sitePath(link.attr('href'))!; |
| 211 | + const name = this.clean(link.text()); |
| 212 | + if (!name || seen.has(path)) return; |
| 213 | + seen.add(path); |
| 214 | + listed.push({ name, path }); |
| 215 | + }); |
| 216 | + |
| 217 | + // Newer novels keep their chapters on other sites; the page only links to |
| 218 | + // them. Say so instead of presenting a truncated list as the whole novel. |
| 219 | + const elsewhere = new Set<string>(); |
| 220 | + body.find('a[href]').each((_, el) => { |
| 221 | + try { |
| 222 | + const url = new URL($(el).attr('href') || '', this.site); |
| 223 | + if ( |
| 224 | + !SITE_HOST.test(url.hostname) && |
| 225 | + /^\/novela\/|^\/\d{4}\/\d{2}\//.test(url.pathname) |
| 226 | + ) { |
| 227 | + elsewhere.add(url.hostname.replace(/^www\./i, '')); |
| 228 | + } |
| 229 | + } catch { |
| 230 | + // Ignore malformed links. |
| 231 | + } |
| 232 | + }); |
| 233 | + const hosts = Array.from(elsewhere).join(', '); |
| 234 | + if (!listed.length) { |
| 235 | + throw new Error( |
| 236 | + hosts |
| 237 | + ? `Novelas Topcur: los capítulos de esta novela están en ${hosts}, no en este blog.` |
| 238 | + : 'Novelas Topcur: no chapters were found.', |
| 239 | + ); |
| 240 | + } |
| 241 | + |
| 242 | + // Every title repeats the novel's name ("Nano Machine (Novela) Capitulo |
| 243 | + // 1"): drop the prefix shared by most chapters, but keep distinguishing |
| 244 | + // ones such as "SPECIAL MGA (Qiang Xuantian) Capitulo 11". |
| 245 | + const prefixOf = (name: string) => |
| 246 | + /^(.*?)\s*(?=\bcap[ií]tulo\b)/i.exec(name)?.[1] || ''; |
| 247 | + const counts = new Map<string, number>(); |
| 248 | + listed.forEach(({ name }) => { |
| 249 | + const prefix = prefixOf(name); |
| 250 | + if (prefix) counts.set(prefix, (counts.get(prefix) || 0) + 1); |
| 251 | + }); |
| 252 | + let commonPrefix = ''; |
| 253 | + counts.forEach((count, prefix) => { |
| 254 | + if (count > (counts.get(commonPrefix) || 0)) commonPrefix = prefix; |
| 255 | + }); |
| 256 | + const stripPrefix = (counts.get(commonPrefix) || 0) * 2 >= listed.length; |
| 257 | + |
| 258 | + const chapters: Plugin.ChapterItem[] = listed.map(({ name, path }) => { |
| 259 | + let chapterName = |
| 260 | + stripPrefix && commonPrefix && prefixOf(name) === commonPrefix |
| 261 | + ? name.slice(commonPrefix.length).trim() |
| 262 | + : name; |
| 263 | + // Some lists only link the number. |
| 264 | + if (/^\d+(?:\.\d+)?$/.test(chapterName)) { |
| 265 | + chapterName = `Capítulo ${chapterName}`; |
| 266 | + } |
| 267 | + const number = |
| 268 | + /\bcap[ií]tulo\s*(\d+(?:\.\d+)?)/i.exec(name)?.[1] || |
| 269 | + /\bC(\d+(?:\.\d+)?)\b/.exec(name)?.[1]; |
| 270 | + return { |
| 271 | + name: chapterName, |
| 272 | + path, |
| 273 | + chapterNumber: number ? Number(number) : undefined, |
| 274 | + }; |
| 275 | + }); |
| 276 | + |
| 277 | + // Everything before the first chapter link is the novel's description. |
| 278 | + const bodyHtml = body.html() || ''; |
| 279 | + const firstLink = /<a\b[^>]*href="[^"]*\/\d{4}\/\d{2}\/[^"]+"/i.exec( |
| 280 | + bodyHtml, |
| 281 | + ); |
| 282 | + const header = this.lines( |
| 283 | + firstLink ? bodyHtml.slice(0, firstLink.index) : bodyHtml, |
| 284 | + ); |
| 285 | + |
| 286 | + const labels: Record<string, string> = {}; |
| 287 | + header.forEach((line, index) => { |
| 288 | + const match = LABEL.exec(line); |
| 289 | + if (!match) return; |
| 290 | + const key = match[1].toLowerCase().replace('é', 'e'); |
| 291 | + const value = |
| 292 | + match[2] || (LABEL.test(header[index + 1]) ? '' : header[index + 1]); |
| 293 | + if (value && !labels[key]) labels[key] = value; |
| 294 | + }); |
| 295 | + |
| 296 | + let summary = ''; |
| 297 | + const start = header.findIndex(line => SYNOPSIS_START.test(line)); |
| 298 | + if (start >= 0) { |
| 299 | + const parts = [SYNOPSIS_START.exec(header[start])![1]]; |
| 300 | + for (const line of header.slice(start + 1)) { |
| 301 | + if (SYNOPSIS_STOP.test(line) || SEPARATOR.test(line)) break; |
| 302 | + parts.push(line); |
| 303 | + } |
| 304 | + summary = parts.filter(Boolean).join('\n').slice(0, SUMMARY_LIMIT).trim(); |
| 305 | + } |
| 306 | + |
| 307 | + if (hosts) { |
| 308 | + summary += `${summary ? '\n\n' : ''}Nota: los capítulos que faltan están en ${hosts}.`; |
| 309 | + } |
| 310 | + |
| 311 | + const name = |
| 312 | + this.titleCase( |
| 313 | + this.title($('h3.post-title, h1.post-title').first().text()), |
| 314 | + ) || |
| 315 | + this.title($('title').text()) || |
| 316 | + 'Untitled'; |
| 317 | + const genres = labels.genero || labels.generos; |
| 318 | + |
| 319 | + return { |
| 320 | + path: novelPath, |
| 321 | + name, |
| 322 | + cover: this.cover(body.find('img[src]').first().attr('src')), |
| 323 | + author: labels.autor, |
| 324 | + genres: genres || undefined, |
| 325 | + status: this.status(labels.estado), |
| 326 | + summary: summary || undefined, |
| 327 | + chapters, |
| 328 | + }; |
| 329 | + } |
| 330 | + |
| 331 | + async parseChapter(chapterPath: string): Promise<string> { |
| 332 | + const $ = await this.document(chapterPath); |
| 333 | + const body = $('.post-body').first(); |
| 334 | + body |
| 335 | + .find('script, style, noscript, iframe, ins, form, .adsbygoogle') |
| 336 | + .remove(); |
| 337 | + // Drop the "Anterior - Índice - Siguiente" line and the author's sharing and |
| 338 | + // donation lines. Only short blocks are touched so that a wrapper around |
| 339 | + // the story text is never removed. |
| 340 | + body.find('div, p, span').each((_, el) => { |
| 341 | + const text = this.clean($(el).text()); |
| 342 | + if (text.length < 250 && (NAVIGATION.test(text) || isPromotion(text))) { |
| 343 | + $(el).remove(); |
| 344 | + } |
| 345 | + }); |
| 346 | + // Trim the empty and separator-only blocks left at the end, innermost first. |
| 347 | + for (let guard = 0; guard < 100; guard++) { |
| 348 | + const last = body |
| 349 | + .find('*') |
| 350 | + .filter( |
| 351 | + (_, el) => |
| 352 | + !$(el).children().length && !$(el).is('img, br, hr, figure'), |
| 353 | + ) |
| 354 | + .last(); |
| 355 | + if (!last.length || !TRAILING.test(this.clean(last.text()))) break; |
| 356 | + last.remove(); |
| 357 | + } |
| 358 | + |
| 359 | + // The text is spaced with runs of empty blocks: keep a single one. |
| 360 | + const chapter = (body.html()?.trim() || '').replace( |
| 361 | + BLANK_BLOCKS, |
| 362 | + '<div><br></div>', |
| 363 | + ); |
| 364 | + if (this.clean(loadCheerio(chapter).text()).length < 100) { |
| 365 | + throw new Error('Novelas Topcur: no readable chapter text found.'); |
| 366 | + } |
| 367 | + return chapter; |
| 368 | + } |
| 369 | + |
| 370 | + async searchNovels( |
| 371 | + searchTerm: string, |
| 372 | + pageNo: number, |
| 373 | + ): Promise<Plugin.NovelItem[]> { |
| 374 | + // The blog's own search only finds individual chapter posts, so series are |
| 375 | + // matched against the catalogue's titles instead (a single page). |
| 376 | + const tokens = this.normalize(searchTerm).split(/\s+/).filter(Boolean); |
| 377 | + if (!tokens.length || pageNo > 1) return []; |
| 378 | + const novels = await this.catalogue(); |
| 379 | + return novels.filter(novel => { |
| 380 | + const name = this.normalize(novel.name); |
| 381 | + return tokens.every(token => name.includes(token)); |
| 382 | + }); |
| 383 | + } |
| 384 | + |
| 385 | + resolveUrl = (path: string) => new URL(path, this.site).href; |
| 386 | +} |
| 387 | + |
| 388 | +export default new NovelasTopcur(); |
0 commit comments