Server: add video language attribute
[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       category: {
55         type: DataTypes.INTEGER,
56         allowNull: false,
57         validate: {
58           categoryValid: function (value) {
59             const res = customVideosValidators.isVideoCategoryValid(value)
60             if (res === false) throw new Error('Video category is not valid.')
61           }
62         }
63       },
64       licence: {
65         type: DataTypes.INTEGER,
66         allowNull: false,
67         defaultValue: null,
68         validate: {
69           licenceValid: function (value) {
70             const res = customVideosValidators.isVideoLicenceValid(value)
71             if (res === false) throw new Error('Video licence is not valid.')
72           }
73         }
74       },
75       language: {
76         type: DataTypes.INTEGER,
77         allowNull: true,
78         validate: {
79           languageValid: function (value) {
80             const res = customVideosValidators.isVideoLanguageValid(value)
81             if (res === false) throw new Error('Video language is not valid.')
82           }
83         }
84       },
85       nsfw: {
86         type: DataTypes.BOOLEAN,
87         allowNull: false,
88         validate: {
89           nsfwValid: function (value) {
90             const res = customVideosValidators.isVideoNSFWValid(value)
91             if (res === false) throw new Error('Video nsfw attribute is not valid.')
92           }
93         }
94       },
95       description: {
96         type: DataTypes.STRING,
97         allowNull: false,
98         validate: {
99           descriptionValid: function (value) {
100             const res = customVideosValidators.isVideoDescriptionValid(value)
101             if (res === false) throw new Error('Video description is not valid.')
102           }
103         }
104       },
105       infoHash: {
106         type: DataTypes.STRING,
107         allowNull: false,
108         validate: {
109           infoHashValid: function (value) {
110             const res = customVideosValidators.isVideoInfoHashValid(value)
111             if (res === false) throw new Error('Video info hash is not valid.')
112           }
113         }
114       },
115       duration: {
116         type: DataTypes.INTEGER,
117         allowNull: false,
118         validate: {
119           durationValid: function (value) {
120             const res = customVideosValidators.isVideoDurationValid(value)
121             if (res === false) throw new Error('Video duration is not valid.')
122           }
123         }
124       },
125       views: {
126         type: DataTypes.INTEGER,
127         allowNull: false,
128         defaultValue: 0,
129         validate: {
130           min: 0,
131           isInt: true
132         }
133       },
134       likes: {
135         type: DataTypes.INTEGER,
136         allowNull: false,
137         defaultValue: 0,
138         validate: {
139           min: 0,
140           isInt: true
141         }
142       },
143       dislikes: {
144         type: DataTypes.INTEGER,
145         allowNull: false,
146         defaultValue: 0,
147         validate: {
148           min: 0,
149           isInt: true
150         }
151       }
152     },
153     {
154       indexes: [
155         {
156           fields: [ 'authorId' ]
157         },
158         {
159           fields: [ 'remoteId' ]
160         },
161         {
162           fields: [ 'name' ]
163         },
164         {
165           fields: [ 'createdAt' ]
166         },
167         {
168           fields: [ 'duration' ]
169         },
170         {
171           fields: [ 'infoHash' ]
172         },
173         {
174           fields: [ 'views' ]
175         },
176         {
177           fields: [ 'likes' ]
178         }
179       ],
180       classMethods: {
181         associate,
182
183         generateThumbnailFromData,
184         getDurationFromFile,
185         list,
186         listForApi,
187         listOwnedAndPopulateAuthorAndTags,
188         listOwnedByAuthor,
189         load,
190         loadByHostAndRemoteId,
191         loadAndPopulateAuthor,
192         loadAndPopulateAuthorAndPodAndTags,
193         searchAndPopulateAuthorAndPodAndTags
194       },
195       instanceMethods: {
196         generateMagnetUri,
197         getVideoFilename,
198         getThumbnailName,
199         getPreviewName,
200         getTorrentName,
201         isOwned,
202         toFormatedJSON,
203         toAddRemoteJSON,
204         toUpdateRemoteJSON
205       },
206       hooks: {
207         beforeValidate,
208         beforeCreate,
209         afterDestroy
210       }
211     }
212   )
213
214   return Video
215 }
216
217 function beforeValidate (video, options, next) {
218   // Put a fake infoHash if it does not exists yet
219   if (video.isOwned() && !video.infoHash) {
220     // 40 hexa length
221     video.infoHash = '0123456789abcdef0123456789abcdef01234567'
222   }
223
224   return next(null)
225 }
226
227 function beforeCreate (video, options, next) {
228   const tasks = []
229
230   if (video.isOwned()) {
231     const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
232
233     tasks.push(
234       function createVideoTorrent (callback) {
235         const options = {
236           announceList: [
237             [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
238           ],
239           urlList: [
240             constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
241           ]
242         }
243
244         createTorrent(videoPath, options, function (err, torrent) {
245           if (err) return callback(err)
246
247           const filePath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
248           fs.writeFile(filePath, torrent, function (err) {
249             if (err) return callback(err)
250
251             const parsedTorrent = parseTorrent(torrent)
252             video.set('infoHash', parsedTorrent.infoHash)
253             video.validate().asCallback(callback)
254           })
255         })
256       },
257
258       function createVideoThumbnail (callback) {
259         createThumbnail(video, videoPath, callback)
260       },
261
262       function createVIdeoPreview (callback) {
263         createPreview(video, videoPath, callback)
264       }
265     )
266
267     return parallel(tasks, next)
268   }
269
270   return next()
271 }
272
273 function afterDestroy (video, options, next) {
274   const tasks = []
275
276   tasks.push(
277     function (callback) {
278       removeThumbnail(video, callback)
279     }
280   )
281
282   if (video.isOwned()) {
283     tasks.push(
284       function removeVideoFile (callback) {
285         removeFile(video, callback)
286       },
287
288       function removeVideoTorrent (callback) {
289         removeTorrent(video, callback)
290       },
291
292       function removeVideoPreview (callback) {
293         removePreview(video, callback)
294       },
295
296       function removeVideoToFriends (callback) {
297         const params = {
298           remoteId: video.id
299         }
300
301         friends.removeVideoToFriends(params)
302
303         return callback()
304       }
305     )
306   }
307
308   parallel(tasks, next)
309 }
310
311 // ------------------------------ METHODS ------------------------------
312
313 function associate (models) {
314   this.belongsTo(models.Author, {
315     foreignKey: {
316       name: 'authorId',
317       allowNull: false
318     },
319     onDelete: 'cascade'
320   })
321
322   this.belongsToMany(models.Tag, {
323     foreignKey: 'videoId',
324     through: models.VideoTag,
325     onDelete: 'cascade'
326   })
327
328   this.hasMany(models.VideoAbuse, {
329     foreignKey: {
330       name: 'videoId',
331       allowNull: false
332     },
333     onDelete: 'cascade'
334   })
335 }
336
337 function generateMagnetUri () {
338   let baseUrlHttp, baseUrlWs
339
340   if (this.isOwned()) {
341     baseUrlHttp = constants.CONFIG.WEBSERVER.URL
342     baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
343   } else {
344     baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
345     baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
346   }
347
348   const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
349   const announce = baseUrlWs + '/tracker/socket'
350   const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
351
352   const magnetHash = {
353     xs,
354     announce,
355     urlList,
356     infoHash: this.infoHash,
357     name: this.name
358   }
359
360   return magnetUtil.encode(magnetHash)
361 }
362
363 function getVideoFilename () {
364   if (this.isOwned()) return this.id + this.extname
365
366   return this.remoteId + this.extname
367 }
368
369 function getThumbnailName () {
370   // We always have a copy of the thumbnail
371   return this.id + '.jpg'
372 }
373
374 function getPreviewName () {
375   const extension = '.jpg'
376
377   if (this.isOwned()) return this.id + extension
378
379   return this.remoteId + extension
380 }
381
382 function getTorrentName () {
383   const extension = '.torrent'
384
385   if (this.isOwned()) return this.id + extension
386
387   return this.remoteId + extension
388 }
389
390 function isOwned () {
391   return this.remoteId === null
392 }
393
394 function toFormatedJSON () {
395   let podHost
396
397   if (this.Author.Pod) {
398     podHost = this.Author.Pod.host
399   } else {
400     // It means it's our video
401     podHost = constants.CONFIG.WEBSERVER.HOST
402   }
403
404   // Maybe our pod is not up to date and there are new categories since our version
405   let categoryLabel = constants.VIDEO_CATEGORIES[this.category]
406   if (!categoryLabel) categoryLabel = 'Misc'
407
408   // Maybe our pod is not up to date and there are new licences since our version
409   let licenceLabel = constants.VIDEO_LICENCES[this.licence]
410   if (!licenceLabel) licenceLabel = 'Unknown'
411
412   // Language is an optional attribute
413   let languageLabel = constants.VIDEO_LANGUAGES[this.language]
414   if (!languageLabel) languageLabel = 'Unknown'
415
416   const json = {
417     id: this.id,
418     name: this.name,
419     category: this.category,
420     categoryLabel,
421     licence: this.licence,
422     licenceLabel,
423     language: this.language,
424     languageLabel,
425     nsfw: this.nsfw,
426     description: this.description,
427     podHost,
428     isLocal: this.isOwned(),
429     magnetUri: this.generateMagnetUri(),
430     author: this.Author.name,
431     duration: this.duration,
432     views: this.views,
433     likes: this.likes,
434     dislikes: this.dislikes,
435     tags: map(this.Tags, 'name'),
436     thumbnailPath: pathUtils.join(constants.STATIC_PATHS.THUMBNAILS, this.getThumbnailName()),
437     createdAt: this.createdAt,
438     updatedAt: this.updatedAt
439   }
440
441   return json
442 }
443
444 function toAddRemoteJSON (callback) {
445   const self = this
446
447   // Get thumbnail data to send to the other pod
448   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
449   fs.readFile(thumbnailPath, function (err, thumbnailData) {
450     if (err) {
451       logger.error('Cannot read the thumbnail of the video')
452       return callback(err)
453     }
454
455     const remoteVideo = {
456       name: self.name,
457       category: self.category,
458       licence: self.licence,
459       language: self.language,
460       nsfw: self.nsfw,
461       description: self.description,
462       infoHash: self.infoHash,
463       remoteId: self.id,
464       author: self.Author.name,
465       duration: self.duration,
466       thumbnailData: thumbnailData.toString('binary'),
467       tags: map(self.Tags, 'name'),
468       createdAt: self.createdAt,
469       updatedAt: self.updatedAt,
470       extname: self.extname,
471       views: self.views,
472       likes: self.likes,
473       dislikes: self.dislikes
474     }
475
476     return callback(null, remoteVideo)
477   })
478 }
479
480 function toUpdateRemoteJSON (callback) {
481   const json = {
482     name: this.name,
483     category: this.category,
484     licence: this.licence,
485     language: this.language,
486     nsfw: this.nsfw,
487     description: this.description,
488     infoHash: this.infoHash,
489     remoteId: this.id,
490     author: this.Author.name,
491     duration: this.duration,
492     tags: map(this.Tags, 'name'),
493     createdAt: this.createdAt,
494     updatedAt: this.updatedAt,
495     extname: this.extname,
496     views: this.views,
497     likes: this.likes,
498     dislikes: this.dislikes
499   }
500
501   return json
502 }
503
504 // ------------------------------ STATICS ------------------------------
505
506 function generateThumbnailFromData (video, thumbnailData, callback) {
507   // Creating the thumbnail for a remote video
508
509   const thumbnailName = video.getThumbnailName()
510   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
511   fs.writeFile(thumbnailPath, Buffer.from(thumbnailData, 'binary'), function (err) {
512     if (err) return callback(err)
513
514     return callback(null, thumbnailName)
515   })
516 }
517
518 function getDurationFromFile (videoPath, callback) {
519   ffmpeg.ffprobe(videoPath, function (err, metadata) {
520     if (err) return callback(err)
521
522     return callback(null, Math.floor(metadata.format.duration))
523   })
524 }
525
526 function list (callback) {
527   return this.findAll().asCallback(callback)
528 }
529
530 function listForApi (start, count, sort, callback) {
531   const query = {
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     include: [
537       {
538         model: this.sequelize.models.Author,
539         include: [ { model: this.sequelize.models.Pod, required: false } ]
540       },
541
542       this.sequelize.models.Tag
543     ]
544   }
545
546   return this.findAndCountAll(query).asCallback(function (err, result) {
547     if (err) return callback(err)
548
549     return callback(null, result.rows, result.count)
550   })
551 }
552
553 function loadByHostAndRemoteId (fromHost, remoteId, callback) {
554   const query = {
555     where: {
556       remoteId: remoteId
557     },
558     include: [
559       {
560         model: this.sequelize.models.Author,
561         include: [
562           {
563             model: this.sequelize.models.Pod,
564             required: true,
565             where: {
566               host: fromHost
567             }
568           }
569         ]
570       }
571     ]
572   }
573
574   return this.findOne(query).asCallback(callback)
575 }
576
577 function listOwnedAndPopulateAuthorAndTags (callback) {
578   // If remoteId is null this is *our* video
579   const query = {
580     where: {
581       remoteId: null
582     },
583     include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
584   }
585
586   return this.findAll(query).asCallback(callback)
587 }
588
589 function listOwnedByAuthor (author, callback) {
590   const query = {
591     where: {
592       remoteId: null
593     },
594     include: [
595       {
596         model: this.sequelize.models.Author,
597         where: {
598           name: author
599         }
600       }
601     ]
602   }
603
604   return this.findAll(query).asCallback(callback)
605 }
606
607 function load (id, callback) {
608   return this.findById(id).asCallback(callback)
609 }
610
611 function loadAndPopulateAuthor (id, callback) {
612   const options = {
613     include: [ this.sequelize.models.Author ]
614   }
615
616   return this.findById(id, options).asCallback(callback)
617 }
618
619 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
620   const options = {
621     include: [
622       {
623         model: this.sequelize.models.Author,
624         include: [ { model: this.sequelize.models.Pod, required: false } ]
625       },
626       this.sequelize.models.Tag
627     ]
628   }
629
630   return this.findById(id, options).asCallback(callback)
631 }
632
633 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
634   const podInclude = {
635     model: this.sequelize.models.Pod,
636     required: false
637   }
638
639   const authorInclude = {
640     model: this.sequelize.models.Author,
641     include: [
642       podInclude
643     ]
644   }
645
646   const tagInclude = {
647     model: this.sequelize.models.Tag
648   }
649
650   const query = {
651     where: {},
652     offset: start,
653     limit: count,
654     distinct: true, // For the count, a video can have many tags
655     order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
656   }
657
658   // Make an exact search with the magnet
659   if (field === 'magnetUri') {
660     const infoHash = magnetUtil.decode(value).infoHash
661     query.where.infoHash = infoHash
662   } else if (field === 'tags') {
663     const escapedValue = this.sequelize.escape('%' + value + '%')
664     query.where = {
665       id: {
666         $in: this.sequelize.literal(
667           '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
668         )
669       }
670     }
671   } else if (field === 'host') {
672     // FIXME: Include our pod? (not stored in the database)
673     podInclude.where = {
674       host: {
675         $like: '%' + value + '%'
676       }
677     }
678     podInclude.required = true
679   } else if (field === 'author') {
680     authorInclude.where = {
681       name: {
682         $like: '%' + value + '%'
683       }
684     }
685
686     // authorInclude.or = true
687   } else {
688     query.where[field] = {
689       $like: '%' + value + '%'
690     }
691   }
692
693   query.include = [
694     authorInclude, tagInclude
695   ]
696
697   if (tagInclude.where) {
698     // query.include.push([ this.sequelize.models.Tag ])
699   }
700
701   return this.findAndCountAll(query).asCallback(function (err, result) {
702     if (err) return callback(err)
703
704     return callback(null, result.rows, result.count)
705   })
706 }
707
708 // ---------------------------------------------------------------------------
709
710 function removeThumbnail (video, callback) {
711   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
712   fs.unlink(thumbnailPath, callback)
713 }
714
715 function removeFile (video, callback) {
716   const filePath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
717   fs.unlink(filePath, callback)
718 }
719
720 function removeTorrent (video, callback) {
721   const torrenPath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
722   fs.unlink(torrenPath, callback)
723 }
724
725 function removePreview (video, callback) {
726   // Same name than video thumnail
727   fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
728 }
729
730 function createPreview (video, videoPath, callback) {
731   generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
732 }
733
734 function createThumbnail (video, videoPath, callback) {
735   generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
736 }
737
738 function generateImage (video, videoPath, folder, imageName, size, callback) {
739   const options = {
740     filename: imageName,
741     count: 1,
742     folder
743   }
744
745   if (!callback) {
746     callback = size
747   } else {
748     options.size = size
749   }
750
751   ffmpeg(videoPath)
752     .on('error', callback)
753     .on('end', function () {
754       callback(null, imageName)
755     })
756     .thumbnail(options)
757 }