1 import * as prompt from 'prompt'
2 import { join } from 'path'
3 import { CONFIG } from '../server/initializers/constants'
4 import { VideoModel } from '../server/models/video/video'
5 import { initDatabaseModels } from '../server/initializers'
6 import { remove, readdir } from 'fs-extra'
7 import { VideoRedundancyModel } from '../server/models/redundancy/video-redundancy'
10 .then(() => process.exit(0))
16 async function run () {
17 await initDatabaseModels(true)
19 const storageOnlyOwnedToPrune = [
20 CONFIG.STORAGE.VIDEOS_DIR,
21 CONFIG.STORAGE.TORRENTS_DIR
24 const storageForAllToPrune = [
25 CONFIG.STORAGE.PREVIEWS_DIR,
26 CONFIG.STORAGE.THUMBNAILS_DIR
29 let toDelete: string[] = []
30 for (const directory of storageOnlyOwnedToPrune) {
31 toDelete = toDelete.concat(await pruneDirectory(directory, true))
34 for (const directory of storageForAllToPrune) {
35 toDelete = toDelete.concat(await pruneDirectory(directory, false))
38 if (toDelete.length === 0) {
39 console.log('No files to delete.')
43 console.log('Will delete %d files:\n\n%s\n\n', toDelete.length, toDelete.join('\n'))
45 const res = await askConfirmation()
47 console.log('Processing delete...\n')
49 for (const path of toDelete) {
55 console.log('Exiting without deleting files.')
59 async function pruneDirectory (directory: string, onlyOwned = false) {
60 const files = await readdir(directory)
62 const toDelete: string[] = []
63 for (const file of files) {
64 const uuid = getUUIDFromFilename(file)
66 let localRedundancy: boolean
69 video = await VideoModel.loadByUUIDWithFile(uuid)
70 localRedundancy = await VideoRedundancyModel.isLocalByVideoUUIDExists(uuid)
76 (onlyOwned === true && (video.isOwned() === false && localRedundancy === false))
78 toDelete.push(join(directory, file))
85 function getUUIDFromFilename (filename: string) {
86 const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
87 const result = filename.match(regex)
89 if (!result || Array.isArray(result) === false) return null
94 async function askConfirmation () {
95 return new Promise((res, rej) => {
101 description: 'These following unused files can be deleted, but please check your backups first (bugs happen).' +
102 ' Can we delete these files?',
108 prompt.get(schema, function (err, result) {
109 if (err) return rej(err)
110 return res(result.confirm && result.confirm.match(/y/) !== null)