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