@@ -3,6 +3,7 @@ import { fetchApi } from '@libs/fetch';
33import { Plugin } from '@/types/plugin' ;
44import { NovelStatus } from '@libs/novelStatus' ;
55import { Filters } from '@libs/filterInputs' ;
6+ import type { FilterOption } from '@libs/filterInputs' ;
67import { storage } from '@libs/storage' ;
78import {
89 checkResponse ,
@@ -11,8 +12,9 @@ import {
1112 type PluginErrorCode ,
1213} from '@libs/pluginError' ;
1314
14- // Live contract for the sites this template serves:
15- // listing <site>search-adv?…&sort=…&page=…
15+ // Live contract for the sites this template serves (verified 2026-11-27):
16+ // listing <site>search-adv?country_id|country_id[]=…&categories[]=…
17+ // &chapter_min/chapter_max|totalchapter=…&sort=…&page=…
1618// novel <site><novelPath> .novel-title, #novel-report[report-post_id]
1719// chapters <site>ajax/listChapterDataAjax { recordsTotal, data: { n_sort, slug, title } }
1820// chapter <site><novelPath>/chapter-<n> #content
@@ -21,11 +23,24 @@ import {
2123const CHAPTER_NOTICE_REGEX =
2224 / S o m e n o v e l p a g e s m o v e d | P a g e N o t F o u n d 4 0 4 | C h a p t e r n o t f o u n d / i;
2325
26+ // Novel Phoenix only accepts numeric tag ids, so tag names have to be resolved
27+ // through its own tag list. The list rarely changes; cache it for a week.
28+ const TAGS_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000 ;
29+
30+ type TagIndex = {
31+ tags : { id : string ; name : string } [ ] ;
32+ byName : Record < string , string > ;
33+ } ;
34+
2435type NovelFireOptions = {
2536 lang ?: string ;
2637 majorVer ?: number ;
2738 minorVer ?: number ;
2839 versionIncrement ?: number ;
40+ // Novel Phoenix moved its advanced search to single-value `country_id` and a
41+ // `chapter_min` / `chapter_max` range. Novel Fire still expects `country_id[]`
42+ // and `totalchapter`, so the parameter shape is chosen per source.
43+ advSearchV2 ?: boolean ;
2944} ;
3045
3146export type NovelFireMetadata = {
@@ -96,6 +111,7 @@ export class NovelFirePlugin implements Plugin.PagePlugin {
96111 } ;
97112 singlePage = storage . get ( 'singlePage' ) ;
98113 pageLength = storage . get ( 'pageLength' ) ;
114+ private tagIndexPromise ?: Promise < TagIndex > ;
99115
100116 constructor ( metadata : NovelFireMetadata ) {
101117 this . id = metadata . id ;
@@ -185,31 +201,66 @@ export class NovelFirePlugin implements Plugin.PagePlugin {
185201 this . draw = 0 ;
186202 }
187203
188- const params = this . buildSearchParams ( pageNo , showLatestNovels , filters ) ;
204+ const params = await this . buildSearchParams (
205+ pageNo ,
206+ showLatestNovels ,
207+ filters ,
208+ ) ;
189209 const loadedCheerio = await this . getCheerio (
190210 `${ this . site } search-adv?${ params . toString ( ) } ` ,
191211 false ,
192212 ) ;
193213
214+ this . assertChapterFilterApplied ( loadedCheerio , filters ?. chapters ?. value ) ;
215+
194216 return this . parseNovels ( loadedCheerio , '.novel-item' , pageNo === 1 ) ;
195217 }
196218
197- private buildSearchParams (
219+ private async buildSearchParams (
198220 pageNo : number ,
199221 showLatestNovels : boolean | undefined ,
200222 filters : Plugin . PopularNovelsOptions < typeof this . filters > [ 'filters' ] ,
201- ) : URLSearchParams {
223+ ) : Promise < URLSearchParams > {
202224 const params = new URLSearchParams ( ) ;
203225
204- for ( const language of filters ?. language ?. value || [ ] ) {
205- params . append ( 'country_id[]' , language ) ;
206- }
207- params . append ( 'totalchapter' , filters ?. chapters ?. value || '0' ) ;
208- for ( const tag of filters ?. tags ?. value || [ ] ) {
209- params . append ( 'tags[]' , tag ) ;
210- }
211- for ( const tag of filters ?. tags_excluded ?. value || [ ] ) {
212- params . append ( 'tags_excluded[]' , tag ) ;
226+ if ( this . options ?. advSearchV2 ) {
227+ // Novel Phoenix ignores the repeated `country_id[]` array and expects a
228+ // single `country_id`, plus `chapter_min` / `chapter_max` instead of the
229+ // combined `totalchapter` range. Novel Fire still uses the old shape.
230+ const language = filters ?. language ?. value ?. [ 0 ] ;
231+ if ( language ) params . append ( 'country_id' , language ) ;
232+
233+ const chapterRange = filters ?. chapters ?. value ;
234+ if ( chapterRange && chapterRange !== '0' ) {
235+ const [ min , max ] = String ( chapterRange ) . split ( ',' ) ;
236+ if ( min ) params . append ( 'chapter_min' , min ) ;
237+ if ( max ) params . append ( 'chapter_max' , max ) ;
238+ }
239+
240+ params . append ( 'content_rating' , filters ?. content_rating ?. value || '-1' ) ;
241+ params . append (
242+ 'latest_release_date' ,
243+ filters ?. latest_release_date ?. value || '-1' ,
244+ ) ;
245+
246+ const tagValue = filters ?. tags ?. value ;
247+ const tagText = Array . isArray ( tagValue ) ? tagValue . join ( ',' ) : tagValue ;
248+ if ( tagText && String ( tagText ) . trim ( ) ) {
249+ for ( const tagId of await this . resolveTagIds ( String ( tagText ) ) ) {
250+ params . append ( 'tags[]' , tagId ) ;
251+ }
252+ }
253+ } else {
254+ for ( const language of filters ?. language ?. value || [ ] ) {
255+ params . append ( 'country_id[]' , language ) ;
256+ }
257+ params . append ( 'totalchapter' , filters ?. chapters ?. value || '0' ) ;
258+ for ( const tag of filters ?. tags ?. value || [ ] ) {
259+ params . append ( 'tags[]' , tag ) ;
260+ }
261+ for ( const tag of filters ?. tags_excluded ?. value || [ ] ) {
262+ params . append ( 'tags_excluded[]' , tag ) ;
263+ }
213264 }
214265
215266 params . append ( 'ctgcon' , filters ?. genre_operator ?. value || 'and' ) ;
@@ -229,6 +280,148 @@ export class NovelFirePlugin implements Plugin.PagePlugin {
229280 return params ;
230281 }
231282
283+ // Novel Phoenix ignores search parameters it does not recognise, so a renamed
284+ // filter silently returns an unfiltered list. Every result card reports its
285+ // chapter count, which lets us verify the range filter actually applied
286+ // without a second request. Only throw when every card disagrees.
287+ private assertChapterFilterApplied (
288+ $ : CheerioAPI ,
289+ chapterRange ?: string ,
290+ ) : void {
291+ if ( ! this . options ?. advSearchV2 || ! chapterRange || chapterRange === '0' ) {
292+ return ;
293+ }
294+
295+ const [ min , max ] = String ( chapterRange ) . split ( ',' ) . map ( Number ) ;
296+ if ( ! Number . isFinite ( min ) || ! Number . isFinite ( max ) ) return ;
297+
298+ const counts : number [ ] = [ ] ;
299+ $ ( '.novel-item .icon-book-open' ) . each ( ( _ , el ) => {
300+ const match = $ ( el )
301+ . parent ( )
302+ . text ( )
303+ . match ( / ( [ \d , ] + ) \s * C h a p t e r s / i) ;
304+ if ( ! match ) return ;
305+ const count = Number ( match [ 1 ] . replace ( / , / g, '' ) ) ;
306+ if ( Number . isFinite ( count ) ) counts . push ( count ) ;
307+ } ) ;
308+
309+ if ( counts . length < 3 ) return ;
310+ if ( counts . some ( count => count >= min && count <= max ) ) return ;
311+
312+ throw createPluginError ( PluginError . InvalidResponse , {
313+ message :
314+ 'Chapter filter was not applied by the source — the site may have changed.' ,
315+ } ) ;
316+ }
317+
318+ // Novel Phoenix only accepts numeric tag ids, so the tag names a user types
319+ // are resolved through the site's own tag list. It changes rarely, so it is
320+ // cached (see TAGS_CACHE_TTL_MS) and fetched at most once per session.
321+ private async getTagIndex ( ) : Promise < TagIndex > {
322+ if ( this . tagIndexPromise ) return this . tagIndexPromise ;
323+
324+ this . tagIndexPromise = ( async ( ) => {
325+ const cacheKey = `${ this . id } _tagIndex` ;
326+ try {
327+ const cached = JSON . parse ( String ( storage . get ( cacheKey ) || 'null' ) ) ;
328+ if (
329+ cached &&
330+ Date . now ( ) - Number ( cached . at ) < TAGS_CACHE_TTL_MS &&
331+ Array . isArray ( cached . tags )
332+ ) {
333+ return this . buildTagIndex ( cached . tags ) ;
334+ }
335+ } catch {
336+ // Stale or unreadable cache: refetch below.
337+ }
338+
339+ const response = await fetchApi ( `${ this . site } ajax/getTags` ) ;
340+ checkResponse ( response ) ;
341+
342+ let payload : { data ?: { id : number | string ; name : string } [ ] } ;
343+ try {
344+ payload = JSON . parse ( await response . text ( ) ) ;
345+ } catch {
346+ throw createPluginError ( PluginError . InvalidResponse , {
347+ message : 'Source returned an unexpected tag list.' ,
348+ } ) ;
349+ }
350+ const tags = ( payload . data || [ ] ) . map ( tag => ( {
351+ id : String ( tag . id ) ,
352+ name : String ( tag . name ) . trim ( ) ,
353+ } ) ) ;
354+
355+ storage . set ( cacheKey , JSON . stringify ( { at : Date . now ( ) , tags } ) ) ;
356+ return this . buildTagIndex ( tags ) ;
357+ } ) ( ) ;
358+
359+ try {
360+ return await this . tagIndexPromise ;
361+ } catch ( error ) {
362+ this . tagIndexPromise = undefined ;
363+ throw error ;
364+ }
365+ }
366+
367+ private buildTagIndex ( tags : { id : string ; name : string } [ ] ) : TagIndex {
368+ const byName : Record < string , string > = { } ;
369+ for ( const tag of tags ) {
370+ const key = tag . name . toLowerCase ( ) ;
371+ if ( key && ! byName [ key ] ) byName [ key ] = tag . id ;
372+ }
373+ return { tags, byName } ;
374+ }
375+
376+ private async resolveTagIds ( rawValue : string ) : Promise < string [ ] > {
377+ const tokens = rawValue
378+ . split ( ',' )
379+ . map ( token => token . trim ( ) )
380+ . filter ( Boolean ) ;
381+ if ( tokens . length === 0 ) return [ ] ;
382+
383+ const index = await this . getTagIndex ( ) ;
384+ const ids : string [ ] = [ ] ;
385+ const unknown : string [ ] = [ ] ;
386+
387+ for ( const token of tokens ) {
388+ if ( / ^ \d + $ / . test ( token ) ) {
389+ ids . push ( token ) ;
390+ continue ;
391+ }
392+ const id = index . byName [ token . toLowerCase ( ) ] ;
393+ if ( id ) ids . push ( id ) ;
394+ else unknown . push ( token ) ;
395+ }
396+
397+ if ( unknown . length > 0 ) {
398+ throw createPluginError ( PluginError . InvalidResponse , {
399+ message : `Unknown tag(s): ${ unknown . join (
400+ ', ' ,
401+ ) } . Pick one from the suggestions.`,
402+ } ) ;
403+ }
404+
405+ return ids ;
406+ }
407+
408+ async getFilterSuggestions (
409+ filterKey : string ,
410+ query : string ,
411+ ) : Promise < FilterOption [ ] > {
412+ if ( filterKey !== 'tags' ) return [ ] ;
413+
414+ const index = await this . getTagIndex ( ) ;
415+ const needle = query . trim ( ) . toLowerCase ( ) ;
416+ const matches = needle
417+ ? index . tags . filter ( tag => tag . name . toLowerCase ( ) . includes ( needle ) )
418+ : index . tags ;
419+
420+ return matches
421+ . slice ( 0 , 20 )
422+ . map ( tag => ( { label : tag . name , value : tag . id } ) ) ;
423+ }
424+
232425 // Both chapter sources (AJAX rows and the HTML fallback) end up here, so
233426 // naming, numbering, ordering and duplicate handling stay identical.
234427 private finalizeChapters (
0 commit comments