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')
12 const constants
= require('../initializers/constants')
13 const logger
= require('../helpers/logger')
14 const modelUtils
= require('./utils')
16 // ---------------------------------------------------------------------------
18 module
.exports = function (sequelize
, DataTypes
) {
19 // TODO: add indexes on searchable columns
20 const Video
= sequelize
.define('Video',
24 defaultValue: DataTypes
.UUIDV4
,
28 type: DataTypes
.STRING
32 type: DataTypes
.STRING
38 type: DataTypes
.STRING
41 type: DataTypes
.STRING
44 type: DataTypes
.INTEGER
51 generateThumbnailFromBase64
,
55 listByHostAndRemoteId
,
56 listOwnedAndPopulateAuthorAndTags
,
59 loadAndPopulateAuthor
,
60 loadAndPopulateAuthorAndPodAndTags
,
61 searchAndPopulateAuthorAndPodAndTags
84 // VideoSchema.path('name').validate(customVideosValidators.isVideoNameValid)
85 // VideoSchema.path('description').validate(customVideosValidators.isVideoDescriptionValid)
86 // VideoSchema.path('podHost').validate(customVideosValidators.isVideoPodHostValid)
87 // VideoSchema.path('author').validate(customVideosValidators.isVideoAuthorValid)
88 // VideoSchema.path('duration').validate(customVideosValidators.isVideoDurationValid)
89 // VideoSchema.path('tags').validate(customVideosValidators.isVideoTagsValid)
91 function beforeCreate (video
, options
, next
) {
94 if (video
.isOwned()) {
95 const videoPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
, video
.getVideoFilename())
102 [ constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
+ '/tracker/socket' ]
105 constants
.CONFIG
.WEBSERVER
.URL
+ constants
.STATIC_PATHS
.WEBSEED
+ video
.getVideoFilename()
109 createTorrent(videoPath
, options
, function (err
, torrent
) {
110 if (err
) return callback(err
)
112 fs
.writeFile(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), torrent
, function (err
) {
113 if (err
) return callback(err
)
115 const parsedTorrent
= parseTorrent(torrent
)
116 video
.infoHash
= parsedTorrent
.infoHash
122 function (callback
) {
123 createThumbnail(video
, videoPath
, callback
)
125 function (callback
) {
126 createPreview(video
, videoPath
, callback
)
130 return parallel(tasks
, next
)
136 function afterDestroy (video
, options
, next
) {
140 function (callback
) {
141 removeThumbnail(video
, callback
)
145 if (video
.isOwned()) {
147 function (callback
) {
148 removeFile(video
, callback
)
150 function (callback
) {
151 removeTorrent(video
, callback
)
153 function (callback
) {
154 removePreview(video
, callback
)
159 parallel(tasks
, next
)
162 // ------------------------------ METHODS ------------------------------
164 function associate (models
) {
165 this.belongsTo(models
.Author
, {
173 this.belongsToMany(models
.Tag
, {
174 foreignKey: 'videoId',
175 through: models
.VideoTag
,
180 function generateMagnetUri () {
181 let baseUrlHttp
, baseUrlWs
183 if (this.isOwned()) {
184 baseUrlHttp
= constants
.CONFIG
.WEBSERVER
.URL
185 baseUrlWs
= constants
.CONFIG
.WEBSERVER
.WS
+ '://' + constants
.CONFIG
.WEBSERVER
.HOSTNAME
+ ':' + constants
.CONFIG
.WEBSERVER
.PORT
187 baseUrlHttp
= constants
.REMOTE_SCHEME
.HTTP
+ '://' + this.Author
.Pod
.host
188 baseUrlWs
= constants
.REMOTE_SCHEME
.WS
+ '://' + this.Author
.Pod
.host
191 const xs
= baseUrlHttp
+ constants
.STATIC_PATHS
.TORRENTS
+ this.getTorrentName()
192 const announce
= baseUrlWs
+ '/tracker/socket'
193 const urlList
= [ baseUrlHttp
+ constants
.STATIC_PATHS
.WEBSEED
+ this.getVideoFilename() ]
199 infoHash: this.infoHash
,
203 return magnetUtil
.encode(magnetHash
)
206 function getVideoFilename () {
207 if (this.isOwned()) return this.id
+ this.extname
209 return this.remoteId
+ this.extname
212 function getThumbnailName () {
213 // We always have a copy of the thumbnail
214 return this.id
+ '.jpg'
217 function getPreviewName () {
218 const extension
= '.jpg'
220 if (this.isOwned()) return this.id
+ extension
222 return this.remoteId
+ extension
225 function getTorrentName () {
226 const extension
= '.torrent'
228 if (this.isOwned()) return this.id
+ extension
230 return this.remoteId
+ extension
233 function isOwned () {
234 return this.remoteId
=== null
237 function toFormatedJSON () {
240 if (this.Author
.Pod
) {
241 podHost
= this.Author
.Pod
.host
243 // It means it's our video
244 podHost
= constants
.CONFIG
.WEBSERVER
.HOST
250 description: this.description
,
252 isLocal: this.isOwned(),
253 magnetUri: this.generateMagnetUri(),
254 author: this.Author
.name
,
255 duration: this.duration
,
256 tags: map(this.Tags
, 'name'),
257 thumbnailPath: constants
.STATIC_PATHS
.THUMBNAILS
+ '/' + this.getThumbnailName(),
258 createdAt: this.createdAt
264 function toRemoteJSON (callback
) {
267 // Convert thumbnail to base64
268 const thumbnailPath
= pathUtils
.join(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, this.getThumbnailName())
269 fs
.readFile(thumbnailPath
, function (err
, thumbnailData
) {
271 logger
.error('Cannot read the thumbnail of the video')
275 const remoteVideo
= {
277 description: self
.description
,
278 infoHash: self
.infoHash
,
280 author: self
.Author
.name
,
281 duration: self
.duration
,
282 thumbnailBase64: new Buffer(thumbnailData
).toString('base64'),
283 tags: map(self
.Tags
, 'name'),
284 createdAt: self
.createdAt
,
285 extname: self
.extname
288 return callback(null, remoteVideo
)
292 // ------------------------------ STATICS ------------------------------
294 function generateThumbnailFromBase64 (video
, thumbnailData
, callback
) {
295 // Creating the thumbnail for a remote video
297 const thumbnailName
= video
.getThumbnailName()
298 const thumbnailPath
= constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ thumbnailName
299 fs
.writeFile(thumbnailPath
, thumbnailData
, { encoding: 'base64' }, function (err
) {
300 if (err
) return callback(err
)
302 return callback(null, thumbnailName
)
306 function getDurationFromFile (videoPath
, callback
) {
307 ffmpeg
.ffprobe(videoPath
, function (err
, metadata
) {
308 if (err
) return callback(err
)
310 return callback(null, Math
.floor(metadata
.format
.duration
))
314 function list (callback
) {
315 return this.find().asCallback()
318 function listForApi (start
, count
, sort
, callback
) {
322 distinct: true, // For the count, a video can have many tags
323 order: [ modelUtils
.getSort(sort
) ],
326 model: this.sequelize
.models
.Author
,
327 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
330 this.sequelize
.models
.Tag
334 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
335 if (err
) return callback(err
)
337 return callback(null, result
.rows
, result
.count
)
341 function listByHostAndRemoteId (fromHost
, remoteId
, callback
) {
348 model: this.sequelize
.models
.Author
,
351 model: this.sequelize
.models
.Pod
,
362 return this.findAll(query
).asCallback(callback
)
365 function listOwnedAndPopulateAuthorAndTags (callback
) {
366 // If remoteId is null this is *our* video
371 include: [ this.sequelize
.models
.Author
, this.sequelize
.models
.Tag
]
374 return this.findAll(query
).asCallback(callback
)
377 function listOwnedByAuthor (author
, callback
) {
384 model: this.sequelize
.models
.Author
,
392 return this.findAll(query
).asCallback(callback
)
395 function load (id
, callback
) {
396 return this.findById(id
).asCallback(callback
)
399 function loadAndPopulateAuthor (id
, callback
) {
401 include: [ this.sequelize
.models
.Author
]
404 return this.findById(id
, options
).asCallback(callback
)
407 function loadAndPopulateAuthorAndPodAndTags (id
, callback
) {
411 model: this.sequelize
.models
.Author
,
412 include: [ { model: this.sequelize
.models
.Pod
, required: false } ]
414 this.sequelize
.models
.Tag
418 return this.findById(id
, options
).asCallback(callback
)
421 function searchAndPopulateAuthorAndPodAndTags (value
, field
, start
, count
, sort
, callback
) {
423 model: this.sequelize
.models
.Pod
,
427 const authorInclude
= {
428 model: this.sequelize
.models
.Author
,
435 model: this.sequelize
.models
.Tag
442 distinct: true, // For the count, a video can have many tags
443 order: [ modelUtils
.getSort(sort
) ]
446 // Make an exact search with the magnet
447 if (field
=== 'magnetUri') {
448 const infoHash
= magnetUtil
.decode(value
).infoHash
449 query
.where
.infoHash
= infoHash
450 } else if (field
=== 'tags') {
451 const escapedValue
= this.sequelize
.escape('%' + value
+ '%')
454 $in: this.sequelize
.literal(
455 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue
+ ')'
459 } else if (field
=== 'host') {
460 // FIXME: Include our pod? (not stored in the database)
463 $like: '%' + value
+ '%'
466 podInclude
.required
= true
467 } else if (field
=== 'author') {
468 authorInclude
.where
= {
470 $like: '%' + value
+ '%'
474 // authorInclude.or = true
476 query
.where
[field
] = {
477 $like: '%' + value
+ '%'
482 authorInclude
, tagInclude
485 if (tagInclude
.where
) {
486 // query.include.push([ this.sequelize.models.Tag ])
489 return this.findAndCountAll(query
).asCallback(function (err
, result
) {
490 if (err
) return callback(err
)
492 return callback(null, result
.rows
, result
.count
)
496 // ---------------------------------------------------------------------------
498 function removeThumbnail (video
, callback
) {
499 fs
.unlink(constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
+ video
.getThumbnailName(), callback
)
502 function removeFile (video
, callback
) {
503 fs
.unlink(constants
.CONFIG
.STORAGE
.VIDEOS_DIR
+ video
.getVideoFilename(), callback
)
506 function removeTorrent (video
, callback
) {
507 fs
.unlink(constants
.CONFIG
.STORAGE
.TORRENTS_DIR
+ video
.getTorrentName(), callback
)
510 function removePreview (video
, callback
) {
511 // Same name than video thumnail
512 fs
.unlink(constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
+ video
.getPreviewName(), callback
)
515 function createPreview (video
, videoPath
, callback
) {
516 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.PREVIEWS_DIR
, video
.getPreviewName(), callback
)
519 function createThumbnail (video
, videoPath
, callback
) {
520 generateImage(video
, videoPath
, constants
.CONFIG
.STORAGE
.THUMBNAILS_DIR
, video
.getThumbnailName(), constants
.THUMBNAILS_SIZE
, callback
)
523 function generateImage (video
, videoPath
, folder
, imageName
, size
, callback
) {
537 .on('error', callback
)
538 .on('end', function () {
539 callback(null, imageName
)