mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-28 04:46:07 -08:00
feat(subsync): keep a one-time backup when replacing subtitles in place
Auto mode rewrites the active subtitle from one keypress with replace on by default. The first in-place rewrite now copies the original to <file>.orig (not a subtitle extension, so mpv autoload and sidecar discovery skip it). Replacements also write through symlinks and keep the file's permissions.
This commit is contained in:
5 files changed
+128
-28
No files matched your search
@@ -1545,6 +1545,69 @@ test('runSubsyncManual supports built-in file reference and manual offset engine
|
||||
assert.equal(offsetResult.message, 'Shifted subtitle by -1.25s');
|
||||
});
|
||||
|
||||
test('in-place replacement keeps a one-time .orig backup, the file mode, and symlinks', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-backup-'));
|
||||
const videoPath = path.join(tmpDir, 'ep01.mkv');
|
||||
const realTargetPath = path.join(tmpDir, 'store', 'ep01.ja.srt');
|
||||
const linkedTargetPath = path.join(tmpDir, 'ep01.ja.srt');
|
||||
fs.mkdirSync(path.dirname(realTargetPath));
|
||||
fs.writeFileSync(videoPath, 'video');
|
||||
writeSrtFromSpans(realTargetPath, generateSyntheticSpans(7n, 1442695040888963407n, 50), 0);
|
||||
fs.chmodSync(realTargetPath, 0o640);
|
||||
const original = fs.readFileSync(realTargetPath, 'utf8');
|
||||
const canSymlink = (() => {
|
||||
try {
|
||||
fs.symlinkSync(realTargetPath, linkedTargetPath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
const targetPath = canSymlink ? linkedTargetPath : realTargetPath;
|
||||
|
||||
const deps = makeDeps({
|
||||
getMpvClient: () => ({
|
||||
connected: true,
|
||||
currentAudioStreamIndex: null,
|
||||
send: () => {},
|
||||
requestProperty: async (name: string) => {
|
||||
if (name === 'path') return videoPath;
|
||||
if (name === 'sid') return 1;
|
||||
if (name === 'secondary-sid') return null;
|
||||
if (name === 'track-list') {
|
||||
return [
|
||||
{ id: 1, type: 'sub', selected: true, external: true, 'external-filename': targetPath },
|
||||
];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
}),
|
||||
getResolvedConfig: () => ({
|
||||
alassPath: '/missing/alass',
|
||||
ffsubsyncPath: '/missing/ffsubsync',
|
||||
ffmpegPath: '/missing/ffmpeg',
|
||||
replace: true,
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal((await runSubsyncManual({ engine: 'offset', offsetMs: 1000 }, deps)).ok, true);
|
||||
assert.equal((await runSubsyncManual({ engine: 'offset', offsetMs: 1000 }, deps)).ok, true);
|
||||
|
||||
const backupPath = `${realTargetPath}.orig`;
|
||||
assert.equal(fs.readFileSync(backupPath, 'utf8'), original);
|
||||
assert.notEqual(fs.readFileSync(realTargetPath, 'utf8'), original);
|
||||
if (process.platform !== 'win32') {
|
||||
assert.equal(fs.statSync(realTargetPath).mode & 0o777, 0o640);
|
||||
}
|
||||
if (canSymlink) {
|
||||
assert.equal(fs.lstatSync(linkedTargetPath).isSymbolicLink(), true);
|
||||
}
|
||||
assert.deepEqual(fs.readdirSync(path.dirname(realTargetPath)).sort(), [
|
||||
'ep01.ja.srt',
|
||||
'ep01.ja.srt.orig',
|
||||
]);
|
||||
});
|
||||
|
||||
test('runSubsyncManual rejects non-file references and keeps the track title and lang on reload', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-manual-ref-validation-'));
|
||||
const videoPath = path.join(tmpDir, 'ep01.mkv');
|
||||
|
||||
@@ -500,23 +500,63 @@ function readAndParseSubtitleFile(filePath: string): ParsedSubtitleFile {
|
||||
};
|
||||
}
|
||||
|
||||
function writeRetimedContent(outputPath: string, content: string): void {
|
||||
const dir = path.dirname(outputPath);
|
||||
/** Suffix for the one-time backup of a replaced subtitle; not a subtitle extension, so mpv and sidecar discovery ignore it. */
|
||||
const SUBSYNC_BACKUP_SUFFIX = '.orig';
|
||||
|
||||
function resolveRealPathOrSelf(filePath: string): string {
|
||||
try {
|
||||
return fs.realpathSync(filePath);
|
||||
} catch {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a staged retimed file over `outputPath`. Writes through a symlink to the real file
|
||||
* and keeps its permissions. When `replacesSource` is set (in-place `subsync.replace`), the
|
||||
* first replacement keeps the untouched original as `<file>.orig`; later runs leave it alone.
|
||||
*/
|
||||
function installRetimedFile(stagedPath: string, outputPath: string, replacesSource: boolean): void {
|
||||
const targetPath = resolveRealPathOrSelf(outputPath);
|
||||
const existing = fs.existsSync(targetPath) ? fs.statSync(targetPath) : null;
|
||||
if (existing) {
|
||||
if (replacesSource) {
|
||||
const backupPath = `${targetPath}${SUBSYNC_BACKUP_SUFFIX}`;
|
||||
if (!fs.existsSync(backupPath)) {
|
||||
fs.copyFileSync(targetPath, backupPath, fs.constants.COPYFILE_EXCL);
|
||||
}
|
||||
}
|
||||
fs.chmodSync(stagedPath, existing.mode & 0o7777);
|
||||
}
|
||||
try {
|
||||
fs.renameSync(stagedPath, targetPath);
|
||||
} catch (error) {
|
||||
// A staged file next to a symlink can sit on another filesystem than the link target.
|
||||
if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error;
|
||||
fs.copyFileSync(stagedPath, targetPath);
|
||||
fs.unlinkSync(stagedPath);
|
||||
}
|
||||
}
|
||||
|
||||
function removeIfExists(filePath: string): void {
|
||||
try {
|
||||
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
||||
} catch {
|
||||
// Best-effort cleanup of a staged write artifact.
|
||||
}
|
||||
}
|
||||
|
||||
function writeRetimedContent(outputPath: string, content: string, replacesSource: boolean): void {
|
||||
const dir = path.dirname(resolveRealPathOrSelf(outputPath));
|
||||
const tmpPath = path.join(
|
||||
dir,
|
||||
`.subminer-subsync-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`,
|
||||
);
|
||||
try {
|
||||
fs.writeFileSync(tmpPath, content, 'utf8');
|
||||
fs.renameSync(tmpPath, outputPath);
|
||||
installRetimedFile(tmpPath, outputPath, replacesSource);
|
||||
} catch (error) {
|
||||
try {
|
||||
if (fs.existsSync(tmpPath)) {
|
||||
fs.unlinkSync(tmpPath);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort cleanup of temp write artifact.
|
||||
}
|
||||
removeIfExists(tmpPath);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1221,7 +1261,7 @@ async function runBuiltinSubsync(
|
||||
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' };
|
||||
}
|
||||
|
||||
writeRetimedContent(outputPath, alignment.rewrittenContent);
|
||||
writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget);
|
||||
if (targetExtraction.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
@@ -1272,7 +1312,7 @@ async function runManualOffsetSubsync(
|
||||
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
|
||||
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' };
|
||||
}
|
||||
writeRetimedContent(outputPath, rewritten);
|
||||
writeRetimedContent(outputPath, rewritten, replaceTarget);
|
||||
if (targetExtraction.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
@@ -1346,20 +1386,14 @@ async function subsyncToReference(
|
||||
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' };
|
||||
}
|
||||
|
||||
fs.renameSync(stagedOutputPath, outputPath);
|
||||
installRetimedFile(stagedOutputPath, outputPath, replaceTarget);
|
||||
await loadSyncedSubtitle(client, outputPath, slot, targetTrack);
|
||||
return {
|
||||
ok: true,
|
||||
message: `Subtitle synchronized with ${engine}`,
|
||||
};
|
||||
} finally {
|
||||
try {
|
||||
if (fs.existsSync(stagedOutputPath)) {
|
||||
fs.unlinkSync(stagedOutputPath);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort cleanup of staged external-engine output.
|
||||
}
|
||||
removeIfExists(stagedOutputPath);
|
||||
cleanupTemporaryFile(targetExtraction);
|
||||
}
|
||||
}
|
||||
@@ -1900,7 +1934,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
deps.showMpvOsd(`Subsync failed: ${LOSSY_REWRITE_ERROR_MESSAGE}`);
|
||||
return;
|
||||
}
|
||||
writeRetimedContent(outputPath, alignment.rewrittenContent);
|
||||
writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget);
|
||||
if (targetExtraction!.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user