Initial commit
This commit is contained in:
78
api/modules/recycle-bin/recycleBinService.ts
Normal file
78
api/modules/recycle-bin/recycleBinService.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user