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