import { BaseCommand, flags } from '@adonisjs/core/ace' import { CommandOptions } from '@adonisjs/core/types/ace' import db from '@adonisjs/lucid/services/db' import { unquotedFileName } from '#services/NzbImportService' /** * Files named after a whole NZB subject without quotes (spot NZBs), e.g. * `Adventure.part0055.rar - [056/175] (1/1)`: renamed to the filename in it. */ export default class FilesCleanNames extends BaseCommand { public static commandName = 'files:clean-names' public static description = 'Strips subject leftovers (counters, "yEnc") from file names that came from NZBs.' public static options: CommandOptions = { startApp: true, } @flags.boolean({ description: 'Only show what would change' }) declare dryRun: boolean public async run() { const files = await db .from('files') .whereRaw(`filename ~* '(\\(\\d+/\\d+\\)|yEnc|\\[\\d+/\\d+\\])\\s*$'`) .select('id', 'filename') const changes = files .map((f) => ({ id: Number(f.id), from: f.filename as string, to: unquotedFileName(f.filename) })) .filter((c) => c.to !== c.from) for (const c of changes.slice(0, 5)) this.logger.info(`"${c.from}" → "${c.to}"`) if (!this.dryRun) { for (const c of changes) await db.from('files').where('id', c.id).update({ filename: c.to }) } this.logger.info(`${changes.length} of ${files.length} file names ${this.dryRun ? 'would change' : 'cleaned'}.`) } }