1 import * as prompt from 'prompt'
2 import { createReadStream } from 'fs'
3 import { join } from 'path'
4 import { createInterface } from 'readline'
5 import { readdirPromise, unlinkPromise } from '../server/helpers/core-utils'
6 import { CONFIG } from '../server/initializers/constants'
7 import { VideoModel } from '../server/models/video/video'
8 import { initDatabaseModels } from '../server/initializers'
11 .then(() => process.exit(0))
17 async function run () {
18 await initDatabaseModels(true)
20 const storageToPrune = [
21 CONFIG.STORAGE.VIDEOS_DIR,
22 CONFIG.STORAGE.PREVIEWS_DIR,
23 CONFIG.STORAGE.THUMBNAILS_DIR,
24 CONFIG.STORAGE.TORRENTS_DIR
27 let toDelete: string[] = []
28 for (const directory of storageToPrune) {
29 toDelete = toDelete.concat(await pruneDirectory(directory))
32 if (toDelete.length === 0) {
33 console.log('No files to delete.')
37 console.log('Will delete %d files:\n\n%s\n\n', toDelete.length, toDelete.join('\n'))
39 const res = await askConfirmation()
41 console.log('Processing delete...\n')
43 for (const path of toDelete) {
44 await unlinkPromise(path)
49 console.log('Exiting without deleting files.')
53 async function pruneDirectory (directory: string) {
54 const files = await readdirPromise(directory)
56 const toDelete: string[] = []
57 for (const file of files) {
58 const uuid = getUUIDFromFilename(file)
61 if (uuid) video = await VideoModel.loadByUUID(uuid)
63 if (!uuid || !video) toDelete.push(join(directory, file))
69 function getUUIDFromFilename (filename: string) {
70 const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
71 const result = filename.match(regex)
73 if (!result || Array.isArray(result) === false) return null
78 async function askConfirmation () {
79 return new Promise((res, rej) => {
85 description: 'Are you sure you want to delete these files? Please check carefully',
91 prompt.get(schema, function (err, result) {
92 if (err) return rej(err)
93 return res(result.confirm && result.confirm.match(/y/) !== null)