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
.STRING
,
58 descriptionValid: function (value
) {
59 const res
= customVideosValidators
.isVideoDescriptionValid(value
)
60 if (res
=== false) throw new Error('Video description is not valid.')
65 type: DataTypes
.STRING
,
68 infoHashValid: function (value
) {
69 const res
= customVideosValidators
.isVideoInfoHashValid(value
)
70 if (res
=== false) throw new Error('Video info hash is not valid.')
75 type: DataTypes
.INTEGER
,
78 durationValid: function (value
) {
79 const res
= customVideosValidators
.isVideoDurationValid(value
)
80 if (res
=== false) throw new Error('Video duration is not valid.')
85 type: DataTypes
.INTEGER
,
94 type: DataTypes
.INTEGER
,
103 type: DataTypes
.INTEGER
,
115 fields: [ 'authorId' ]
118 fields: [ 'remoteId' ]
124 fields: [ 'createdAt' ]
127 fields: [ 'duration' ]
130 fields: [ 'infoHash' ]
142 generateThumbnailFromData
,
146 listOwnedAndPopulateAuthorAndTags
,
149 loadByHostAndRemoteId
,
150 loadAndPopulateAuthor
,
151 loadAndPopulateAuthorAndPodAndTags
,
152 searchAndPopulateAuthorAndPodAndTags
176 function beforeValidate (video
, options
, next
) {
177 // Put a fake infoHash if it does not exists yet
178 if (video
.isOwned() && !video
.infoHash
) {
180 video
.infoHash
= '0123456789abcdef0123456789abcdef01234567'
186 function beforeCreate (video
, options
, next
) {
189 if (video
.isOwned()) {
190 const videoPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
193 function createVideoTorrent (callback
) {
196 [ constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
+ '/tracker/socket' ]
199 constants
.CONFIG
.WEBSERVER
.URL
+ constants
.STATIC_PATHS
.WEBSEED
+ video
.getVideoFilename()
203 createTorrent(videoPath
, options
, function (err
, torrent
) {
204 if (err
) return callback(err
)
206 const filePath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
, video
.getTorrentName())
207 fs
.writeFile(filePath
, torrent
, function (err
) {
208 if (err
) return callback(err
)
210 const parsedTorrent
= parseTorrent(torrent
)
211 video
.set('infoHash', parsedTorrent
.infoHash
)
212 video
.validate().asCallback(callback
)
217 function createVideoThumbnail (callback
) {
218 createThumbnail(video
, videoPath
, callback
)
221 function createVIdeoPreview (callback
) {
222 createPreview(video
, videoPath
, callback
)
226 return parallel(tasks
, next
)
232 function afterDestroy (video
, options
, next
) {
236 function (callback
) {
237 removeThumbnail(video
, callback
)
241 if (video
.isOwned()) {
243 function removeVideoFile (callback
) {
244 removeFile(video
, callback
)
247 function removeVideoTorrent (callback
) {
248 removeTorrent(video
, callback
)
251 function removeVideoPreview (callback
) {
252 removePreview(video
, callback
)
255 function removeVideoToFriends (callback
) {
260 friends
.removeVideoToFriends(params
)
267 parallel(tasks
, next
)
270 // ------------------------------ METHODS ------------------------------
272 function associate (models
) {
273 this.belongsTo(models
.Author
, {
281 this.belongsToMany(models
.Tag
, {
282 foreignKey: 'videoId',
283 through: models
.VideoTag
,
287 this.hasMany(models
.VideoAbuse
, {
296 function generateMagnetUri () {
297 let baseUrlHttp
, baseUrlWs
299 if (this.isOwned()) {
300 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
301 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
303 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
304 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
307 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
308 const announce
= baseUrlWs
+ '/tracker/socket'
309 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
315 infoHash: this.infoHash
,
319 return magnetUtil
.encode(magnetHash
)
322 function getVideoFilename () {
323 if (this.isOwned()) return this.id
+ this.extname
325 return this.remoteId
+ this.extname
328 function getThumbnailName () {
329 // We always have a copy of the thumbnail
330 return this.id
+ '.jpg'
333 function getPreviewName () {
334 const extension
= '.jpg'
336 if (this.isOwned()) return this.id
+ extension
338 return this.remoteId
+ extension
341 function getTorrentName () {
342 const extension
= '.torrent'
344 if (this.isOwned()) return this.id
+ extension
346 return this.remoteId
+ extension
349 function isOwned () {
350 return this.remoteId
=== null
353 function toFormatedJSON () {
356 if (this.Author
.Pod
) {
357 podHost
= this.Author
.Pod
.host
359 // It means it's our video
360 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
366 description: this.description
,
368 isLocal: this.isOwned(),
369 magnetUri: this.generateMagnetUri(),
370 author: this.Author
.name
,
371 duration: this.duration
,
374 dislikes: this.dislikes
,
375 tags: map(this.Tags
, 'name'),
376 thumbnailPath: pathUtils
.join(constants
.STATIC_PATHS
.THUMBNAILS
, this.getThumbnailName()),
377 createdAt: this.createdAt
,
378 updatedAt: this.updatedAt
384 function toAddRemoteJSON (callback
) {
387 // Get thumbnail data to send to the other pod
388 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, this.getThumbnailName())
389 fs
.readFile(thumbnailPath
, function (err
, thumbnailData
) {
391 logger
.error('Cannot read the thumbnail of the video')
395 const remoteVideo
= {
397 description: self
.description
,
398 infoHash: self
.infoHash
,
400 author: self
.Author
.name
,
401 duration: self
.duration
,
402 thumbnailData: thumbnailData
.toString('binary'),
403 tags: map(self
.Tags
, 'name'),
404 createdAt: self
.createdAt
,
405 updatedAt: self
.updatedAt
,
406 extname: self
.extname
,
409 dislikes: self
.dislikes
412 return callback(null, remoteVideo
)
416 function toUpdateRemoteJSON (callback
) {
419 description: this.description
,
420 infoHash: this.infoHash
,
422 author: this.Author
.name
,
423 duration: this.duration
,
424 tags: map(this.Tags
, 'name'),
425 createdAt: this.createdAt
,
426 updatedAt: this.updatedAt
,
427 extname: this.extname
,
430 dislikes: this.dislikes
436 // ------------------------------ STATICS ------------------------------
438 function generateThumbnailFromData (video
, thumbnailData
, callback
) {
439 // Creating the thumbnail for a remote video
441 const thumbnailName
= video
.getThumbnailName()
442 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, thumbnailName
)
443 fs
.writeFile(thumbnailPath
, Buffer
.from(thumbnailData
, 'binary'), function (err
) {
444 if (err
) return callback(err
)
446 return callback(null, thumbnailName
)
450 function getDurationFromFile (videoPath
, callback
) {
451 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
452 if (err
) return callback(err
)
454 return callback(null, Math
.floor(metadata
.format
.duration
))
458 function list (callback
) {
459 return this.findAll().asCallback(callback
)
462 function listForApi (start
, count
, sort
, callback
) {
466 distinct: true, // For the count, a video can have many tags
467 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ],
470 model: this.sequelize
.models
.Author
,
471 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
474 this.sequelize
.models
.Tag
478 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
479 if (err
) return callback(err
)
481 return callback(null, result
.rows
, result
.count
)
485 function loadByHostAndRemoteId (fromHost
, remoteId
, callback
) {
492 model: this.sequelize
.models
.Author
,
495 model: this.sequelize
.models
.Pod
,
506 return this.findOne(query
).asCallback(callback
)
509 function listOwnedAndPopulateAuthorAndTags (callback
) {
510 // If remoteId is null this is *our* video
515 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
518 return this.findAll(query
).asCallback(callback
)
521 function listOwnedByAuthor (author
, callback
) {
528 model: this.sequelize
.models
.Author
,
536 return this.findAll(query
).asCallback(callback
)
539 function load (id
, callback
) {
540 return this.findById(id
).asCallback(callback
)
543 function loadAndPopulateAuthor (id
, callback
) {
545 include: [ this.sequelize
.models
.Author
]
548 return this.findById(id
, options
).asCallback(callback
)
551 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
555 model: this.sequelize
.models
.Author
,
556 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
558 this.sequelize
.models
.Tag
562 return this.findById(id
, options
).asCallback(callback
)
565 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
567 model: this.sequelize
.models
.Pod
,
571 const authorInclude
= {
572 model: this.sequelize
.models
.Author
,
579 model: this.sequelize
.models
.Tag
586 distinct: true, // For the count, a video can have many tags
587 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ]
590 // Make an exact search with the magnet
591 if (field
=== 'magnetUri') {
592 const infoHash
= magnetUtil
.decode(value
).infoHash
593 query
.where
.infoHash
= infoHash
594 } else if (field
=== 'tags') {
595 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
598 $in: this.sequelize
.literal(
599 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
603 } else if (field
=== 'host') {
604 // FIXME: Include our pod? (not stored in the database)
607 $like: '%' + value
+ '%'
610 podInclude
.required
= true
611 } else if (field
=== 'author') {
612 authorInclude
.where
= {
614 $like: '%' + value
+ '%'
618 // authorInclude.or = true
620 query
.where
[field
] = {
621 $like: '%' + value
+ '%'
626 authorInclude
, tagInclude
629 if (tagInclude
.where
) {
630 // query.include.push([ this.sequelize.models.Tag ])
633 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
634 if (err
) return callback(err
)
636 return callback(null, result
.rows
, result
.count
)
640 // ---------------------------------------------------------------------------
642 function removeThumbnail (video
, callback
) {
643 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName())
644 fs
.unlink(thumbnailPath
, callback
)
647 function removeFile (video
, callback
) {
648 const filePath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
649 fs
.unlink(filePath
, callback
)
652 function removeTorrent (video
, callback
) {
653 const torrenPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
, video
.getTorrentName())
654 fs
.unlink(torrenPath
, callback
)
657 function removePreview (video
, callback
) {
658 // Same name than video thumnail
659 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
662 function createPreview (video
, videoPath
, callback
) {
663 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
666 function createThumbnail (video
, videoPath
, callback
) {
667 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
670 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
684 .on('error', callback
)
685 .on('end', function () {
686 callback(null, imageName
)