Server: use video hook to send information to other pods when a video is
[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 map = require('lodash/map')
8 const parallel = require('async/parallel')
9 const parseTorrent = require('parse-torrent')
10 const pathUtils = require('path')
11 const values = require('lodash/values')
12
13 const constants = require('../initializers/constants')
14 const logger = require('../helpers/logger')
15 const friends = require('../lib/friends')
16 const modelUtils = require('./utils')
17 const customVideosValidators = require('../helpers/custom-validators').videos
18
19 // ---------------------------------------------------------------------------
20
21 module.exports = function (sequelize, DataTypes) {
22   // TODO: add indexes on searchable columns
23   const Video = sequelize.define('Video',
24     {
25       id: {
26         type: DataTypes.UUID,
27         defaultValue: DataTypes.UUIDV4,
28         primaryKey: true,
29         validate: {
30           isUUID: 4
31         }
32       },
33       name: {
34         type: DataTypes.STRING,
35         allowNull: false,
36         validate: {
37           nameValid: function (value) {
38             const res = customVideosValidators.isVideoNameValid(value)
39             if (res === false) throw new Error('Video name is not valid.')
40           }
41         }
42       },
43       extname: {
44         type: DataTypes.ENUM(values(constants.CONSTRAINTS_FIELDS.VIDEOS.EXTNAME)),
45         allowNull: false
46       },
47       remoteId: {
48         type: DataTypes.UUID,
49         allowNull: true,
50         validate: {
51           isUUID: 4
52         }
53       },
54       description: {
55         type: DataTypes.STRING,
56         allowNull: false,
57         validate: {
58           descriptionValid: function (value) {
59             const res = customVideosValidators.isVideoDescriptionValid(value)
60             if (res === false) throw new Error('Video description is not valid.')
61           }
62         }
63       },
64       infoHash: {
65         type: DataTypes.STRING,
66         allowNull: false,
67         validate: {
68           infoHashValid: function (value) {
69             const res = customVideosValidators.isVideoInfoHashValid(value)
70             if (res === false) throw new Error('Video info hash is not valid.')
71           }
72         }
73       },
74       duration: {
75         type: DataTypes.INTEGER,
76         allowNull: false,
77         validate: {
78           durationValid: function (value) {
79             const res = customVideosValidators.isVideoDurationValid(value)
80             if (res === false) throw new Error('Video duration is not valid.')
81           }
82         }
83       }
84     },
85     {
86       indexes: [
87         {
88           fields: [ 'authorId' ]
89         },
90         {
91           fields: [ 'remoteId' ]
92         },
93         {
94           fields: [ 'name' ]
95         },
96         {
97           fields: [ 'createdAt' ]
98         },
99         {
100           fields: [ 'duration' ]
101         },
102         {
103           fields: [ 'infoHash' ]
104         }
105       ],
106       classMethods: {
107         associate,
108
109         generateThumbnailFromBase64,
110         getDurationFromFile,
111         list,
112         listForApi,
113         listByHostAndRemoteId,
114         listOwnedAndPopulateAuthorAndTags,
115         listOwnedByAuthor,
116         load,
117         loadAndPopulateAuthor,
118         loadAndPopulateAuthorAndPodAndTags,
119         searchAndPopulateAuthorAndPodAndTags
120       },
121       instanceMethods: {
122         generateMagnetUri,
123         getVideoFilename,
124         getThumbnailName,
125         getPreviewName,
126         getTorrentName,
127         isOwned,
128         toFormatedJSON,
129         toRemoteJSON
130       },
131       hooks: {
132         beforeValidate,
133         beforeCreate,
134         afterDestroy
135       }
136     }
137   )
138
139   return Video
140 }
141
142 function beforeValidate (video, options, next) {
143   if (video.isOwned()) {
144     // 40 hexa length
145     video.infoHash = '0123456789abcdef0123456789abcdef01234567'
146   }
147
148   return next(null)
149 }
150
151 function beforeCreate (video, options, next) {
152   const tasks = []
153
154   if (video.isOwned()) {
155     const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
156
157     tasks.push(
158       // TODO: refractoring
159       function (callback) {
160         const options = {
161           announceList: [
162             [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
163           ],
164           urlList: [
165             constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
166           ]
167         }
168
169         createTorrent(videoPath, options, function (err, torrent) {
170           if (err) return callback(err)
171
172           fs.writeFile(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), torrent, function (err) {
173             if (err) return callback(err)
174
175             const parsedTorrent = parseTorrent(torrent)
176             video.set('infoHash', parsedTorrent.infoHash)
177             video.validate().asCallback(callback)
178           })
179         })
180       },
181       function (callback) {
182         createThumbnail(video, videoPath, callback)
183       },
184       function (callback) {
185         createPreview(video, videoPath, callback)
186       }
187     )
188
189     return parallel(tasks, next)
190   }
191
192   return next()
193 }
194
195 function afterDestroy (video, options, next) {
196   const tasks = []
197
198   tasks.push(
199     function (callback) {
200       removeThumbnail(video, callback)
201     }
202   )
203
204   if (video.isOwned()) {
205     tasks.push(
206       function (callback) {
207         removeFile(video, callback)
208       },
209
210       function (callback) {
211         removeTorrent(video, callback)
212       },
213
214       function (callback) {
215         removePreview(video, callback)
216       },
217
218       function (callback) {
219         const params = {
220           name: video.name,
221           remoteId: video.id
222         }
223
224         friends.removeVideoToFriends(params)
225
226         return callback()
227       }
228     )
229   }
230
231   parallel(tasks, next)
232 }
233
234 // ------------------------------ METHODS ------------------------------
235
236 function associate (models) {
237   this.belongsTo(models.Author, {
238     foreignKey: {
239       name: 'authorId',
240       allowNull: false
241     },
242     onDelete: 'cascade'
243   })
244
245   this.belongsToMany(models.Tag, {
246     foreignKey: 'videoId',
247     through: models.VideoTag,
248     onDelete: 'cascade'
249   })
250 }
251
252 function generateMagnetUri () {
253   let baseUrlHttp, baseUrlWs
254
255   if (this.isOwned()) {
256     baseUrlHttp = constants.CONFIG.WEBSERVER.URL
257     baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
258   } else {
259     baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
260     baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
261   }
262
263   const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
264   const announce = baseUrlWs + '/tracker/socket'
265   const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
266
267   const magnetHash = {
268     xs,
269     announce,
270     urlList,
271     infoHash: this.infoHash,
272     name: this.name
273   }
274
275   return magnetUtil.encode(magnetHash)
276 }
277
278 function getVideoFilename () {
279   if (this.isOwned()) return this.id + this.extname
280
281   return this.remoteId + this.extname
282 }
283
284 function getThumbnailName () {
285   // We always have a copy of the thumbnail
286   return this.id + '.jpg'
287 }
288
289 function getPreviewName () {
290   const extension = '.jpg'
291
292   if (this.isOwned()) return this.id + extension
293
294   return this.remoteId + extension
295 }
296
297 function getTorrentName () {
298   const extension = '.torrent'
299
300   if (this.isOwned()) return this.id + extension
301
302   return this.remoteId + extension
303 }
304
305 function isOwned () {
306   return this.remoteId === null
307 }
308
309 function toFormatedJSON () {
310   let podHost
311
312   if (this.Author.Pod) {
313     podHost = this.Author.Pod.host
314   } else {
315     // It means it's our video
316     podHost = constants.CONFIG.WEBSERVER.HOST
317   }
318
319   const json = {
320     id: this.id,
321     name: this.name,
322     description: this.description,
323     podHost,
324     isLocal: this.isOwned(),
325     magnetUri: this.generateMagnetUri(),
326     author: this.Author.name,
327     duration: this.duration,
328     tags: map(this.Tags, 'name'),
329     thumbnailPath: constants.STATIC_PATHS.THUMBNAILS + '/' + this.getThumbnailName(),
330     createdAt: this.createdAt
331   }
332
333   return json
334 }
335
336 function toRemoteJSON (callback) {
337   const self = this
338
339   // Convert thumbnail to base64
340   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
341   fs.readFile(thumbnailPath, function (err, thumbnailData) {
342     if (err) {
343       logger.error('Cannot read the thumbnail of the video')
344       return callback(err)
345     }
346
347     const remoteVideo = {
348       name: self.name,
349       description: self.description,
350       infoHash: self.infoHash,
351       remoteId: self.id,
352       author: self.Author.name,
353       duration: self.duration,
354       thumbnailBase64: new Buffer(thumbnailData).toString('base64'),
355       tags: map(self.Tags, 'name'),
356       createdAt: self.createdAt,
357       extname: self.extname
358     }
359
360     return callback(null, remoteVideo)
361   })
362 }
363
364 // ------------------------------ STATICS ------------------------------
365
366 function generateThumbnailFromBase64 (video, thumbnailData, callback) {
367   // Creating the thumbnail for a remote video
368
369   const thumbnailName = video.getThumbnailName()
370   const thumbnailPath = constants.CONFIG.STORAGE.THUMBNAILS_DIR + thumbnailName
371   fs.writeFile(thumbnailPath, thumbnailData, { encoding: 'base64' }, function (err) {
372     if (err) return callback(err)
373
374     return callback(null, thumbnailName)
375   })
376 }
377
378 function getDurationFromFile (videoPath, callback) {
379   ffmpeg.ffprobe(videoPath, function (err, metadata) {
380     if (err) return callback(err)
381
382     return callback(null, Math.floor(metadata.format.duration))
383   })
384 }
385
386 function list (callback) {
387   return this.find().asCallback()
388 }
389
390 function listForApi (start, count, sort, callback) {
391   const query = {
392     offset: start,
393     limit: count,
394     distinct: true, // For the count, a video can have many tags
395     order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
396     include: [
397       {
398         model: this.sequelize.models.Author,
399         include: [ { model: this.sequelize.models.Pod, required: false } ]
400       },
401
402       this.sequelize.models.Tag
403     ]
404   }
405
406   return this.findAndCountAll(query).asCallback(function (err, result) {
407     if (err) return callback(err)
408
409     return callback(null, result.rows, result.count)
410   })
411 }
412
413 function listByHostAndRemoteId (fromHost, remoteId, callback) {
414   const query = {
415     where: {
416       remoteId: remoteId
417     },
418     include: [
419       {
420         model: this.sequelize.models.Author,
421         include: [
422           {
423             model: this.sequelize.models.Pod,
424             required: true,
425             where: {
426               host: fromHost
427             }
428           }
429         ]
430       }
431     ]
432   }
433
434   return this.findAll(query).asCallback(callback)
435 }
436
437 function listOwnedAndPopulateAuthorAndTags (callback) {
438   // If remoteId is null this is *our* video
439   const query = {
440     where: {
441       remoteId: null
442     },
443     include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
444   }
445
446   return this.findAll(query).asCallback(callback)
447 }
448
449 function listOwnedByAuthor (author, callback) {
450   const query = {
451     where: {
452       remoteId: null
453     },
454     include: [
455       {
456         model: this.sequelize.models.Author,
457         where: {
458           name: author
459         }
460       }
461     ]
462   }
463
464   return this.findAll(query).asCallback(callback)
465 }
466
467 function load (id, callback) {
468   return this.findById(id).asCallback(callback)
469 }
470
471 function loadAndPopulateAuthor (id, callback) {
472   const options = {
473     include: [ this.sequelize.models.Author ]
474   }
475
476   return this.findById(id, options).asCallback(callback)
477 }
478
479 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
480   const options = {
481     include: [
482       {
483         model: this.sequelize.models.Author,
484         include: [ { model: this.sequelize.models.Pod, required: false } ]
485       },
486       this.sequelize.models.Tag
487     ]
488   }
489
490   return this.findById(id, options).asCallback(callback)
491 }
492
493 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
494   const podInclude = {
495     model: this.sequelize.models.Pod,
496     required: false
497   }
498
499   const authorInclude = {
500     model: this.sequelize.models.Author,
501     include: [
502       podInclude
503     ]
504   }
505
506   const tagInclude = {
507     model: this.sequelize.models.Tag
508   }
509
510   const query = {
511     where: {},
512     offset: start,
513     limit: count,
514     distinct: true, // For the count, a video can have many tags
515     order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
516   }
517
518   // Make an exact search with the magnet
519   if (field === 'magnetUri') {
520     const infoHash = magnetUtil.decode(value).infoHash
521     query.where.infoHash = infoHash
522   } else if (field === 'tags') {
523     const escapedValue = this.sequelize.escape('%' + value + '%')
524     query.where = {
525       id: {
526         $in: this.sequelize.literal(
527           '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
528         )
529       }
530     }
531   } else if (field === 'host') {
532     // FIXME: Include our pod? (not stored in the database)
533     podInclude.where = {
534       host: {
535         $like: '%' + value + '%'
536       }
537     }
538     podInclude.required = true
539   } else if (field === 'author') {
540     authorInclude.where = {
541       name: {
542         $like: '%' + value + '%'
543       }
544     }
545
546     // authorInclude.or = true
547   } else {
548     query.where[field] = {
549       $like: '%' + value + '%'
550     }
551   }
552
553   query.include = [
554     authorInclude, tagInclude
555   ]
556
557   if (tagInclude.where) {
558     // query.include.push([ this.sequelize.models.Tag ])
559   }
560
561   return this.findAndCountAll(query).asCallback(function (err, result) {
562     if (err) return callback(err)
563
564     return callback(null, result.rows, result.count)
565   })
566 }
567
568 // ---------------------------------------------------------------------------
569
570 function removeThumbnail (video, callback) {
571   fs.unlink(constants.CONFIG.STORAGE.THUMBNAILS_DIR + video.getThumbnailName(), callback)
572 }
573
574 function removeFile (video, callback) {
575   fs.unlink(constants.CONFIG.STORAGE.VIDEOS_DIR + video.getVideoFilename(), callback)
576 }
577
578 function removeTorrent (video, callback) {
579   fs.unlink(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), callback)
580 }
581
582 function removePreview (video, callback) {
583   // Same name than video thumnail
584   fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
585 }
586
587 function createPreview (video, videoPath, callback) {
588   generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
589 }
590
591 function createThumbnail (video, videoPath, callback) {
592   generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
593 }
594
595 function generateImage (video, videoPath, folder, imageName, size, callback) {
596   const options = {
597     filename: imageName,
598     count: 1,
599     folder
600   }
601
602   if (!callback) {
603     callback = size
604   } else {
605     options.size = size
606   }
607
608   ffmpeg(videoPath)
609     .on('error', callback)
610     .on('end', function () {
611       callback(null, imageName)
612     })
613     .thumbnail(options)
614 }