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 // TODO: add indexes on searchable columns
24 const Video
= sequelize
.define('Video',
28 defaultValue: DataTypes
.UUIDV4
,
35 type: DataTypes
.STRING
,
38 nameValid: function (value
) {
39 const res
= customVideosValidators
.isVideoNameValid(value
)
40 if (res
=== false) throw new Error('Video name is not valid.')
45 type: DataTypes
.ENUM(values(constants
.CONSTRAINTS_FIELDS
.VIDEOS
.EXTNAME
)),
56 type: DataTypes
.STRING
,
59 descriptionValid: function (value
) {
60 const res
= customVideosValidators
.isVideoDescriptionValid(value
)
61 if (res
=== false) throw new Error('Video description is not valid.')
66 type: DataTypes
.STRING
,
69 infoHashValid: function (value
) {
70 const res
= customVideosValidators
.isVideoInfoHashValid(value
)
71 if (res
=== false) throw new Error('Video info hash is not valid.')
76 type: DataTypes
.INTEGER
,
79 durationValid: function (value
) {
80 const res
= customVideosValidators
.isVideoDurationValid(value
)
81 if (res
=== false) throw new Error('Video duration is not valid.')
89 fields: [ 'authorId' ]
92 fields: [ 'remoteId' ]
98 fields: [ 'createdAt' ]
101 fields: [ 'duration' ]
104 fields: [ 'infoHash' ]
110 generateThumbnailFromData
,
114 listByHostAndRemoteId
,
115 listOwnedAndPopulateAuthorAndTags
,
118 loadAndPopulateAuthor
,
119 loadAndPopulateAuthorAndPodAndTags
,
120 searchAndPopulateAuthorAndPodAndTags
144 function beforeValidate (video
, options
, next
) {
145 if (video
.isOwned()) {
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
) {
226 friends
.removeVideoToFriends(params
)
233 parallel(tasks
, next
)
236 // ------------------------------ METHODS ------------------------------
238 function associate (models
) {
239 this.belongsTo(models
.Author
, {
247 this.belongsToMany(models
.Tag
, {
248 foreignKey: 'videoId',
249 through: models
.VideoTag
,
254 function generateMagnetUri () {
255 let baseUrlHttp
, baseUrlWs
257 if (this.isOwned()) {
258 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
259 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
261 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
262 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
265 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
266 const announce
= baseUrlWs
+ '/tracker/socket'
267 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
273 infoHash: this.infoHash
,
277 return magnetUtil
.encode(magnetHash
)
280 function getVideoFilename () {
281 if (this.isOwned()) return this.id
+ this.extname
283 return this.remoteId
+ this.extname
286 function getThumbnailName () {
287 // We always have a copy of the thumbnail
288 return this.id
+ '.jpg'
291 function getPreviewName () {
292 const extension
= '.jpg'
294 if (this.isOwned()) return this.id
+ extension
296 return this.remoteId
+ extension
299 function getTorrentName () {
300 const extension
= '.torrent'
302 if (this.isOwned()) return this.id
+ extension
304 return this.remoteId
+ extension
307 function isOwned () {
308 return this.remoteId
=== null
311 function toFormatedJSON () {
314 if (this.Author
.Pod
) {
315 podHost
= this.Author
.Pod
.host
317 // It means it's our video
318 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
324 description: this.description
,
326 isLocal: this.isOwned(),
327 magnetUri: this.generateMagnetUri(),
328 author: this.Author
.name
,
329 duration: this.duration
,
330 tags: map(this.Tags
, 'name'),
331 thumbnailPath: constants
.STATIC_PATHS
.THUMBNAILS
+ '/' + this.getThumbnailName(),
332 createdAt: this.createdAt
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 extname: self
.extname
362 return callback(null, remoteVideo
)
366 function toUpdateRemoteJSON (callback
) {
369 description: this.description
,
370 infoHash: this.infoHash
,
372 author: this.Author
.name
,
373 duration: this.duration
,
374 tags: map(this.Tags
, 'name'),
375 createdAt: this.createdAt
,
376 extname: this.extname
382 // ------------------------------ STATICS ------------------------------
384 function generateThumbnailFromData (video
, thumbnailData
, callback
) {
385 // Creating the thumbnail for a remote video
387 const thumbnailName
= video
.getThumbnailName()
388 const thumbnailPath
= constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ thumbnailName
389 fs
.writeFile(thumbnailPath
, Buffer
.from(thumbnailData
, 'binary'), function (err
) {
390 if (err
) return callback(err
)
392 return callback(null, thumbnailName
)
396 function getDurationFromFile (videoPath
, callback
) {
397 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
398 if (err
) return callback(err
)
400 return callback(null, Math
.floor(metadata
.format
.duration
))
404 function list (callback
) {
405 return this.find().asCallback()
408 function listForApi (start
, count
, sort
, callback
) {
412 distinct: true, // For the count, a video can have many tags
413 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ],
416 model: this.sequelize
.models
.Author
,
417 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
420 this.sequelize
.models
.Tag
424 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
425 if (err
) return callback(err
)
427 return callback(null, result
.rows
, result
.count
)
431 function listByHostAndRemoteId (fromHost
, remoteId
, callback
) {
438 model: this.sequelize
.models
.Author
,
441 model: this.sequelize
.models
.Pod
,
452 return this.findAll(query
).asCallback(callback
)
455 function listOwnedAndPopulateAuthorAndTags (callback
) {
456 // If remoteId is null this is *our* video
461 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
464 return this.findAll(query
).asCallback(callback
)
467 function listOwnedByAuthor (author
, callback
) {
474 model: this.sequelize
.models
.Author
,
482 return this.findAll(query
).asCallback(callback
)
485 function load (id
, callback
) {
486 return this.findById(id
).asCallback(callback
)
489 function loadAndPopulateAuthor (id
, callback
) {
491 include: [ this.sequelize
.models
.Author
]
494 return this.findById(id
, options
).asCallback(callback
)
497 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
501 model: this.sequelize
.models
.Author
,
502 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
504 this.sequelize
.models
.Tag
508 return this.findById(id
, options
).asCallback(callback
)
511 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
513 model: this.sequelize
.models
.Pod
,
517 const authorInclude
= {
518 model: this.sequelize
.models
.Author
,
525 model: this.sequelize
.models
.Tag
532 distinct: true, // For the count, a video can have many tags
533 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ]
536 // Make an exact search with the magnet
537 if (field
=== 'magnetUri') {
538 const infoHash
= magnetUtil
.decode(value
).infoHash
539 query
.where
.infoHash
= infoHash
540 } else if (field
=== 'tags') {
541 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
544 $in: this.sequelize
.literal(
545 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
549 } else if (field
=== 'host') {
550 // FIXME: Include our pod? (not stored in the database)
553 $like: '%' + value
+ '%'
556 podInclude
.required
= true
557 } else if (field
=== 'author') {
558 authorInclude
.where
= {
560 $like: '%' + value
+ '%'
564 // authorInclude.or = true
566 query
.where
[field
] = {
567 $like: '%' + value
+ '%'
572 authorInclude
, tagInclude
575 if (tagInclude
.where
) {
576 // query.include.push([ this.sequelize.models.Tag ])
579 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
580 if (err
) return callback(err
)
582 return callback(null, result
.rows
, result
.count
)
586 // ---------------------------------------------------------------------------
588 function removeThumbnail (video
, callback
) {
589 fs
.unlink(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ video
.getThumbnailName(), callback
)
592 function removeFile (video
, callback
) {
593 fs
.unlink(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
+ video
.getVideoFilename(), callback
)
596 function removeTorrent (video
, callback
) {
597 fs
.unlink(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), callback
)
600 function removePreview (video
, callback
) {
601 // Same name than video thumnail
602 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
605 function createPreview (video
, videoPath
, callback
) {
606 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
609 function createThumbnail (video
, videoPath
, callback
) {
610 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
613 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
627 .on('error', callback
)
628 .on('end', function () {
629 callback(null, imageName
)