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.')
88 fields: [ 'authorId' ]
91 fields: [ 'remoteId' ]
97 fields: [ 'createdAt' ]
100 fields: [ 'duration' ]
103 fields: [ 'infoHash' ]
109 generateThumbnailFromData
,
113 listOwnedAndPopulateAuthorAndTags
,
116 loadByHostAndRemoteId
,
117 loadAndPopulateAuthor
,
118 loadAndPopulateAuthorAndPodAndTags
,
119 searchAndPopulateAuthorAndPodAndTags
143 function beforeValidate (video
, options
, next
) {
144 if (video
.isOwned()) {
146 video
.infoHash
= '0123456789abcdef0123456789abcdef01234567'
152 function beforeCreate (video
, options
, next
) {
155 if (video
.isOwned()) {
156 const videoPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
159 // TODO: refractoring
160 function (callback
) {
163 [ constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
+ '/tracker/socket' ]
166 constants
.CONFIG
.WEBSERVER
.URL
+ constants
.STATIC_PATHS
.WEBSEED
+ video
.getVideoFilename()
170 createTorrent(videoPath
, options
, function (err
, torrent
) {
171 if (err
) return callback(err
)
173 fs
.writeFile(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), torrent
, function (err
) {
174 if (err
) return callback(err
)
176 const parsedTorrent
= parseTorrent(torrent
)
177 video
.set('infoHash', parsedTorrent
.infoHash
)
178 video
.validate().asCallback(callback
)
182 function (callback
) {
183 createThumbnail(video
, videoPath
, callback
)
185 function (callback
) {
186 createPreview(video
, videoPath
, callback
)
190 return parallel(tasks
, next
)
196 function afterDestroy (video
, options
, next
) {
200 function (callback
) {
201 removeThumbnail(video
, callback
)
205 if (video
.isOwned()) {
207 function (callback
) {
208 removeFile(video
, callback
)
211 function (callback
) {
212 removeTorrent(video
, callback
)
215 function (callback
) {
216 removePreview(video
, callback
)
219 function (callback
) {
224 friends
.removeVideoToFriends(params
)
231 parallel(tasks
, next
)
234 // ------------------------------ METHODS ------------------------------
236 function associate (models
) {
237 this.belongsTo(models
.Author
, {
245 this.belongsToMany(models
.Tag
, {
246 foreignKey: 'videoId',
247 through: models
.VideoTag
,
251 this.hasMany(models
.VideoAbuse
, {
260 function generateMagnetUri () {
261 let baseUrlHttp
, baseUrlWs
263 if (this.isOwned()) {
264 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
265 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
267 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
268 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
271 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
272 const announce
= baseUrlWs
+ '/tracker/socket'
273 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
279 infoHash: this.infoHash
,
283 return magnetUtil
.encode(magnetHash
)
286 function getVideoFilename () {
287 if (this.isOwned()) return this.id
+ this.extname
289 return this.remoteId
+ this.extname
292 function getThumbnailName () {
293 // We always have a copy of the thumbnail
294 return this.id
+ '.jpg'
297 function getPreviewName () {
298 const extension
= '.jpg'
300 if (this.isOwned()) return this.id
+ extension
302 return this.remoteId
+ extension
305 function getTorrentName () {
306 const extension
= '.torrent'
308 if (this.isOwned()) return this.id
+ extension
310 return this.remoteId
+ extension
313 function isOwned () {
314 return this.remoteId
=== null
317 function toFormatedJSON () {
320 if (this.Author
.Pod
) {
321 podHost
= this.Author
.Pod
.host
323 // It means it's our video
324 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
330 description: this.description
,
332 isLocal: this.isOwned(),
333 magnetUri: this.generateMagnetUri(),
334 author: this.Author
.name
,
335 duration: this.duration
,
336 tags: map(this.Tags
, 'name'),
337 thumbnailPath: constants
.STATIC_PATHS
.THUMBNAILS
+ '/' + this.getThumbnailName(),
338 createdAt: this.createdAt
,
339 updatedAt: this.updatedAt
345 function toAddRemoteJSON (callback
) {
348 // Get thumbnail data to send to the other pod
349 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, this.getThumbnailName())
350 fs
.readFile(thumbnailPath
, function (err
, thumbnailData
) {
352 logger
.error('Cannot read the thumbnail of the video')
356 const remoteVideo
= {
358 description: self
.description
,
359 infoHash: self
.infoHash
,
361 author: self
.Author
.name
,
362 duration: self
.duration
,
363 thumbnailData: thumbnailData
.toString('binary'),
364 tags: map(self
.Tags
, 'name'),
365 createdAt: self
.createdAt
,
366 updatedAt: self
.updatedAt
,
367 extname: self
.extname
370 return callback(null, remoteVideo
)
374 function toUpdateRemoteJSON (callback
) {
377 description: this.description
,
378 infoHash: this.infoHash
,
380 author: this.Author
.name
,
381 duration: this.duration
,
382 tags: map(this.Tags
, 'name'),
383 createdAt: this.createdAt
,
384 updatedAt: this.updatedAt
,
385 extname: this.extname
391 // ------------------------------ STATICS ------------------------------
393 function generateThumbnailFromData (video
, thumbnailData
, callback
) {
394 // Creating the thumbnail for a remote video
396 const thumbnailName
= video
.getThumbnailName()
397 const thumbnailPath
= constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ thumbnailName
398 fs
.writeFile(thumbnailPath
, Buffer
.from(thumbnailData
, 'binary'), function (err
) {
399 if (err
) return callback(err
)
401 return callback(null, thumbnailName
)
405 function getDurationFromFile (videoPath
, callback
) {
406 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
407 if (err
) return callback(err
)
409 return callback(null, Math
.floor(metadata
.format
.duration
))
413 function list (callback
) {
414 return this.find().asCallback()
417 function listForApi (start
, count
, sort
, callback
) {
421 distinct: true, // For the count, a video can have many tags
422 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ],
425 model: this.sequelize
.models
.Author
,
426 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
429 this.sequelize
.models
.Tag
433 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
434 if (err
) return callback(err
)
436 return callback(null, result
.rows
, result
.count
)
440 function loadByHostAndRemoteId (fromHost
, remoteId
, callback
) {
447 model: this.sequelize
.models
.Author
,
450 model: this.sequelize
.models
.Pod
,
461 return this.findOne(query
).asCallback(callback
)
464 function listOwnedAndPopulateAuthorAndTags (callback
) {
465 // If remoteId is null this is *our* video
470 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
473 return this.findAll(query
).asCallback(callback
)
476 function listOwnedByAuthor (author
, callback
) {
483 model: this.sequelize
.models
.Author
,
491 return this.findAll(query
).asCallback(callback
)
494 function load (id
, callback
) {
495 return this.findById(id
).asCallback(callback
)
498 function loadAndPopulateAuthor (id
, callback
) {
500 include: [ this.sequelize
.models
.Author
]
503 return this.findById(id
, options
).asCallback(callback
)
506 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
510 model: this.sequelize
.models
.Author
,
511 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
513 this.sequelize
.models
.Tag
517 return this.findById(id
, options
).asCallback(callback
)
520 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
522 model: this.sequelize
.models
.Pod
,
526 const authorInclude
= {
527 model: this.sequelize
.models
.Author
,
534 model: this.sequelize
.models
.Tag
541 distinct: true, // For the count, a video can have many tags
542 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ]
545 // Make an exact search with the magnet
546 if (field
=== 'magnetUri') {
547 const infoHash
= magnetUtil
.decode(value
).infoHash
548 query
.where
.infoHash
= infoHash
549 } else if (field
=== 'tags') {
550 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
553 $in: this.sequelize
.literal(
554 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
558 } else if (field
=== 'host') {
559 // FIXME: Include our pod? (not stored in the database)
562 $like: '%' + value
+ '%'
565 podInclude
.required
= true
566 } else if (field
=== 'author') {
567 authorInclude
.where
= {
569 $like: '%' + value
+ '%'
573 // authorInclude.or = true
575 query
.where
[field
] = {
576 $like: '%' + value
+ '%'
581 authorInclude
, tagInclude
584 if (tagInclude
.where
) {
585 // query.include.push([ this.sequelize.models.Tag ])
588 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
589 if (err
) return callback(err
)
591 return callback(null, result
.rows
, result
.count
)
595 // ---------------------------------------------------------------------------
597 function removeThumbnail (video
, callback
) {
598 fs
.unlink(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ video
.getThumbnailName(), callback
)
601 function removeFile (video
, callback
) {
602 fs
.unlink(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
+ video
.getVideoFilename(), callback
)
605 function removeTorrent (video
, callback
) {
606 fs
.unlink(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), callback
)
609 function removePreview (video
, callback
) {
610 // Same name than video thumnail
611 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
614 function createPreview (video
, videoPath
, callback
) {
615 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
618 function createThumbnail (video
, videoPath
, callback
) {
619 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
622 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
636 .on('error', callback
)
637 .on('end', function () {
638 callback(null, imageName
)