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
) {
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
,
253 function generateMagnetUri () {
254 let baseUrlHttp
, baseUrlWs
256 if (this.isOwned()) {
257 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
258 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
260 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
261 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
264 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
265 const announce
= baseUrlWs
+ '/tracker/socket'
266 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
272 infoHash: this.infoHash
,
276 return magnetUtil
.encode(magnetHash
)
279 function getVideoFilename () {
280 if (this.isOwned()) return this.id
+ this.extname
282 return this.remoteId
+ this.extname
285 function getThumbnailName () {
286 // We always have a copy of the thumbnail
287 return this.id
+ '.jpg'
290 function getPreviewName () {
291 const extension
= '.jpg'
293 if (this.isOwned()) return this.id
+ extension
295 return this.remoteId
+ extension
298 function getTorrentName () {
299 const extension
= '.torrent'
301 if (this.isOwned()) return this.id
+ extension
303 return this.remoteId
+ extension
306 function isOwned () {
307 return this.remoteId
=== null
310 function toFormatedJSON () {
313 if (this.Author
.Pod
) {
314 podHost
= this.Author
.Pod
.host
316 // It means it's our video
317 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
323 description: this.description
,
325 isLocal: this.isOwned(),
326 magnetUri: this.generateMagnetUri(),
327 author: this.Author
.name
,
328 duration: this.duration
,
329 tags: map(this.Tags
, 'name'),
330 thumbnailPath: constants
.STATIC_PATHS
.THUMBNAILS
+ '/' + this.getThumbnailName(),
331 createdAt: this.createdAt
,
332 updatedAt: this.updatedAt
338 function toAddRemoteJSON (callback
) {
341 // Get thumbnail data to send to the other pod
342 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, this.getThumbnailName())
343 fs
.readFile(thumbnailPath
, function (err
, thumbnailData
) {
345 logger
.error('Cannot read the thumbnail of the video')
349 const remoteVideo
= {
351 description: self
.description
,
352 infoHash: self
.infoHash
,
354 author: self
.Author
.name
,
355 duration: self
.duration
,
356 thumbnailData: thumbnailData
.toString('binary'),
357 tags: map(self
.Tags
, 'name'),
358 createdAt: self
.createdAt
,
359 updatedAt: self
.updatedAt
,
360 extname: self
.extname
363 return callback(null, remoteVideo
)
367 function toUpdateRemoteJSON (callback
) {
370 description: this.description
,
371 infoHash: this.infoHash
,
373 author: this.Author
.name
,
374 duration: this.duration
,
375 tags: map(this.Tags
, 'name'),
376 createdAt: this.createdAt
,
377 updatedAt: this.updatedAt
,
378 extname: this.extname
384 // ------------------------------ STATICS ------------------------------
386 function generateThumbnailFromData (video
, thumbnailData
, callback
) {
387 // Creating the thumbnail for a remote video
389 const thumbnailName
= video
.getThumbnailName()
390 const thumbnailPath
= constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ thumbnailName
391 fs
.writeFile(thumbnailPath
, Buffer
.from(thumbnailData
, 'binary'), function (err
) {
392 if (err
) return callback(err
)
394 return callback(null, thumbnailName
)
398 function getDurationFromFile (videoPath
, callback
) {
399 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
400 if (err
) return callback(err
)
402 return callback(null, Math
.floor(metadata
.format
.duration
))
406 function list (callback
) {
407 return this.find().asCallback()
410 function listForApi (start
, count
, sort
, callback
) {
414 distinct: true, // For the count, a video can have many tags
415 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ],
418 model: this.sequelize
.models
.Author
,
419 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
422 this.sequelize
.models
.Tag
426 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
427 if (err
) return callback(err
)
429 return callback(null, result
.rows
, result
.count
)
433 function loadByHostAndRemoteId (fromHost
, remoteId
, callback
) {
440 model: this.sequelize
.models
.Author
,
443 model: this.sequelize
.models
.Pod
,
454 return this.findOne(query
).asCallback(callback
)
457 function listOwnedAndPopulateAuthorAndTags (callback
) {
458 // If remoteId is null this is *our* video
463 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
466 return this.findAll(query
).asCallback(callback
)
469 function listOwnedByAuthor (author
, callback
) {
476 model: this.sequelize
.models
.Author
,
484 return this.findAll(query
).asCallback(callback
)
487 function load (id
, callback
) {
488 return this.findById(id
).asCallback(callback
)
491 function loadAndPopulateAuthor (id
, callback
) {
493 include: [ this.sequelize
.models
.Author
]
496 return this.findById(id
, options
).asCallback(callback
)
499 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
503 model: this.sequelize
.models
.Author
,
504 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
506 this.sequelize
.models
.Tag
510 return this.findById(id
, options
).asCallback(callback
)
513 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
515 model: this.sequelize
.models
.Pod
,
519 const authorInclude
= {
520 model: this.sequelize
.models
.Author
,
527 model: this.sequelize
.models
.Tag
534 distinct: true, // For the count, a video can have many tags
535 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ]
538 // Make an exact search with the magnet
539 if (field
=== 'magnetUri') {
540 const infoHash
= magnetUtil
.decode(value
).infoHash
541 query
.where
.infoHash
= infoHash
542 } else if (field
=== 'tags') {
543 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
546 $in: this.sequelize
.literal(
547 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
551 } else if (field
=== 'host') {
552 // FIXME: Include our pod? (not stored in the database)
555 $like: '%' + value
+ '%'
558 podInclude
.required
= true
559 } else if (field
=== 'author') {
560 authorInclude
.where
= {
562 $like: '%' + value
+ '%'
566 // authorInclude.or = true
568 query
.where
[field
] = {
569 $like: '%' + value
+ '%'
574 authorInclude
, tagInclude
577 if (tagInclude
.where
) {
578 // query.include.push([ this.sequelize.models.Tag ])
581 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
582 if (err
) return callback(err
)
584 return callback(null, result
.rows
, result
.count
)
588 // ---------------------------------------------------------------------------
590 function removeThumbnail (video
, callback
) {
591 fs
.unlink(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ video
.getThumbnailName(), callback
)
594 function removeFile (video
, callback
) {
595 fs
.unlink(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
+ video
.getVideoFilename(), callback
)
598 function removeTorrent (video
, callback
) {
599 fs
.unlink(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), callback
)
602 function removePreview (video
, callback
) {
603 // Same name than video thumnail
604 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
607 function createPreview (video
, videoPath
, callback
) {
608 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
611 function createThumbnail (video
, videoPath
, callback
) {
612 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
615 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
629 .on('error', callback
)
630 .on('end', function () {
631 callback(null, imageName
)