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
,
97 fields: [ 'authorId' ]
100 fields: [ 'remoteId' ]
106 fields: [ 'createdAt' ]
109 fields: [ 'duration' ]
112 fields: [ 'infoHash' ]
121 generateThumbnailFromData
,
125 listOwnedAndPopulateAuthorAndTags
,
128 loadByHostAndRemoteId
,
129 loadAndPopulateAuthor
,
130 loadAndPopulateAuthorAndPodAndTags
,
131 searchAndPopulateAuthorAndPodAndTags
155 function beforeValidate (video
, options
, next
) {
156 // Put a fake infoHash if it does not exists yet
157 if (video
.isOwned() && !video
.infoHash
) {
159 video
.infoHash
= '0123456789abcdef0123456789abcdef01234567'
165 function beforeCreate (video
, options
, next
) {
168 if (video
.isOwned()) {
169 const videoPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
172 function createVideoTorrent (callback
) {
175 [ constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
+ '/tracker/socket' ]
178 constants
.CONFIG
.WEBSERVER
.URL
+ constants
.STATIC_PATHS
.WEBSEED
+ video
.getVideoFilename()
182 createTorrent(videoPath
, options
, function (err
, torrent
) {
183 if (err
) return callback(err
)
185 const filePath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
, video
.getTorrentName())
186 fs
.writeFile(filePath
, torrent
, function (err
) {
187 if (err
) return callback(err
)
189 const parsedTorrent
= parseTorrent(torrent
)
190 video
.set('infoHash', parsedTorrent
.infoHash
)
191 video
.validate().asCallback(callback
)
196 function createVideoThumbnail (callback
) {
197 createThumbnail(video
, videoPath
, callback
)
200 function createVIdeoPreview (callback
) {
201 createPreview(video
, videoPath
, callback
)
205 return parallel(tasks
, next
)
211 function afterDestroy (video
, options
, next
) {
215 function (callback
) {
216 removeThumbnail(video
, callback
)
220 if (video
.isOwned()) {
222 function removeVideoFile (callback
) {
223 removeFile(video
, callback
)
226 function removeVideoTorrent (callback
) {
227 removeTorrent(video
, callback
)
230 function removeVideoPreview (callback
) {
231 removePreview(video
, callback
)
234 function removeVideoToFriends (callback
) {
239 friends
.removeVideoToFriends(params
)
246 parallel(tasks
, next
)
249 // ------------------------------ METHODS ------------------------------
251 function associate (models
) {
252 this.belongsTo(models
.Author
, {
260 this.belongsToMany(models
.Tag
, {
261 foreignKey: 'videoId',
262 through: models
.VideoTag
,
266 this.hasMany(models
.VideoAbuse
, {
275 function generateMagnetUri () {
276 let baseUrlHttp
, baseUrlWs
278 if (this.isOwned()) {
279 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
280 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
282 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
283 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
286 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
287 const announce
= baseUrlWs
+ '/tracker/socket'
288 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
294 infoHash: this.infoHash
,
298 return magnetUtil
.encode(magnetHash
)
301 function getVideoFilename () {
302 if (this.isOwned()) return this.id
+ this.extname
304 return this.remoteId
+ this.extname
307 function getThumbnailName () {
308 // We always have a copy of the thumbnail
309 return this.id
+ '.jpg'
312 function getPreviewName () {
313 const extension
= '.jpg'
315 if (this.isOwned()) return this.id
+ extension
317 return this.remoteId
+ extension
320 function getTorrentName () {
321 const extension
= '.torrent'
323 if (this.isOwned()) return this.id
+ extension
325 return this.remoteId
+ extension
328 function isOwned () {
329 return this.remoteId
=== null
332 function toFormatedJSON () {
335 if (this.Author
.Pod
) {
336 podHost
= this.Author
.Pod
.host
338 // It means it's our video
339 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
345 description: this.description
,
347 isLocal: this.isOwned(),
348 magnetUri: this.generateMagnetUri(),
349 author: this.Author
.name
,
350 duration: this.duration
,
352 tags: map(this.Tags
, 'name'),
353 thumbnailPath: pathUtils
.join(constants
.STATIC_PATHS
.THUMBNAILS
, this.getThumbnailName()),
354 createdAt: this.createdAt
,
355 updatedAt: this.updatedAt
361 function toAddRemoteJSON (callback
) {
364 // Get thumbnail data to send to the other pod
365 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, this.getThumbnailName())
366 fs
.readFile(thumbnailPath
, function (err
, thumbnailData
) {
368 logger
.error('Cannot read the thumbnail of the video')
372 const remoteVideo
= {
374 description: self
.description
,
375 infoHash: self
.infoHash
,
377 author: self
.Author
.name
,
378 duration: self
.duration
,
379 thumbnailData: thumbnailData
.toString('binary'),
380 tags: map(self
.Tags
, 'name'),
381 createdAt: self
.createdAt
,
382 updatedAt: self
.updatedAt
,
383 extname: self
.extname
,
387 return callback(null, remoteVideo
)
391 function toUpdateRemoteJSON (callback
) {
394 description: this.description
,
395 infoHash: this.infoHash
,
397 author: this.Author
.name
,
398 duration: this.duration
,
399 tags: map(this.Tags
, 'name'),
400 createdAt: this.createdAt
,
401 updatedAt: this.updatedAt
,
402 extname: this.extname
,
409 // ------------------------------ STATICS ------------------------------
411 function generateThumbnailFromData (video
, thumbnailData
, callback
) {
412 // Creating the thumbnail for a remote video
414 const thumbnailName
= video
.getThumbnailName()
415 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, thumbnailName
)
416 fs
.writeFile(thumbnailPath
, Buffer
.from(thumbnailData
, 'binary'), function (err
) {
417 if (err
) return callback(err
)
419 return callback(null, thumbnailName
)
423 function getDurationFromFile (videoPath
, callback
) {
424 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
425 if (err
) return callback(err
)
427 return callback(null, Math
.floor(metadata
.format
.duration
))
431 function list (callback
) {
432 return this.findAll().asCallback(callback
)
435 function listForApi (start
, count
, sort
, callback
) {
439 distinct: true, // For the count, a video can have many tags
440 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ],
443 model: this.sequelize
.models
.Author
,
444 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
447 this.sequelize
.models
.Tag
451 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
452 if (err
) return callback(err
)
454 return callback(null, result
.rows
, result
.count
)
458 function loadByHostAndRemoteId (fromHost
, remoteId
, callback
) {
465 model: this.sequelize
.models
.Author
,
468 model: this.sequelize
.models
.Pod
,
479 return this.findOne(query
).asCallback(callback
)
482 function listOwnedAndPopulateAuthorAndTags (callback
) {
483 // If remoteId is null this is *our* video
488 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
491 return this.findAll(query
).asCallback(callback
)
494 function listOwnedByAuthor (author
, callback
) {
501 model: this.sequelize
.models
.Author
,
509 return this.findAll(query
).asCallback(callback
)
512 function load (id
, callback
) {
513 return this.findById(id
).asCallback(callback
)
516 function loadAndPopulateAuthor (id
, callback
) {
518 include: [ this.sequelize
.models
.Author
]
521 return this.findById(id
, options
).asCallback(callback
)
524 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
528 model: this.sequelize
.models
.Author
,
529 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
531 this.sequelize
.models
.Tag
535 return this.findById(id
, options
).asCallback(callback
)
538 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
540 model: this.sequelize
.models
.Pod
,
544 const authorInclude
= {
545 model: this.sequelize
.models
.Author
,
552 model: this.sequelize
.models
.Tag
559 distinct: true, // For the count, a video can have many tags
560 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ]
563 // Make an exact search with the magnet
564 if (field
=== 'magnetUri') {
565 const infoHash
= magnetUtil
.decode(value
).infoHash
566 query
.where
.infoHash
= infoHash
567 } else if (field
=== 'tags') {
568 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
571 $in: this.sequelize
.literal(
572 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
576 } else if (field
=== 'host') {
577 // FIXME: Include our pod? (not stored in the database)
580 $like: '%' + value
+ '%'
583 podInclude
.required
= true
584 } else if (field
=== 'author') {
585 authorInclude
.where
= {
587 $like: '%' + value
+ '%'
591 // authorInclude.or = true
593 query
.where
[field
] = {
594 $like: '%' + value
+ '%'
599 authorInclude
, tagInclude
602 if (tagInclude
.where
) {
603 // query.include.push([ this.sequelize.models.Tag ])
606 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
607 if (err
) return callback(err
)
609 return callback(null, result
.rows
, result
.count
)
613 // ---------------------------------------------------------------------------
615 function removeThumbnail (video
, callback
) {
616 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName())
617 fs
.unlink(thumbnailPath
, callback
)
620 function removeFile (video
, callback
) {
621 const filePath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
622 fs
.unlink(filePath
, callback
)
625 function removeTorrent (video
, callback
) {
626 const torrenPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
, video
.getTorrentName())
627 fs
.unlink(torrenPath
, callback
)
630 function removePreview (video
, callback
) {
631 // Same name than video thumnail
632 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
635 function createPreview (video
, videoPath
, callback
) {
636 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
639 function createThumbnail (video
, videoPath
, callback
) {
640 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
643 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
657 .on('error', callback
)
658 .on('end', function () {
659 callback(null, imageName
)