Files
shelfmark/src/frontend/src/utils/namingTemplatePreview.ts
T
Amalkrishna A S b38e4e4a00 feat(naming): add {AuthorSort} template variable (#1484)
Closes #1178.

Adds `{AuthorSort}`, the first author surname-first ("Arthur Conan
Doyle" → "Doyle, Arthur Conan"), for rename and organize templates,
alongside `{FirstAuthor}`.

- A value already in "Last, First" form (one word before the comma) is
kept as is; Jr/Sr/II/III/IV stay at the end.
- Known limits, same as calibre's default: the last word is treated as
the surname, so particles ("Le Guin") and surname-first names aren't
detected.
- Added to the settings help, env docs, the frontend variable
picker/preview, and tests.
2026-10-20 01:22:05 -04:00

347 lines
9.5 KiB
TypeScript

export type NamingTemplateMode = 'filename' | 'path';
export type NamingTemplateContent = 'book' | 'audiobook';
export interface NamingTemplateToken {
token: string;
label: string;
description: string;
value: string;
group: 'Core' | 'Universal' | 'Files';
audiobookOnly?: boolean;
}
interface RenderOptions {
allowPathSeparators: boolean;
/** Mirrors `word_separator` in shelfmark/core/naming.py. Defaults to ' ' (no change). */
wordSeparator?: string;
}
interface RenderResult {
value: string;
unknownTokens: string[];
}
export const NAMING_TEMPLATE_TOKENS: NamingTemplateToken[] = [
{
token: 'Author',
label: 'Author',
description: 'Primary author',
value: 'Arthur Conan Doyle',
group: 'Core',
},
{
token: 'FirstAuthor',
label: 'First author',
description: 'First author only, when metadata lists several',
value: 'Arthur Conan Doyle',
group: 'Core',
},
{
token: 'AuthorSort',
label: 'Author (surname first)',
description: 'First author as "Last, First"',
value: 'Doyle, Arthur Conan',
group: 'Core',
},
{
token: 'Title',
label: 'Full title',
description: 'Title as provided by metadata',
value: 'The Hound of the Baskervilles: Another Adventure of Sherlock Holmes',
group: 'Core',
},
{
token: 'PrimaryTitle',
label: 'Primary title',
description: 'Title without the subtitle suffix',
value: 'The Hound of the Baskervilles',
group: 'Universal',
},
{
token: 'Year',
label: 'Year',
description: 'Publication year',
value: '1902',
group: 'Core',
},
{
token: 'Language',
label: 'Language',
description: 'Release language code, so translations do not share a folder',
value: 'en',
group: 'Core',
},
{
token: 'User',
label: 'User',
description: 'Requesting user',
value: 'alex',
group: 'Core',
},
{
token: 'Series',
label: 'Series',
description: 'Series name',
value: 'Sherlock Holmes',
group: 'Universal',
},
{
token: 'SeriesPosition',
label: 'Series position',
description: 'Book position in the series',
value: '5',
group: 'Universal',
},
{
token: 'Narrator',
label: 'Narrator',
description:
'Release narrator (MyAnonamouse via Prowlarr, needs a MAM session ID). {{Narrator}} gives "{Name}"',
value: 'Simon Vance',
group: 'Universal',
audiobookOnly: true,
},
{
token: 'Subtitle',
label: 'Subtitle',
description: 'Subtitle from metadata',
value: 'Another Adventure of Sherlock Holmes',
group: 'Universal',
},
{
token: 'OriginalName',
label: 'Original name',
description: 'Source filename without extension',
value: 'The Hound of the Baskervilles - Chapter 01',
group: 'Files',
},
{
token: 'PartNumber',
label: 'Part number',
description: 'Sequential part number for multi-file audiobooks',
value: '01',
group: 'Files',
audiobookOnly: true,
},
];
const KNOWN_TOKENS = [
'seriesposition',
'primarytitle',
'originalname',
'firstauthor',
'authorsort',
'partnumber',
'language',
'narrator',
'subtitle',
'author',
'series',
'title',
'year',
'user',
];
// Mirrors AUTHOR_LIST_SEPARATOR in shelfmark/core/naming.py: authors arrive
// pre-joined with ',' or ';' and {FirstAuthor} keeps only the first entry.
const firstAuthor = (value: string): string => value.split(/\s*[,;]\s*/)[0]?.trim() ?? '';
// Mirrors author_sort() in shelfmark/core/naming.py.
const NAME_SUFFIXES = new Set(['jr', 'jr.', 'sr', 'sr.', 'ii', 'iii', 'iv']);
const authorSort = (value: string): string => {
const text = value.split(/\s+/).filter(Boolean).join(' ');
const entries = text.split(/\s*[,;]\s*/).filter(Boolean);
const [first, second] = entries;
if (!first) {
return '';
}
if (entries.length === 2 && second && !first.includes(' ') && !text.includes(';')) {
return `${first}, ${second}`;
}
const words = first.split(' ');
let suffix = '';
if (second && NAME_SUFFIXES.has(second.toLowerCase())) {
suffix = second;
} else if (words.length > 2 && NAME_SUFFIXES.has(words[words.length - 1].toLowerCase())) {
suffix = words.pop() ?? '';
}
if (words.length < 2) {
return first;
}
const sorted = `${words[words.length - 1]}, ${words.slice(0, -1).join(' ')}`;
return suffix ? `${sorted}, ${suffix}` : sorted;
};
const BRACE_PATTERN = /\{([^}]+)\}/g;
const INVALID_CHARS_PATTERN = /[\\/:*?"<>|]/g;
const WHITESPACE_RUN_PATTERN = /\s+/g;
export const SAMPLE_NAMING_METADATA = NAMING_TEMPLATE_TOKENS.reduce<Record<string, string>>(
(metadata, token) => {
metadata[token.token] = token.value;
return metadata;
},
{},
);
const sanitizeFilename = (value: string): string => {
return value
.replace(INVALID_CHARS_PATTERN, '_')
.replace(/^[\s.]+|[\s.]+$/g, '')
.replace(/_+/g, '_')
.slice(0, 245);
};
const normalizeMetadata = (metadata: Record<string, string>): Record<string, string> => {
return Object.fromEntries(
Object.entries(metadata).map(([key, value]) => [key.toLowerCase(), value]),
);
};
const findPlaceholder = (content: string): { name: string | null; index: number } => {
const lowerContent = content.toLowerCase();
for (const tokenName of KNOWN_TOKENS) {
const index = lowerContent.indexOf(tokenName);
if (index !== -1) {
return { name: tokenName, index };
}
}
return { name: null, index: -1 };
};
export const renderNamingTemplate = (
template: string,
metadata: Record<string, string> = SAMPLE_NAMING_METADATA,
options: RenderOptions,
): RenderResult => {
if (!template) {
return { value: '', unknownTokens: [] };
}
const normalized = normalizeMetadata(metadata);
const unknownTokens: string[] = [];
const placeholderValue = (placeholderName: string): string => {
if (placeholderName === 'firstauthor' && !normalized['firstauthor']) {
return firstAuthor(normalized['author'] ?? '');
}
if (placeholderName === 'authorsort' && !normalized['authorsort']) {
return authorSort(normalized['author'] ?? '');
}
return (normalized[placeholderName] ?? '').trim();
};
const renderBlock = (content: string): string | null => {
const { name, index } = findPlaceholder(content);
if (!name) {
const unknown = content.trim();
if (unknown && !/\s/.test(unknown) && !unknownTokens.includes(unknown)) {
unknownTokens.push(unknown);
}
return null;
}
const prefix = content.slice(0, index);
const suffix = content.slice(index + name.length);
let rawValue = placeholderValue(name);
if (!rawValue) {
return '';
}
const wordSeparator = options.wordSeparator ?? ' ';
if (wordSeparator !== ' ') {
rawValue = rawValue.replace(WHITESPACE_RUN_PATTERN, wordSeparator);
}
const value = sanitizeFilename(
options.allowPathSeparators ? rawValue : rawValue.replace(/\//g, '_'),
);
return `${prefix}${value}${suffix}`;
};
const matches = Array.from(template.matchAll(BRACE_PATTERN));
let result = '';
if (matches.length === 0) {
result = template;
} else {
let cursor = 0;
matches.forEach((match, index) => {
result += template.slice(cursor, match.index);
const content = match[1] ?? '';
const rendered = renderBlock(content);
if (rendered !== null) {
result += rendered;
} else {
const nextMatch = matches[index + 1];
const conditionalLiteral =
nextMatch !== undefined && match.index + match[0].length === nextMatch.index;
const nextContent = nextMatch?.[1] ?? '';
const nextPlaceholder = findPlaceholder(nextContent).name;
const includeLiteral =
conditionalLiteral && nextPlaceholder
? Boolean(placeholderValue(nextPlaceholder))
: false;
if (includeLiteral) {
result += content;
} else if (!conditionalLiteral && /\s/.test(content)) {
result += match[0];
}
}
cursor = match.index + match[0].length;
if (rendered === '') {
// Mirrors naming.py: "{{Narrator}}" drops the closing braces it opened when empty.
const opened = (content.match(/\{/g) ?? []).length;
for (let i = 0; i < opened && template[cursor] === '}'; i += 1) {
cursor += 1;
}
}
});
result += template.slice(cursor);
}
result = result.replace(/\/+/g, '/');
result = result.replace(/[ \t]+\//g, '/');
result = result.replace(/\/[ \t]+/g, '/');
result = result.replace(/^\/+|\/+$/g, '');
result = result.replace(/^[\s\-_.]+/g, '');
result = result.replace(/[\s\-_.]+$/g, '');
result = result.replace(/(\s*-\s*){2,}/g, ' - ');
result = result.replace(/\(\s*\)/g, '');
result = result.replace(/\[\s*\]/g, '');
result = result.replace(/[\s\-_.]+$/g, '');
return { value: result, unknownTokens };
};
// Mirrors get_word_separator() in shelfmark/download/postprocess/policy.py.
export const resolveWordSeparator = (value: unknown): string => {
return (typeof value === 'string' ? value : '') || ' ';
};
export const buildNamingTemplatePreview = (
template: string,
mode: NamingTemplateMode,
content: NamingTemplateContent,
wordSeparator = ' ',
): RenderResult => {
const rendered = renderNamingTemplate(template, SAMPLE_NAMING_METADATA, {
allowPathSeparators: mode === 'path',
wordSeparator,
});
const fallback = SAMPLE_NAMING_METADATA.PrimaryTitle;
const extension = content === 'audiobook' ? 'mp3' : 'epub';
const baseValue = rendered.value || fallback;
return {
value: `${baseValue}.${extension}`,
unknownTokens: rendered.unknownTokens,
};
};