aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/scripts/prune-storage.ts
diff options
context:
space:
mode:
authorChocobozzz <me@florianbigard.com>2023-07-31 14:34:36 +0200
committerChocobozzz <me@florianbigard.com>2023-08-11 15:02:33 +0200
commit3a4992633ee62d5edfbb484d9c6bcb3cf158489d (patch)
treee4510b39bdac9c318fdb4b47018d08f15368b8f0 /server/scripts/prune-storage.ts
parent04d1da5621d25d59bd5fa1543b725c497bf5d9a8 (diff)
downloadPeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.tar.gz
PeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.tar.zst
PeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.zip
Migrate server to ESM
Sorry for the very big commit that may lead to git log issues and merge conflicts, but it's a major step forward: * Server can be faster at startup because imports() are async and we can easily lazy import big modules * Angular doesn't seem to support ES import (with .js extension), so we had to correctly organize peertube into a monorepo: * Use yarn workspace feature * Use typescript reference projects for dependencies * Shared projects have been moved into "packages", each one is now a node module (with a dedicated package.json/tsconfig.json) * server/tools have been moved into apps/ and is now a dedicated app bundled and published on NPM so users don't have to build peertube cli tools manually * server/tests have been moved into packages/ so we don't compile them every time we want to run the server * Use isolatedModule option: * Had to move from const enum to const (https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums) * Had to explictely specify "type" imports when used in decorators * Prefer tsx (that uses esbuild under the hood) instead of ts-node to load typescript files (tests with mocha or scripts): * To reduce test complexity as esbuild doesn't support decorator metadata, we only test server files that do not import server models * We still build tests files into js files for a faster CI * Remove unmaintained peertube CLI import script * Removed some barrels to speed up execution (less imports)
Diffstat (limited to 'server/scripts/prune-storage.ts')
-rwxr-xr-xserver/scripts/prune-storage.ts187
1 files changed, 187 insertions, 0 deletions
diff --git a/server/scripts/prune-storage.ts b/server/scripts/prune-storage.ts
new file mode 100755
index 000000000..9309724b9
--- /dev/null
+++ b/server/scripts/prune-storage.ts
@@ -0,0 +1,187 @@
1import Bluebird from 'bluebird'
2import { remove } from 'fs-extra/esm'
3import { readdir, stat } from 'fs/promises'
4import { basename, join } from 'path'
5import prompt from 'prompt'
6import { uniqify } from '@peertube/peertube-core-utils'
7import { ThumbnailType, ThumbnailType_Type } from '@peertube/peertube-models'
8import { DIRECTORIES } from '@server/initializers/constants.js'
9import { VideoFileModel } from '@server/models/video/video-file.js'
10import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist.js'
11import { getUUIDFromFilename } from '../server/helpers/utils.js'
12import { CONFIG } from '../server/initializers/config.js'
13import { initDatabaseModels } from '../server/initializers/database.js'
14import { ActorImageModel } from '../server/models/actor/actor-image.js'
15import { VideoRedundancyModel } from '../server/models/redundancy/video-redundancy.js'
16import { ThumbnailModel } from '../server/models/video/thumbnail.js'
17import { VideoModel } from '../server/models/video/video.js'
18
19run()
20 .then(() => process.exit(0))
21 .catch(err => {
22 console.error(err)
23 process.exit(-1)
24 })
25
26async function run () {
27 const dirs = Object.values(CONFIG.STORAGE)
28
29 if (uniqify(dirs).length !== dirs.length) {
30 console.error('Cannot prune storage because you put multiple storage keys in the same directory.')
31 process.exit(0)
32 }
33
34 await initDatabaseModels(true)
35
36 let toDelete: string[] = []
37
38 console.log('Detecting files to remove, it could take a while...')
39
40 toDelete = toDelete.concat(
41 await pruneDirectory(DIRECTORIES.VIDEOS.PUBLIC, doesWebVideoFileExist()),
42 await pruneDirectory(DIRECTORIES.VIDEOS.PRIVATE, doesWebVideoFileExist()),
43
44 await pruneDirectory(DIRECTORIES.HLS_STREAMING_PLAYLIST.PRIVATE, doesHLSPlaylistExist()),
45 await pruneDirectory(DIRECTORIES.HLS_STREAMING_PLAYLIST.PUBLIC, doesHLSPlaylistExist()),
46
47 await pruneDirectory(CONFIG.STORAGE.TORRENTS_DIR, doesTorrentFileExist()),
48
49 await pruneDirectory(CONFIG.STORAGE.REDUNDANCY_DIR, doesRedundancyExist),
50
51 await pruneDirectory(CONFIG.STORAGE.PREVIEWS_DIR, doesThumbnailExist(true, ThumbnailType.PREVIEW)),
52 await pruneDirectory(CONFIG.STORAGE.THUMBNAILS_DIR, doesThumbnailExist(false, ThumbnailType.MINIATURE)),
53
54 await pruneDirectory(CONFIG.STORAGE.ACTOR_IMAGES_DIR, doesActorImageExist)
55 )
56
57 const tmpFiles = await readdir(CONFIG.STORAGE.TMP_DIR)
58 toDelete = toDelete.concat(tmpFiles.map(t => join(CONFIG.STORAGE.TMP_DIR, t)))
59
60 if (toDelete.length === 0) {
61 console.log('No files to delete.')
62 return
63 }
64
65 console.log('Will delete %d files:\n\n%s\n\n', toDelete.length, toDelete.join('\n'))
66
67 const res = await askConfirmation()
68 if (res === true) {
69 console.log('Processing delete...\n')
70
71 for (const path of toDelete) {
72 await remove(path)
73 }
74
75 console.log('Done!')
76 } else {
77 console.log('Exiting without deleting files.')
78 }
79}
80
81type ExistFun = (file: string) => Promise<boolean> | boolean
82async function pruneDirectory (directory: string, existFun: ExistFun) {
83 const files = await readdir(directory)
84
85 const toDelete: string[] = []
86 await Bluebird.map(files, async file => {
87 const filePath = join(directory, file)
88
89 if (await existFun(filePath) !== true) {
90 toDelete.push(filePath)
91 }
92 }, { concurrency: 20 })
93
94 return toDelete
95}
96
97function doesWebVideoFileExist () {
98 return (filePath: string) => {
99 // Don't delete private directory
100 if (filePath === DIRECTORIES.VIDEOS.PRIVATE) return true
101
102 return VideoFileModel.doesOwnedWebVideoFileExist(basename(filePath))
103 }
104}
105
106function doesHLSPlaylistExist () {
107 return (hlsPath: string) => {
108 // Don't delete private directory
109 if (hlsPath === DIRECTORIES.HLS_STREAMING_PLAYLIST.PRIVATE) return true
110
111 return VideoStreamingPlaylistModel.doesOwnedHLSPlaylistExist(basename(hlsPath))
112 }
113}
114
115function doesTorrentFileExist () {
116 return (filePath: string) => VideoFileModel.doesOwnedTorrentFileExist(basename(filePath))
117}
118
119function doesThumbnailExist (keepOnlyOwned: boolean, type: ThumbnailType_Type) {
120 return async (filePath: string) => {
121 const thumbnail = await ThumbnailModel.loadByFilename(basename(filePath), type)
122 if (!thumbnail) return false
123
124 if (keepOnlyOwned) {
125 const video = await VideoModel.load(thumbnail.videoId)
126 if (video.isOwned() === false) return false
127 }
128
129 return true
130 }
131}
132
133async function doesActorImageExist (filePath: string) {
134 const image = await ActorImageModel.loadByName(basename(filePath))
135
136 return !!image
137}
138
139async function doesRedundancyExist (filePath: string) {
140 const isPlaylist = (await stat(filePath)).isDirectory()
141
142 if (isPlaylist) {
143 // Don't delete HLS redundancy directory
144 if (filePath === DIRECTORIES.HLS_REDUNDANCY) return true
145
146 const uuid = getUUIDFromFilename(filePath)
147 const video = await VideoModel.loadWithFiles(uuid)
148 if (!video) return false
149
150 const p = video.getHLSPlaylist()
151 if (!p) return false
152
153 const redundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(p.id)
154 return !!redundancy
155 }
156
157 const file = await VideoFileModel.loadByFilename(basename(filePath))
158 if (!file) return false
159
160 const redundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
161 return !!redundancy
162}
163
164async function askConfirmation () {
165 return new Promise((res, rej) => {
166 prompt.start()
167
168 const schema = {
169 properties: {
170 confirm: {
171 type: 'string',
172 description: 'These following unused files can be deleted, but please check your backups first (bugs happen).' +
173 ' Notice PeerTube must have been stopped when your ran this script.' +
174 ' Can we delete these files?',
175 default: 'n',
176 required: true
177 }
178 }
179 }
180
181 prompt.get(schema, function (err, result) {
182 if (err) return rej(err)
183
184 return res(result.confirm?.match(/y/) !== null)
185 })
186 })
187}