diff --git a/src/__tests__/longTitle.test.ts b/src/__tests__/longTitle.test.ts new file mode 100644 index 0000000..1c35e6b --- /dev/null +++ b/src/__tests__/longTitle.test.ts @@ -0,0 +1,39 @@ +import { parseTorrentTitle } from '../index'; + +describe('Long title tests', () => { + // Without a "/" or "|" the alt title pattern used to backtrack through every + // split of the name: 3000 Cyrillic letters took about 30 seconds. + test('a long Cyrillic name without separators parses quickly', () => { + const name = 'Фильм ' + 'а'.repeat(3000); + const started = Date.now(); + const result = parseTorrentTitle(name); + expect(Date.now() - started).toBeLessThan(3000); + expect(result.title).toBe(name); + }); + test('the same after a separator and a bracket', () => { + const started = Date.now(); + parseTorrentTitle('Movie / (' + 'а'.repeat(3000)); + expect(Date.now() - started).toBeLessThan(3000); + }); + // The cast pattern did the same on brackets that never close the name. + test('a long name of unclosed brackets parses quickly', () => { + const started = Date.now(); + parseTorrentTitle('а('.repeat(1500)); + parseTorrentTitle('a/('.repeat(1000)); + expect(Date.now() - started).toBeLessThan(3000); + }); + test('a Russian cast list is still removed', () => { + expect(parseTorrentTitle('Движение вверх (Антон Мегердичев)').title).toBe( + 'Движение вверх' + ); + expect(parseTorrentTitle('Фильм / Movie (Иван Иванов)').title).toBe( + 'Movie' + ); + }); + test('alt titles are still removed', () => { + const result = parseTorrentTitle( + 'Дюна: Часть вторая / Dune: Part Two (2024) BDRip 1080p' + ); + expect(result.title).toBe('Dune: Part Two'); + }); +}); diff --git a/src/utils.ts b/src/utils.ts index 558e256..a97bd5a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -14,12 +14,16 @@ export const NON_ENGLISH_CHARS = '\\u3040-\\u309F\\u30A0-\\u30FF\\u4E00-\\u9FFF\\u0400-\\u04FF'; // Main regex patterns from ptt.go +// The lookaheads in the two patterns below change no match: each states where +// its alternative has to end anyway (at the ")" closing the name, at the next +// "/" or "|"). Without them, a start that cannot end there backtracks through +// every split of the rest of the name, which is cubic in its length. export const russianCastRegex = new RegExp( - `(\\([^)]*[${NON_ENGLISH_CHARS}][^)]*\\))$|(?:\\/.*?)(\\(.*\\))$`, + `(\\((?=[^)]*\\)$)[^)]*[${NON_ENGLISH_CHARS}][^)]*\\))$|(?:\\/(?=.*\\)$).*?)(\\(.*\\))$`, 'u' ); export const altTitlesRegex = new RegExp( - `[^/|(]*[${NON_ENGLISH_CHARS}][^/|]*[/|]|[/|][^/|(]*[${NON_ENGLISH_CHARS}][^/|]*`, + `(?=[^/|]*[/|])[^/|(]*[${NON_ENGLISH_CHARS}][^/|]*[/|]|[/|][^/|(]*[${NON_ENGLISH_CHARS}][^/|]*`, 'gu' ); export const notOnlyNonEnglishRegex = new RegExp(