Files
XCDesktop/api/modules/recycle-bin/recycleBinService.ts

79 lines
2.3 KiB
TypeScript
Raw Normal View History

2026-03-08 01:34:54 +08:00
import fs from 'fs/promises'
import path from 'path'
import { resolveNotebookPath } from '../../utils/pathSafety.js'
export async function restoreFile(
srcPath: string,
destPath: string,
deletedDate: string,
year: string,
month: string,
day: string
) {
const { fullPath: imagesDir } = resolveNotebookPath(`images/${year}/${month}/${day}`)
let content = await fs.readFile(srcPath, 'utf-8')
const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g
let match
const imageReplacements: { oldPath: string; newPath: string }[] = []
while ((match = imageRegex.exec(content)) !== null) {
const imagePath = match[2]
const imageName = path.basename(imagePath)
const rbImageName = `${deletedDate}_${imageName}`
const { fullPath: srcImagePath } = resolveNotebookPath(`RB/${rbImageName}`)
try {
await fs.access(srcImagePath)
await fs.mkdir(imagesDir, { recursive: true })
const destImagePath = path.join(imagesDir, imageName)
await fs.rename(srcImagePath, destImagePath)
const newImagePath = `images/${year}/${month}/${day}/${imageName}`
imageReplacements.push({ oldPath: imagePath, newPath: newImagePath })
} catch {
}
}
for (const { oldPath, newPath } of imageReplacements) {
content = content.replace(new RegExp(oldPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), newPath)
}
await fs.writeFile(destPath, content, 'utf-8')
await fs.unlink(srcPath)
}
export async function restoreFolder(
srcPath: string,
destPath: string,
deletedDate: string,
year: string,
month: string,
day: string
) {
await fs.mkdir(destPath, { recursive: true })
const entries = await fs.readdir(srcPath, { withFileTypes: true })
for (const entry of entries) {
const srcEntryPath = path.join(srcPath, entry.name)
const destEntryPath = path.join(destPath, entry.name)
if (entry.isDirectory()) {
await restoreFolder(srcEntryPath, destEntryPath, deletedDate, year, month, day)
} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) {
await restoreFile(srcEntryPath, destEntryPath, deletedDate, year, month, day)
} else {
await fs.rename(srcEntryPath, destEntryPath)
}
}
const remaining = await fs.readdir(srcPath)
if (remaining.length === 0) {
await fs.rmdir(srcPath)
}
}