Fix migration script
[oweals/peertube.git] / server / initializers / migrations / 0025-video-filenames.js
1 /*
2   Rename thumbnails and video filenames to _id.extension
3 */
4
5 const each = require('async/each')
6 const fs = require('fs')
7 const path = require('path')
8 const mongoose = require('mongoose')
9
10 const constants = require('../constants')
11 const logger = require('../../helpers/logger')
12
13 const Video = mongoose.model('Video')
14
15 exports.up = function (callback) {
16   // Use of lean because the new Video scheme does not have filename field
17   Video.find({ filename: { $ne: null } }).lean().exec(function (err, videos) {
18     if (err) throw err
19
20     each(videos, function (video, callbackEach) {
21       const torrentName = video.filename + '.torrent'
22       const thumbnailName = video.thumbnail
23       const thumbnailExtension = path.extname(thumbnailName)
24       const videoName = video.filename
25       const videoExtension = path.extname(videoName)
26
27       const newTorrentName = video._id + '.torrent'
28       const newThumbnailName = video._id + thumbnailExtension
29       const newVideoName = video._id + videoExtension
30
31       const torrentsDir = constants.CONFIG.STORAGE.TORRENTS_DIR
32       const thumbnailsDir = constants.CONFIG.STORAGE.THUMBNAILS_DIR
33       const videosDir = constants.CONFIG.STORAGE.VIDEOS_DIR
34
35       logger.info('Renaming %s to %s.', torrentsDir + torrentName, torrentsDir + newTorrentName)
36       fs.renameSync(torrentsDir + torrentName, torrentsDir + newTorrentName)
37
38       logger.info('Renaming %s to %s.', thumbnailsDir + thumbnailName, thumbnailsDir + newThumbnailName)
39       fs.renameSync(thumbnailsDir + thumbnailName, thumbnailsDir + newThumbnailName)
40
41       logger.info('Renaming %s to %s.', videosDir + videoName, videosDir + newVideoName)
42       fs.renameSync(videosDir + videoName, videosDir + newVideoName)
43
44       Video.load(video._id, function (err, videoObj) {
45         if (err) return callbackEach(err)
46
47         videoObj.extname = videoExtension
48         videoObj.remoteId = null
49         videoObj.save(callbackEach)
50       })
51     }, callback)
52   })
53 }
54
55 exports.down = function (callback) {
56   throw new Error('Not implemented.')
57 }