Skip to content

Commit 6aef570

Browse files
committed
feat(multisrc/novelfire): fix Novel Phoenix filters, add tags, content rating and last updated
Novel Phoenix only. Tag names autocomplete from the source's tag list. Novel Fire keeps its legacy parameters.
1 parent eae38ec commit 6aef570

3 files changed

Lines changed: 269 additions & 15 deletions

File tree

‎plugins/multisrc/novelfire/filters/novelphoenix.json‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@
8282
"label": "Chinese Novel",
8383
"value": "1"
8484
},
85+
{
86+
"label": "Korean Novel",
87+
"value": "2"
88+
},
8589
{
8690
"label": "Japanese Novel",
8791
"value": "3"
@@ -438,6 +442,62 @@
438442
}
439443
],
440444
"type": "Picker"
445+
},
446+
"tags": {
447+
"label": "Tags (comma separated, e.g. Isekai, Weak to Strong)",
448+
"value": "",
449+
"autocomplete": true,
450+
"type": "Text"
451+
},
452+
"content_rating": {
453+
"label": "Content Rating",
454+
"value": "-1",
455+
"options": [
456+
{
457+
"label": "All",
458+
"value": "-1"
459+
},
460+
{
461+
"label": "Safe",
462+
"value": "0"
463+
},
464+
{
465+
"label": "Suggestive",
466+
"value": "1"
467+
},
468+
{
469+
"label": "18+",
470+
"value": "2"
471+
}
472+
],
473+
"type": "Picker"
474+
},
475+
"latest_release_date": {
476+
"label": "Last Updated",
477+
"value": "-1",
478+
"options": [
479+
{
480+
"label": "Any time",
481+
"value": "-1"
482+
},
483+
{
484+
"label": "Within 24 hours",
485+
"value": "0"
486+
},
487+
{
488+
"label": "Within 7 days",
489+
"value": "1"
490+
},
491+
{
492+
"label": "Within 30 days",
493+
"value": "2"
494+
},
495+
{
496+
"label": "Within 3 months",
497+
"value": "3"
498+
}
499+
],
500+
"type": "Picker"
441501
}
442502
}
443503
}

‎plugins/multisrc/novelfire/sources.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
"sourceName": "Novel Phoenix",
1616
"options": {
1717
"lang": "English",
18-
"versionIncrement": 4
18+
"minorVer": 1,
19+
"advSearchV2": true
1920
}
2021
}
2122
]

‎plugins/multisrc/novelfire/template.ts‎

Lines changed: 207 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { fetchApi } from '@libs/fetch';
33
import { Plugin } from '@/types/plugin';
44
import { NovelStatus } from '@libs/novelStatus';
55
import { Filters } from '@libs/filterInputs';
6+
import type { FilterOption } from '@libs/filterInputs';
67
import { storage } from '@libs/storage';
78
import {
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 {
2123
const CHAPTER_NOTICE_REGEX =
2224
/Some novel pages moved|Page Not Found 404|Chapter not found/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+
2435
type 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

3146
export 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*Chapters/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

Comments
 (0)