filesafe/scripts/clean-up.js
Bobby Wibowo 02e2e402c3
!!! MASSIVE OVERHAUL !!!
As the title says, this commit is a massive overhaul.
I've rewritten/restrucuted almost everything in the controller scripts.
Because of that, there's a considerable possibility that I've broken
something somewhere.

Notable changes:

Added temporary uploads.

Removed file name length changer from dashboard,
in favor of an equivalent in homepage config tab.
This allows non-registered users to also set file name length.

A bunch of other undocmented stuff.
I don't know, I'm too tired to remember them all.
2019-09-08 08:56:29 +07:00

79 lines
2.2 KiB
JavaScript

const { stripIndents } = require('./_utils')
const config = require('./../config')
const db = require('knex')(config.database)
const path = require('path')
const paths = require('./../controllers/pathsController')
const self = {
mode: null
}
self.getFiles = async directory => {
const names = await paths.readdir(directory)
const files = []
for (const name of names) {
const lstat = await paths.lstat(path.join(directory, name))
if (lstat.isFile() && !name.startsWith('.'))
files.push(name)
}
return files
}
;(async () => {
const location = process.argv[1].replace(process.cwd() + '/', '')
const args = process.argv.slice(2)
self.mode = parseInt(args[0]) || 0
if (args.includes('--help') || args.includes('-h'))
return console.log(stripIndents(`
Clean up files that are not in the database.
Usage:
node ${location} [mode=0|1|2]
mode:
0 = Only list names of files that are not in the database.
1 = Clean up the files.
`))
const dryrun = self.mode === 0
const uploads = await self.getFiles(paths.uploads)
console.log(`Uploads: ${uploads.length}`)
const uploadsDb = await db.table('files')
.select('name')
.then(rows => rows.map(row => row.name))
console.log(`- In DB: ${uploadsDb.length}`)
const uploadsNotInDb = uploads.filter(upload => !uploadsDb.includes(upload))
console.log(`- Not in DB: ${uploadsNotInDb.length}`)
const thumbs = await self.getFiles(paths.thumbs)
console.log(`Thumbs: ${thumbs.length}`)
const uploadsDbSet = new Set(uploadsDb.map(upload => upload.split('.')[0]))
const thumbsNotInDb = thumbs.filter(thumb => !uploadsDbSet.has(thumb.slice(0, -4)))
console.log(`- Not in DB: ${thumbsNotInDb.length}`)
if (dryrun) {
console.log('U:', uploadsNotInDb.join(', '))
console.log('T:', thumbsNotInDb.join(', '))
} else if (!dryrun) {
for (const upload of uploadsNotInDb) {
await paths.unlink(path.join(paths.uploads, upload))
console.log(`${upload}: OK`)
}
for (const thumb of thumbsNotInDb) {
await paths.unlink(path.join(paths.thumbs, thumb))
console.log(`${thumb}: OK`)
}
}
})()
.then(() => process.exit(0))
.catch(error => {
console.error(error)
process.exit(1)
})