330067cdfa6e892776692f1787fd70efe22f2ea4
[oweals/peertube.git] / server / models / video.js
1 'use strict'
2
3 const createTorrent = require('create-torrent')
4 const ffmpeg = require('fluent-ffmpeg')
5 const fs = require('fs')
6 const magnetUtil = require('magnet-uri')
7 const parallel = require('async/parallel')
8 const parseTorrent = require('parse-torrent')
9 const pathUtils = require('path')
10 const mongoose = require('mongoose')
11
12 const constants = require('../initializers/constants')
13 const customVideosValidators = require('../helpers/custom-validators').videos
14 const logger = require('../helpers/logger')
15 const modelUtils = require('./utils')
16
17 // ---------------------------------------------------------------------------
18
19 // TODO: add indexes on searchable columns
20 const VideoSchema = mongoose.Schema({
21   name: String,
22   extname: {
23     type: String,
24     enum: [ '.mp4', '.webm', '.ogv' ]
25   },
26   remoteId: mongoose.Schema.Types.ObjectId,
27   description: String,
28   magnet: {
29     infoHash: String
30   },
31   podHost: String,
32   author: String,
33   duration: Number,
34   tags: [ String ],
35   createdDate: {
36     type: Date,
37     default: Date.now
38   }
39 })
40
41 VideoSchema.path('name').validate(customVideosValidators.isVideoNameValid)
42 VideoSchema.path('description').validate(customVideosValidators.isVideoDescriptionValid)
43 VideoSchema.path('podHost').validate(customVideosValidators.isVideoPodHostValid)
44 VideoSchema.path('author').validate(customVideosValidators.isVideoAuthorValid)
45 VideoSchema.path('duration').validate(customVideosValidators.isVideoDurationValid)
46 VideoSchema.path('tags').validate(customVideosValidators.isVideoTagsValid)
47
48 VideoSchema.methods = {
49   generateMagnetUri,
50   getVideoFilename,
51   getThumbnailName,
52   getPreviewName,
53   getTorrentName,
54   isOwned,
55   toFormatedJSON,
56   toRemoteJSON
57 }
58
59 VideoSchema.statics = {
60   generateThumbnailFromBase64,
61   getDurationFromFile,
62   listForApi,
63   listByHostAndRemoteId,
64   listByHost,
65   listOwned,
66   listOwnedByAuthor,
67   listRemotes,
68   load,
69   search
70 }
71
72 VideoSchema.pre('remove', function (next) {
73   const video = this
74   const tasks = []
75
76   tasks.push(
77     function (callback) {
78       removeThumbnail(video, callback)
79     }
80   )
81
82   if (video.isOwned()) {
83     tasks.push(
84       function (callback) {
85         removeFile(video, callback)
86       },
87       function (callback) {
88         removeTorrent(video, callback)
89       },
90       function (callback) {
91         removePreview(video, callback)
92       }
93     )
94   }
95
96   parallel(tasks, next)
97 })
98
99 VideoSchema.pre('save', function (next) {
100   const video = this
101   const tasks = []
102
103   if (video.isOwned()) {
104     const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
105     this.podHost = constants.CONFIG.WEBSERVER.HOST
106
107     tasks.push(
108       // TODO: refractoring
109       function (callback) {
110         const options = {
111           announceList: [
112             [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
113           ],
114           urlList: [
115             constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
116           ]
117         }
118
119         createTorrent(videoPath, options, function (err, torrent) {
120           if (err) return callback(err)
121
122           fs.writeFile(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), torrent, function (err) {
123             if (err) return callback(err)
124
125             const parsedTorrent = parseTorrent(torrent)
126             video.magnet.infoHash = parsedTorrent.infoHash
127
128             callback(null)
129           })
130         })
131       },
132       function (callback) {
133         createThumbnail(video, videoPath, callback)
134       },
135       function (callback) {
136         createPreview(video, videoPath, callback)
137       }
138     )
139
140     return parallel(tasks, next)
141   }
142
143   return next()
144 })
145
146 mongoose.model('Video', VideoSchema)
147
148 // ------------------------------ METHODS ------------------------------
149
150 function generateMagnetUri () {
151   let baseUrlHttp, baseUrlWs
152
153   if (this.isOwned()) {
154     baseUrlHttp = constants.CONFIG.WEBSERVER.URL
155     baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
156   } else {
157     baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.podHost
158     baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.podHost
159   }
160
161   const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
162   const announce = baseUrlWs + '/tracker/socket'
163   const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
164
165   const magnetHash = {
166     xs,
167     announce,
168     urlList,
169     infoHash: this.magnet.infoHash,
170     name: this.name
171   }
172
173   return magnetUtil.encode(magnetHash)
174 }
175
176 function getVideoFilename () {
177   if (this.isOwned()) return this._id + this.extname
178
179   return this.remoteId + this.extname
180 }
181
182 function getThumbnailName () {
183   // We always have a copy of the thumbnail
184   return this._id + '.jpg'
185 }
186
187 function getPreviewName () {
188   const extension = '.jpg'
189
190   if (this.isOwned()) return this._id + extension
191
192   return this.remoteId + extension
193 }
194
195 function getTorrentName () {
196   const extension = '.torrent'
197
198   if (this.isOwned()) return this._id + extension
199
200   return this.remoteId + extension
201 }
202
203 function isOwned () {
204   return this.remoteId === null
205 }
206
207 function toFormatedJSON () {
208   const json = {
209     id: this._id,
210     name: this.name,
211     description: this.description,
212     podHost: this.podHost,
213     isLocal: this.isOwned(),
214     magnetUri: this.generateMagnetUri(),
215     author: this.author,
216     duration: this.duration,
217     tags: this.tags,
218     thumbnailPath: constants.STATIC_PATHS.THUMBNAILS + '/' + this.getThumbnailName(),
219     createdDate: this.createdDate
220   }
221
222   return json
223 }
224
225 function toRemoteJSON (callback) {
226   const self = this
227
228   // Convert thumbnail to base64
229   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
230   fs.readFile(thumbnailPath, function (err, thumbnailData) {
231     if (err) {
232       logger.error('Cannot read the thumbnail of the video')
233       return callback(err)
234     }
235
236     const remoteVideo = {
237       name: self.name,
238       description: self.description,
239       magnet: self.magnet,
240       remoteId: self._id,
241       author: self.author,
242       duration: self.duration,
243       thumbnailBase64: new Buffer(thumbnailData).toString('base64'),
244       tags: self.tags,
245       createdDate: self.createdDate,
246       extname: self.extname
247     }
248
249     return callback(null, remoteVideo)
250   })
251 }
252
253 // ------------------------------ STATICS ------------------------------
254
255 function generateThumbnailFromBase64 (video, thumbnailData, callback) {
256   // Creating the thumbnail for a remote video
257
258   const thumbnailName = video.getThumbnailName()
259   const thumbnailPath = constants.CONFIG.STORAGE.THUMBNAILS_DIR + thumbnailName
260   fs.writeFile(thumbnailPath, thumbnailData, { encoding: 'base64' }, function (err) {
261     if (err) return callback(err)
262
263     return callback(null, thumbnailName)
264   })
265 }
266
267 function getDurationFromFile (videoPath, callback) {
268   ffmpeg.ffprobe(videoPath, function (err, metadata) {
269     if (err) return callback(err)
270
271     return callback(null, Math.floor(metadata.format.duration))
272   })
273 }
274
275 function listForApi (start, count, sort, callback) {
276   const query = {}
277   return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
278 }
279
280 function listByHostAndRemoteId (fromHost, remoteId, callback) {
281   this.find({ podHost: fromHost, remoteId: remoteId }, callback)
282 }
283
284 function listByHost (fromHost, callback) {
285   this.find({ podHost: fromHost }, callback)
286 }
287
288 function listOwned (callback) {
289   // If remoteId is null this is *our* video
290   this.find({ remoteId: null }, callback)
291 }
292
293 function listOwnedByAuthor (author, callback) {
294   this.find({ remoteId: null, author: author }, callback)
295 }
296
297 function listRemotes (callback) {
298   this.find({ remoteId: { $ne: null } }, callback)
299 }
300
301 function load (id, callback) {
302   this.findById(id, callback)
303 }
304
305 function search (value, field, start, count, sort, callback) {
306   const query = {}
307   // Make an exact search with the magnet
308   if (field === 'magnetUri') {
309     const infoHash = magnetUtil.decode(value).infoHash
310     query.magnet = {
311       infoHash
312     }
313   } else if (field === 'tags') {
314     query[field] = value
315   } else {
316     query[field] = new RegExp(value, 'i')
317   }
318
319   modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
320 }
321
322 // ---------------------------------------------------------------------------
323
324 function removeThumbnail (video, callback) {
325   fs.unlink(constants.CONFIG.STORAGE.THUMBNAILS_DIR + video.getThumbnailName(), callback)
326 }
327
328 function removeFile (video, callback) {
329   fs.unlink(constants.CONFIG.STORAGE.VIDEOS_DIR + video.getVideoFilename(), callback)
330 }
331
332 function removeTorrent (video, callback) {
333   fs.unlink(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), callback)
334 }
335
336 function removePreview (video, callback) {
337   // Same name than video thumnail
338   fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
339 }
340
341 function createPreview (video, videoPath, callback) {
342   generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
343 }
344
345 function createThumbnail (video, videoPath, callback) {
346   generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
347 }
348
349 function generateImage (video, videoPath, folder, imageName, size, callback) {
350   const options = {
351     filename: imageName,
352     count: 1,
353     folder
354   }
355
356   if (!callback) {
357     callback = size
358   } else {
359     options.size = size
360   }
361
362   ffmpeg(videoPath)
363     .on('error', callback)
364     .on('end', function () {
365       callback(null, imageName)
366     })
367     .thumbnail(options)
368 }