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 // Put a fake infoHash if it does not exists yet
145 if (video
.isOwned() && !video
.infoHash
) {
147 video
.infoHash
= '0123456789abcdef0123456789abcdef01234567'
153 function beforeCreate (video
, options
, next
) {
156 if (video
.isOwned()) {
157 const videoPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
160 // TODO: refractoring
161 function (callback
) {
164 [ constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
+ '/tracker/socket' ]
167 constants
.CONFIG
.WEBSERVER
.URL
+ constants
.STATIC_PATHS
.WEBSEED
+ video
.getVideoFilename()
171 createTorrent(videoPath
, options
, function (err
, torrent
) {
172 if (err
) return callback(err
)
174 fs
.writeFile(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), torrent
, function (err
) {
175 if (err
) return callback(err
)
177 const parsedTorrent
= parseTorrent(torrent
)
178 video
.set('infoHash', parsedTorrent
.infoHash
)
179 video
.validate().asCallback(callback
)
183 function (callback
) {
184 createThumbnail(video
, videoPath
, callback
)
186 function (callback
) {
187 createPreview(video
, videoPath
, callback
)
191 return parallel(tasks
, next
)
197 function afterDestroy (video
, options
, next
) {
201 function (callback
) {
202 removeThumbnail(video
, callback
)
206 if (video
.isOwned()) {
208 function (callback
) {
209 removeFile(video
, callback
)
212 function (callback
) {
213 removeTorrent(video
, callback
)
216 function (callback
) {
217 removePreview(video
, callback
)
220 function (callback
) {
225 friends
.removeVideoToFriends(params
)
232 parallel(tasks
, next
)
235 // ------------------------------ METHODS ------------------------------
237 function associate (models
) {
238 this.belongsTo(models
.Author
, {
246 this.belongsToMany(models
.Tag
, {
247 foreignKey: 'videoId',
248 through: models
.VideoTag
,
252 this.hasMany(models
.VideoAbuse
, {
261 function generateMagnetUri () {
262 let baseUrlHttp
, baseUrlWs
264 if (this.isOwned()) {
265 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
266 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
268 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
269 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
272 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
273 const announce
= baseUrlWs
+ '/tracker/socket'
274 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
280 infoHash: this.infoHash
,
284 return magnetUtil
.encode(magnetHash
)
287 function getVideoFilename () {
288 if (this.isOwned()) return this.id
+ this.extname
290 return this.remoteId
+ this.extname
293 function getThumbnailName () {
294 // We always have a copy of the thumbnail
295 return this.id
+ '.jpg'
298 function getPreviewName () {
299 const extension
= '.jpg'
301 if (this.isOwned()) return this.id
+ extension
303 return this.remoteId
+ extension
306 function getTorrentName () {
307 const extension
= '.torrent'
309 if (this.isOwned()) return this.id
+ extension
311 return this.remoteId
+ extension
314 function isOwned () {
315 return this.remoteId
=== null
318 function toFormatedJSON () {
321 if (this.Author
.Pod
) {
322 podHost
= this.Author
.Pod
.host
324 // It means it's our video
325 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
331 description: this.description
,
333 isLocal: this.isOwned(),
334 magnetUri: this.generateMagnetUri(),
335 author: this.Author
.name
,
336 duration: this.duration
,
337 tags: map(this.Tags
, 'name'),
338 thumbnailPath: pathUtils
.join(constants
.STATIC_PATHS
.THUMBNAILS
, this.getThumbnailName()),
339 createdAt: this.createdAt
,
340 updatedAt: this.updatedAt
346 function toAddRemoteJSON (callback
) {
349 // Get thumbnail data to send to the other pod
350 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, this.getThumbnailName())
351 fs
.readFile(thumbnailPath
, function (err
, thumbnailData
) {
353 logger
.error('Cannot read the thumbnail of the video')
357 const remoteVideo
= {
359 description: self
.description
,
360 infoHash: self
.infoHash
,
362 author: self
.Author
.name
,
363 duration: self
.duration
,
364 thumbnailData: thumbnailData
.toString('binary'),
365 tags: map(self
.Tags
, 'name'),
366 createdAt: self
.createdAt
,
367 updatedAt: self
.updatedAt
,
368 extname: self
.extname
371 return callback(null, remoteVideo
)
375 function toUpdateRemoteJSON (callback
) {
378 description: this.description
,
379 infoHash: this.infoHash
,
381 author: this.Author
.name
,
382 duration: this.duration
,
383 tags: map(this.Tags
, 'name'),
384 createdAt: this.createdAt
,
385 updatedAt: this.updatedAt
,
386 extname: this.extname
392 // ------------------------------ STATICS ------------------------------
394 function generateThumbnailFromData (video
, thumbnailData
, callback
) {
395 // Creating the thumbnail for a remote video
397 const thumbnailName
= video
.getThumbnailName()
398 const thumbnailPath
= constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ thumbnailName
399 fs
.writeFile(thumbnailPath
, Buffer
.from(thumbnailData
, 'binary'), function (err
) {
400 if (err
) return callback(err
)
402 return callback(null, thumbnailName
)
406 function getDurationFromFile (videoPath
, callback
) {
407 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
408 if (err
) return callback(err
)
410 return callback(null, Math
.floor(metadata
.format
.duration
))
414 function list (callback
) {
415 return this.find().asCallback()
418 function listForApi (start
, count
, sort
, callback
) {
422 distinct: true, // For the count, a video can have many tags
423 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ],
426 model: this.sequelize
.models
.Author
,
427 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
430 this.sequelize
.models
.Tag
434 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
435 if (err
) return callback(err
)
437 return callback(null, result
.rows
, result
.count
)
441 function loadByHostAndRemoteId (fromHost
, remoteId
, callback
) {
448 model: this.sequelize
.models
.Author
,
451 model: this.sequelize
.models
.Pod
,
462 return this.findOne(query
).asCallback(callback
)
465 function listOwnedAndPopulateAuthorAndTags (callback
) {
466 // If remoteId is null this is *our* video
471 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
474 return this.findAll(query
).asCallback(callback
)
477 function listOwnedByAuthor (author
, callback
) {
484 model: this.sequelize
.models
.Author
,
492 return this.findAll(query
).asCallback(callback
)
495 function load (id
, callback
) {
496 return this.findById(id
).asCallback(callback
)
499 function loadAndPopulateAuthor (id
, callback
) {
501 include: [ this.sequelize
.models
.Author
]
504 return this.findById(id
, options
).asCallback(callback
)
507 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
511 model: this.sequelize
.models
.Author
,
512 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
514 this.sequelize
.models
.Tag
518 return this.findById(id
, options
).asCallback(callback
)
521 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
523 model: this.sequelize
.models
.Pod
,
527 const authorInclude
= {
528 model: this.sequelize
.models
.Author
,
535 model: this.sequelize
.models
.Tag
542 distinct: true, // For the count, a video can have many tags
543 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ]
546 // Make an exact search with the magnet
547 if (field
=== 'magnetUri') {
548 const infoHash
= magnetUtil
.decode(value
).infoHash
549 query
.where
.infoHash
= infoHash
550 } else if (field
=== 'tags') {
551 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
554 $in: this.sequelize
.literal(
555 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
559 } else if (field
=== 'host') {
560 // FIXME: Include our pod? (not stored in the database)
563 $like: '%' + value
+ '%'
566 podInclude
.required
= true
567 } else if (field
=== 'author') {
568 authorInclude
.where
= {
570 $like: '%' + value
+ '%'
574 // authorInclude.or = true
576 query
.where
[field
] = {
577 $like: '%' + value
+ '%'
582 authorInclude
, tagInclude
585 if (tagInclude
.where
) {
586 // query.include.push([ this.sequelize.models.Tag ])
589 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
590 if (err
) return callback(err
)
592 return callback(null, result
.rows
, result
.count
)
596 // ---------------------------------------------------------------------------
598 function removeThumbnail (video
, callback
) {
599 fs
.unlink(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ video
.getThumbnailName(), callback
)
602 function removeFile (video
, callback
) {
603 fs
.unlink(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
+ video
.getVideoFilename(), callback
)
606 function removeTorrent (video
, callback
) {
607 fs
.unlink(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), callback
)
610 function removePreview (video
, callback
) {
611 // Same name than video thumnail
612 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
615 function createPreview (video
, videoPath
, callback
) {
616 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
619 function createThumbnail (video
, videoPath
, callback
) {
620 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
623 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
637 .on('error', callback
)
638 .on('end', function () {
639 callback(null, imageName
)