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')
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
20 // ---------------------------------------------------------------------------
22 module
.exports = function (sequelize
, DataTypes
) {
23 const Video
= sequelize
.define('Video',
27 defaultValue: DataTypes
.UUIDV4
,
34 type: DataTypes
.STRING
,
37 nameValid: function (value
) {
38 const res
= customVideosValidators
.isVideoNameValid(value
)
39 if (res
=== false) throw new Error('Video name is not valid.')
44 type: DataTypes
.ENUM(values(constants
.CONSTRAINTS_FIELDS
.VIDEOS
.EXTNAME
)),
55 type: DataTypes
.INTEGER
,
58 categoryValid: function (value
) {
59 const res
= customVideosValidators
.isVideoCategoryValid(value
)
60 if (res
=== false) throw new Error('Video category is not valid.')
65 type: DataTypes
.INTEGER
,
68 licenceValid: function (value
) {
69 const res
= customVideosValidators
.isVideoLicenceValid(value
)
70 if (res
=== false) throw new Error('Video licence is not valid.')
75 type: DataTypes
.BOOLEAN
,
78 nsfwValid: function (value
) {
79 const res
= customVideosValidators
.isVideoNSFWValid(value
)
80 if (res
=== false) throw new Error('Video nsfw attribute is not valid.')
85 type: DataTypes
.STRING
,
88 descriptionValid: function (value
) {
89 const res
= customVideosValidators
.isVideoDescriptionValid(value
)
90 if (res
=== false) throw new Error('Video description is not valid.')
95 type: DataTypes
.STRING
,
98 infoHashValid: function (value
) {
99 const res
= customVideosValidators
.isVideoInfoHashValid(value
)
100 if (res
=== false) throw new Error('Video info hash is not valid.')
105 type: DataTypes
.INTEGER
,
108 durationValid: function (value
) {
109 const res
= customVideosValidators
.isVideoDurationValid(value
)
110 if (res
=== false) throw new Error('Video duration is not valid.')
115 type: DataTypes
.INTEGER
,
124 type: DataTypes
.INTEGER
,
133 type: DataTypes
.INTEGER
,
145 fields: [ 'authorId' ]
148 fields: [ 'remoteId' ]
154 fields: [ 'createdAt' ]
157 fields: [ 'duration' ]
160 fields: [ 'infoHash' ]
172 generateThumbnailFromData
,
176 listOwnedAndPopulateAuthorAndTags
,
179 loadByHostAndRemoteId
,
180 loadAndPopulateAuthor
,
181 loadAndPopulateAuthorAndPodAndTags
,
182 searchAndPopulateAuthorAndPodAndTags
206 function beforeValidate (video
, options
, next
) {
207 // Put a fake infoHash if it does not exists yet
208 if (video
.isOwned() && !video
.infoHash
) {
210 video
.infoHash
= '0123456789abcdef0123456789abcdef01234567'
216 function beforeCreate (video
, options
, next
) {
219 if (video
.isOwned()) {
220 const videoPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
223 function createVideoTorrent (callback
) {
226 [ constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
+ '/tracker/socket' ]
229 constants
.CONFIG
.WEBSERVER
.URL
+ constants
.STATIC_PATHS
.WEBSEED
+ video
.getVideoFilename()
233 createTorrent(videoPath
, options
, function (err
, torrent
) {
234 if (err
) return callback(err
)
236 const filePath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
, video
.getTorrentName())
237 fs
.writeFile(filePath
, torrent
, function (err
) {
238 if (err
) return callback(err
)
240 const parsedTorrent
= parseTorrent(torrent
)
241 video
.set('infoHash', parsedTorrent
.infoHash
)
242 video
.validate().asCallback(callback
)
247 function createVideoThumbnail (callback
) {
248 createThumbnail(video
, videoPath
, callback
)
251 function createVIdeoPreview (callback
) {
252 createPreview(video
, videoPath
, callback
)
256 return parallel(tasks
, next
)
262 function afterDestroy (video
, options
, next
) {
266 function (callback
) {
267 removeThumbnail(video
, callback
)
271 if (video
.isOwned()) {
273 function removeVideoFile (callback
) {
274 removeFile(video
, callback
)
277 function removeVideoTorrent (callback
) {
278 removeTorrent(video
, callback
)
281 function removeVideoPreview (callback
) {
282 removePreview(video
, callback
)
285 function removeVideoToFriends (callback
) {
290 friends
.removeVideoToFriends(params
)
297 parallel(tasks
, next
)
300 // ------------------------------ METHODS ------------------------------
302 function associate (models
) {
303 this.belongsTo(models
.Author
, {
311 this.belongsToMany(models
.Tag
, {
312 foreignKey: 'videoId',
313 through: models
.VideoTag
,
317 this.hasMany(models
.VideoAbuse
, {
326 function generateMagnetUri () {
327 let baseUrlHttp
, baseUrlWs
329 if (this.isOwned()) {
330 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
331 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
333 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
334 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
337 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
338 const announce
= baseUrlWs
+ '/tracker/socket'
339 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
345 infoHash: this.infoHash
,
349 return magnetUtil
.encode(magnetHash
)
352 function getVideoFilename () {
353 if (this.isOwned()) return this.id
+ this.extname
355 return this.remoteId
+ this.extname
358 function getThumbnailName () {
359 // We always have a copy of the thumbnail
360 return this.id
+ '.jpg'
363 function getPreviewName () {
364 const extension
= '.jpg'
366 if (this.isOwned()) return this.id
+ extension
368 return this.remoteId
+ extension
371 function getTorrentName () {
372 const extension
= '.torrent'
374 if (this.isOwned()) return this.id
+ extension
376 return this.remoteId
+ extension
379 function isOwned () {
380 return this.remoteId
=== null
383 function toFormatedJSON () {
386 if (this.Author
.Pod
) {
387 podHost
= this.Author
.Pod
.host
389 // It means it's our video
390 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
393 // Maybe our pod is not up to date and there are new categories since our version
394 let categoryLabel
= constants
.VIDEO_CATEGORIES
[this.category
]
395 if (!categoryLabel
) categoryLabel
= 'Misc'
397 // Maybe our pod is not up to date and there are new licences since our version
398 let licenceLabel
= constants
.VIDEO_LICENCES
[this.licence
]
399 if (!licenceLabel
) licenceLabel
= 'Unknown'
404 category: this.category
,
406 licence: this.licence
,
409 description: this.description
,
411 isLocal: this.isOwned(),
412 magnetUri: this.generateMagnetUri(),
413 author: this.Author
.name
,
414 duration: this.duration
,
417 dislikes: this.dislikes
,
418 tags: map(this.Tags
, 'name'),
419 thumbnailPath: pathUtils
.join(constants
.STATIC_PATHS
.THUMBNAILS
, this.getThumbnailName()),
420 createdAt: this.createdAt
,
421 updatedAt: this.updatedAt
427 function toAddRemoteJSON (callback
) {
430 // Get thumbnail data to send to the other pod
431 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, this.getThumbnailName())
432 fs
.readFile(thumbnailPath
, function (err
, thumbnailData
) {
434 logger
.error('Cannot read the thumbnail of the video')
438 const remoteVideo
= {
440 category: self
.category
,
441 licence: self
.licence
,
443 description: self
.description
,
444 infoHash: self
.infoHash
,
446 author: self
.Author
.name
,
447 duration: self
.duration
,
448 thumbnailData: thumbnailData
.toString('binary'),
449 tags: map(self
.Tags
, 'name'),
450 createdAt: self
.createdAt
,
451 updatedAt: self
.updatedAt
,
452 extname: self
.extname
,
455 dislikes: self
.dislikes
458 return callback(null, remoteVideo
)
462 function toUpdateRemoteJSON (callback
) {
465 category: this.category
,
466 licence: this.licence
,
468 description: this.description
,
469 infoHash: this.infoHash
,
471 author: this.Author
.name
,
472 duration: this.duration
,
473 tags: map(this.Tags
, 'name'),
474 createdAt: this.createdAt
,
475 updatedAt: this.updatedAt
,
476 extname: this.extname
,
479 dislikes: this.dislikes
485 // ------------------------------ STATICS ------------------------------
487 function generateThumbnailFromData (video
, thumbnailData
, callback
) {
488 // Creating the thumbnail for a remote video
490 const thumbnailName
= video
.getThumbnailName()
491 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, thumbnailName
)
492 fs
.writeFile(thumbnailPath
, Buffer
.from(thumbnailData
, 'binary'), function (err
) {
493 if (err
) return callback(err
)
495 return callback(null, thumbnailName
)
499 function getDurationFromFile (videoPath
, callback
) {
500 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
501 if (err
) return callback(err
)
503 return callback(null, Math
.floor(metadata
.format
.duration
))
507 function list (callback
) {
508 return this.findAll().asCallback(callback
)
511 function listForApi (start
, count
, sort
, callback
) {
515 distinct: true, // For the count, a video can have many tags
516 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ],
519 model: this.sequelize
.models
.Author
,
520 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
523 this.sequelize
.models
.Tag
527 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
528 if (err
) return callback(err
)
530 return callback(null, result
.rows
, result
.count
)
534 function loadByHostAndRemoteId (fromHost
, remoteId
, callback
) {
541 model: this.sequelize
.models
.Author
,
544 model: this.sequelize
.models
.Pod
,
555 return this.findOne(query
).asCallback(callback
)
558 function listOwnedAndPopulateAuthorAndTags (callback
) {
559 // If remoteId is null this is *our* video
564 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
567 return this.findAll(query
).asCallback(callback
)
570 function listOwnedByAuthor (author
, callback
) {
577 model: this.sequelize
.models
.Author
,
585 return this.findAll(query
).asCallback(callback
)
588 function load (id
, callback
) {
589 return this.findById(id
).asCallback(callback
)
592 function loadAndPopulateAuthor (id
, callback
) {
594 include: [ this.sequelize
.models
.Author
]
597 return this.findById(id
, options
).asCallback(callback
)
600 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
604 model: this.sequelize
.models
.Author
,
605 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
607 this.sequelize
.models
.Tag
611 return this.findById(id
, options
).asCallback(callback
)
614 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
616 model: this.sequelize
.models
.Pod
,
620 const authorInclude
= {
621 model: this.sequelize
.models
.Author
,
628 model: this.sequelize
.models
.Tag
635 distinct: true, // For the count, a video can have many tags
636 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ]
639 // Make an exact search with the magnet
640 if (field
=== 'magnetUri') {
641 const infoHash
= magnetUtil
.decode(value
).infoHash
642 query
.where
.infoHash
= infoHash
643 } else if (field
=== 'tags') {
644 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
647 $in: this.sequelize
.literal(
648 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
652 } else if (field
=== 'host') {
653 // FIXME: Include our pod? (not stored in the database)
656 $like: '%' + value
+ '%'
659 podInclude
.required
= true
660 } else if (field
=== 'author') {
661 authorInclude
.where
= {
663 $like: '%' + value
+ '%'
667 // authorInclude.or = true
669 query
.where
[field
] = {
670 $like: '%' + value
+ '%'
675 authorInclude
, tagInclude
678 if (tagInclude
.where
) {
679 // query.include.push([ this.sequelize.models.Tag ])
682 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
683 if (err
) return callback(err
)
685 return callback(null, result
.rows
, result
.count
)
689 // ---------------------------------------------------------------------------
691 function removeThumbnail (video
, callback
) {
692 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName())
693 fs
.unlink(thumbnailPath
, callback
)
696 function removeFile (video
, callback
) {
697 const filePath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
698 fs
.unlink(filePath
, callback
)
701 function removeTorrent (video
, callback
) {
702 const torrenPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
, video
.getTorrentName())
703 fs
.unlink(torrenPath
, callback
)
706 function removePreview (video
, callback
) {
707 // Same name than video thumnail
708 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
711 function createPreview (video
, videoPath
, callback
) {
712 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
715 function createThumbnail (video
, videoPath
, callback
) {
716 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
719 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
733 .on('error', callback
)
734 .on('end', function () {
735 callback(null, imageName
)