3 const createTorrent
= require('create-torrent')
4 const ffmpeg
= require('fluent-ffmpeg')
5 const fs
= require('fs')
6 const magnetUtil
= require('magnet-uri')
7 const map
= require('lodash/map')
8 const parallel
= require('async/parallel')
9 const parseTorrent
= require('parse-torrent')
10 const pathUtils
= require('path')
11 const values
= require('lodash/values')
13 const constants
= require('../initializers/constants')
14 const logger
= require('../helpers/logger')
15 const friends
= require('../lib/friends')
16 const modelUtils
= require('./utils')
17 const customVideosValidators
= require('../helpers/custom-validators').videos
19 // ---------------------------------------------------------------------------
21 module
.exports = function (sequelize
, DataTypes
) {
22 // TODO: add indexes on searchable columns
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 generateThumbnailFromBase64
,
113 listByHostAndRemoteId
,
114 listOwnedAndPopulateAuthorAndTags
,
117 loadAndPopulateAuthor
,
118 loadAndPopulateAuthorAndPodAndTags
,
119 searchAndPopulateAuthorAndPodAndTags
142 function beforeValidate (video
, options
, next
) {
143 if (video
.isOwned()) {
145 video
.infoHash
= '0123456789abcdef0123456789abcdef01234567'
151 function beforeCreate (video
, options
, next
) {
154 if (video
.isOwned()) {
155 const videoPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
158 // TODO: refractoring
159 function (callback
) {
162 [ constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
+ '/tracker/socket' ]
165 constants
.CONFIG
.WEBSERVER
.URL
+ constants
.STATIC_PATHS
.WEBSEED
+ video
.getVideoFilename()
169 createTorrent(videoPath
, options
, function (err
, torrent
) {
170 if (err
) return callback(err
)
172 fs
.writeFile(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), torrent
, function (err
) {
173 if (err
) return callback(err
)
175 const parsedTorrent
= parseTorrent(torrent
)
176 video
.set('infoHash', parsedTorrent
.infoHash
)
177 video
.validate().asCallback(callback
)
181 function (callback
) {
182 createThumbnail(video
, videoPath
, callback
)
184 function (callback
) {
185 createPreview(video
, videoPath
, callback
)
189 return parallel(tasks
, next
)
195 function afterDestroy (video
, options
, next
) {
199 function (callback
) {
200 removeThumbnail(video
, callback
)
204 if (video
.isOwned()) {
206 function (callback
) {
207 removeFile(video
, callback
)
210 function (callback
) {
211 removeTorrent(video
, callback
)
214 function (callback
) {
215 removePreview(video
, callback
)
218 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
,
252 function generateMagnetUri () {
253 let baseUrlHttp
, baseUrlWs
255 if (this.isOwned()) {
256 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
257 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
259 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
260 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
263 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
264 const announce
= baseUrlWs
+ '/tracker/socket'
265 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
271 infoHash: this.infoHash
,
275 return magnetUtil
.encode(magnetHash
)
278 function getVideoFilename () {
279 if (this.isOwned()) return this.id
+ this.extname
281 return this.remoteId
+ this.extname
284 function getThumbnailName () {
285 // We always have a copy of the thumbnail
286 return this.id
+ '.jpg'
289 function getPreviewName () {
290 const extension
= '.jpg'
292 if (this.isOwned()) return this.id
+ extension
294 return this.remoteId
+ extension
297 function getTorrentName () {
298 const extension
= '.torrent'
300 if (this.isOwned()) return this.id
+ extension
302 return this.remoteId
+ extension
305 function isOwned () {
306 return this.remoteId
=== null
309 function toFormatedJSON () {
312 if (this.Author
.Pod
) {
313 podHost
= this.Author
.Pod
.host
315 // It means it's our video
316 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
322 description: this.description
,
324 isLocal: this.isOwned(),
325 magnetUri: this.generateMagnetUri(),
326 author: this.Author
.name
,
327 duration: this.duration
,
328 tags: map(this.Tags
, 'name'),
329 thumbnailPath: constants
.STATIC_PATHS
.THUMBNAILS
+ '/' + this.getThumbnailName(),
330 createdAt: this.createdAt
336 function toRemoteJSON (callback
) {
339 // Convert thumbnail to base64
340 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, this.getThumbnailName())
341 fs
.readFile(thumbnailPath
, function (err
, thumbnailData
) {
343 logger
.error('Cannot read the thumbnail of the video')
347 const remoteVideo
= {
349 description: self
.description
,
350 infoHash: self
.infoHash
,
352 author: self
.Author
.name
,
353 duration: self
.duration
,
354 thumbnailBase64: new Buffer(thumbnailData
).toString('base64'),
355 tags: map(self
.Tags
, 'name'),
356 createdAt: self
.createdAt
,
357 extname: self
.extname
360 return callback(null, remoteVideo
)
364 // ------------------------------ STATICS ------------------------------
366 function generateThumbnailFromBase64 (video
, thumbnailData
, callback
) {
367 // Creating the thumbnail for a remote video
369 const thumbnailName
= video
.getThumbnailName()
370 const thumbnailPath
= constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ thumbnailName
371 fs
.writeFile(thumbnailPath
, thumbnailData
, { encoding: 'base64' }, function (err
) {
372 if (err
) return callback(err
)
374 return callback(null, thumbnailName
)
378 function getDurationFromFile (videoPath
, callback
) {
379 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
380 if (err
) return callback(err
)
382 return callback(null, Math
.floor(metadata
.format
.duration
))
386 function list (callback
) {
387 return this.find().asCallback()
390 function listForApi (start
, count
, sort
, callback
) {
394 distinct: true, // For the count, a video can have many tags
395 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ],
398 model: this.sequelize
.models
.Author
,
399 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
402 this.sequelize
.models
.Tag
406 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
407 if (err
) return callback(err
)
409 return callback(null, result
.rows
, result
.count
)
413 function listByHostAndRemoteId (fromHost
, remoteId
, callback
) {
420 model: this.sequelize
.models
.Author
,
423 model: this.sequelize
.models
.Pod
,
434 return this.findAll(query
).asCallback(callback
)
437 function listOwnedAndPopulateAuthorAndTags (callback
) {
438 // If remoteId is null this is *our* video
443 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
446 return this.findAll(query
).asCallback(callback
)
449 function listOwnedByAuthor (author
, callback
) {
456 model: this.sequelize
.models
.Author
,
464 return this.findAll(query
).asCallback(callback
)
467 function load (id
, callback
) {
468 return this.findById(id
).asCallback(callback
)
471 function loadAndPopulateAuthor (id
, callback
) {
473 include: [ this.sequelize
.models
.Author
]
476 return this.findById(id
, options
).asCallback(callback
)
479 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
483 model: this.sequelize
.models
.Author
,
484 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
486 this.sequelize
.models
.Tag
490 return this.findById(id
, options
).asCallback(callback
)
493 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
495 model: this.sequelize
.models
.Pod
,
499 const authorInclude
= {
500 model: this.sequelize
.models
.Author
,
507 model: this.sequelize
.models
.Tag
514 distinct: true, // For the count, a video can have many tags
515 order: [ modelUtils
.getSort(sort
), [ this.sequelize
.models
.Tag
, 'name', 'ASC' ] ]
518 // Make an exact search with the magnet
519 if (field
=== 'magnetUri') {
520 const infoHash
= magnetUtil
.decode(value
).infoHash
521 query
.where
.infoHash
= infoHash
522 } else if (field
=== 'tags') {
523 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
526 $in: this.sequelize
.literal(
527 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
531 } else if (field
=== 'host') {
532 // FIXME: Include our pod? (not stored in the database)
535 $like: '%' + value
+ '%'
538 podInclude
.required
= true
539 } else if (field
=== 'author') {
540 authorInclude
.where
= {
542 $like: '%' + value
+ '%'
546 // authorInclude.or = true
548 query
.where
[field
] = {
549 $like: '%' + value
+ '%'
554 authorInclude
, tagInclude
557 if (tagInclude
.where
) {
558 // query.include.push([ this.sequelize.models.Tag ])
561 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
562 if (err
) return callback(err
)
564 return callback(null, result
.rows
, result
.count
)
568 // ---------------------------------------------------------------------------
570 function removeThumbnail (video
, callback
) {
571 fs
.unlink(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ video
.getThumbnailName(), callback
)
574 function removeFile (video
, callback
) {
575 fs
.unlink(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
+ video
.getVideoFilename(), callback
)
578 function removeTorrent (video
, callback
) {
579 fs
.unlink(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), callback
)
582 function removePreview (video
, callback
) {
583 // Same name than video thumnail
584 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
587 function createPreview (video
, videoPath
, callback
) {
588 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
591 function createThumbnail (video
, videoPath
, callback
) {
592 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
595 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
609 .on('error', callback
)
610 .on('end', function () {
611 callback(null, imageName
)