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'
8 import { getUUIDFromFilename } from '../server/helpers/utils'
11 .then(() => process.exit(0))
17 async function run () {
18 await initDatabaseModels(true)
20 const storageOnlyOwnedToPrune = [
21 CONFIG.STORAGE.VIDEOS_DIR,
22 CONFIG.STORAGE.TORRENTS_DIR,
23 CONFIG.STORAGE.REDUNDANCY_DIR
26 const storageForAllToPrune = [
27 CONFIG.STORAGE.PREVIEWS_DIR,
28 CONFIG.STORAGE.THUMBNAILS_DIR
31 let toDelete: string[] = []
32 for (const directory of storageOnlyOwnedToPrune) {
33 toDelete = toDelete.concat(await pruneDirectory(directory, true))
36 for (const directory of storageForAllToPrune) {
37 toDelete = toDelete.concat(await pruneDirectory(directory, false))
40 const tmpFiles = await readdir(CONFIG.STORAGE.TMP_DIR)
41 toDelete = toDelete.concat(tmpFiles.map(t => join(CONFIG.STORAGE.TMP_DIR, t)))
43 if (toDelete.length === 0) {
44 console.log('No files to delete.')
48 console.log('Will delete %d files:\n\n%s\n\n', toDelete.length, toDelete.join('\n'))
50 const res = await askConfirmation()
52 console.log('Processing delete...\n')
54 for (const path of toDelete) {
60 console.log('Exiting without deleting files.')
64 async function pruneDirectory (directory: string, onlyOwned = false) {
65 const files = await readdir(directory)
67 const toDelete: string[] = []
68 for (const file of files) {
69 const uuid = getUUIDFromFilename(file)
71 let localRedundancy: boolean
74 video = await VideoModel.loadByUUIDWithFile(uuid)
75 localRedundancy = await VideoRedundancyModel.isLocalByVideoUUIDExists(uuid)
81 (onlyOwned === true && (video.isOwned() === false && localRedundancy === false))
83 toDelete.push(join(directory, file))
90 async function askConfirmation () {
91 return new Promise((res, rej) => {
97 description: 'These following unused files can be deleted, but please check your backups first (bugs happen).' +
98 ' Notice PeerTube must have been stopped when your ran this script.' +
99 ' Can we delete these files?',
105 prompt.get(schema, function (err, result) {
106 if (err) return rej(err)
107 return res(result.confirm && result.confirm.match(/y/) !== null)