Fix video channel description/support max length
[oweals/peertube.git] / server / initializers / migrations / 0075-video-resolutions.ts
1 import * as Sequelize from 'sequelize'
2 import { join } from 'path'
3
4 import { readdirPromise, renamePromise } from '../../helpers/core-utils'
5 import { CONFIG } from '../../initializers/constants'
6 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
7
8 function up (utils: {
9   transaction: Sequelize.Transaction,
10   queryInterface: Sequelize.QueryInterface,
11   sequelize: Sequelize.Sequelize,
12   db: any
13 }): Promise<void> {
14   const torrentDir = CONFIG.STORAGE.TORRENTS_DIR
15   const videoFileDir = CONFIG.STORAGE.VIDEOS_DIR
16
17   return readdirPromise(videoFileDir)
18     .then(videoFiles => {
19       const tasks: Promise<any>[] = []
20       for (const videoFile of videoFiles) {
21         const matches = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.([a-z0-9]+)/.exec(videoFile)
22         if (matches === null) {
23           console.log('Invalid video file name %s.', videoFile)
24           continue
25         }
26
27         const uuid = matches[1]
28         const ext = matches[2]
29
30         const p = getVideoFileResolution(join(videoFileDir, videoFile))
31           .then(height => {
32             const oldTorrentName = uuid + '.torrent'
33             const newTorrentName = uuid + '-' + height + '.torrent'
34             return renamePromise(join(torrentDir, oldTorrentName), join(torrentDir, newTorrentName)).then(() => height)
35           })
36           .then(height => {
37             const newVideoFileName = uuid + '-' + height + '.' + ext
38             return renamePromise(join(videoFileDir, videoFile), join(videoFileDir, newVideoFileName)).then(() => height)
39           })
40           .then(height => {
41             const query = 'UPDATE "VideoFiles" SET "resolution" = ' + height +
42                           ' WHERE "videoId" = (SELECT "id" FROM "Videos" WHERE "uuid" = \'' + uuid + '\')'
43             return utils.sequelize.query(query)
44           })
45
46         tasks.push(p)
47       }
48
49       return Promise.all(tasks).then(() => undefined)
50     })
51 }
52
53 function down (options) {
54   throw new Error('Not implemented.')
55 }
56
57 export {
58   up,
59   down
60 }