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 function createVideoTorrent (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 const filePath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
174 fs.writeFile(filePath, 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)
184 function createVideoThumbnail (callback) {
185 createThumbnail(video, videoPath, callback)
188 function createVIdeoPreview (callback) {
189 createPreview(video, videoPath, callback)
193 return parallel(tasks, next)
199 function afterDestroy (video, options, next) {
203 function (callback) {
204 removeThumbnail(video, callback)
208 if (video.isOwned()) {
210 function removeVideoFile (callback) {
211 removeFile(video, callback)
214 function removeVideoTorrent (callback) {
215 removeTorrent(video, callback)
218 function removeVideoPreview (callback) {
219 removePreview(video, callback)
222 function removeVideoToFriends (callback) {
227 friends.removeVideoToFriends(params)
234 parallel(tasks, next)
237 // ------------------------------ METHODS ------------------------------
239 function associate (models) {
240 this.belongsTo(models.Author, {
248 this.belongsToMany(models.Tag, {
249 foreignKey: 'videoId',
250 through: models.VideoTag,
254 this.hasMany(models.VideoAbuse, {
263 function generateMagnetUri () {
264 let baseUrlHttp, baseUrlWs
266 if (this.isOwned()) {
267 baseUrlHttp = constants.CONFIG.WEBSERVER.URL
268 baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
270 baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
271 baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
274 const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
275 const announce = baseUrlWs + '/tracker/socket'
276 const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
282 infoHash: this.infoHash,
286 return magnetUtil.encode(magnetHash)
289 function getVideoFilename () {
290 if (this.isOwned()) return this.id + this.extname
292 return this.remoteId + this.extname
295 function getThumbnailName () {
296 // We always have a copy of the thumbnail
297 return this.id + '.jpg'
300 function getPreviewName () {
301 const extension = '.jpg'
303 if (this.isOwned()) return this.id + extension
305 return this.remoteId + extension
308 function getTorrentName () {
309 const extension = '.torrent'
311 if (this.isOwned()) return this.id + extension
313 return this.remoteId + extension
316 function isOwned () {
317 return this.remoteId === null
320 function toFormatedJSON () {
323 if (this.Author.Pod) {
324 podHost = this.Author.Pod.host
326 // It means it's our video
327 podHost = constants.CONFIG.WEBSERVER.HOST
333 description: this.description,
335 isLocal: this.isOwned(),
336 magnetUri: this.generateMagnetUri(),
337 author: this.Author.name,
338 duration: this.duration,
339 tags: map(this.Tags, 'name'),
340 thumbnailPath: pathUtils.join(constants.STATIC_PATHS.THUMBNAILS, this.getThumbnailName()),
341 createdAt: this.createdAt,
342 updatedAt: this.updatedAt
348 function toAddRemoteJSON (callback) {
351 // Get thumbnail data to send to the other pod
352 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
353 fs.readFile(thumbnailPath, function (err, thumbnailData) {
355 logger.error('Cannot read the thumbnail of the video')
359 const remoteVideo = {
361 description: self.description,
362 infoHash: self.infoHash,
364 author: self.Author.name,
365 duration: self.duration,
366 thumbnailData: thumbnailData.toString('binary'),
367 tags: map(self.Tags, 'name'),
368 createdAt: self.createdAt,
369 updatedAt: self.updatedAt,
370 extname: self.extname
373 return callback(null, remoteVideo)
377 function toUpdateRemoteJSON (callback) {
380 description: this.description,
381 infoHash: this.infoHash,
383 author: this.Author.name,
384 duration: this.duration,
385 tags: map(this.Tags, 'name'),
386 createdAt: this.createdAt,
387 updatedAt: this.updatedAt,
388 extname: this.extname
394 // ------------------------------ STATICS ------------------------------
396 function generateThumbnailFromData (video, thumbnailData, callback) {
397 // Creating the thumbnail for a remote video
399 const thumbnailName = video.getThumbnailName()
400 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
401 fs.writeFile(thumbnailPath, Buffer.from(thumbnailData, 'binary'), function (err) {
402 if (err) return callback(err)
404 return callback(null, thumbnailName)
408 function getDurationFromFile (videoPath, callback) {
409 ffmpeg.ffprobe(videoPath, function (err, metadata) {
410 if (err) return callback(err)
412 return callback(null, Math.floor(metadata.format.duration))
416 function list (callback) {
417 return this.findAll().asCallback(callback)
420 function listForApi (start, count, sort, callback) {
424 distinct: true, // For the count, a video can have many tags
425 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
428 model: this.sequelize.models.Author,
429 include: [ { model: this.sequelize.models.Pod, required: false } ]
432 this.sequelize.models.Tag
436 return this.findAndCountAll(query).asCallback(function (err, result) {
437 if (err) return callback(err)
439 return callback(null, result.rows, result.count)
443 function loadByHostAndRemoteId (fromHost, remoteId, callback) {
450 model: this.sequelize.models.Author,
453 model: this.sequelize.models.Pod,
464 return this.findOne(query).asCallback(callback)
467 function listOwnedAndPopulateAuthorAndTags (callback) {
468 // If remoteId is null this is *our* video
473 include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
476 return this.findAll(query).asCallback(callback)
479 function listOwnedByAuthor (author, callback) {
486 model: this.sequelize.models.Author,
494 return this.findAll(query).asCallback(callback)
497 function load (id, callback) {
498 return this.findById(id).asCallback(callback)
501 function loadAndPopulateAuthor (id, callback) {
503 include: [ this.sequelize.models.Author ]
506 return this.findById(id, options).asCallback(callback)
509 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
513 model: this.sequelize.models.Author,
514 include: [ { model: this.sequelize.models.Pod, required: false } ]
516 this.sequelize.models.Tag
520 return this.findById(id, options).asCallback(callback)
523 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
525 model: this.sequelize.models.Pod,
529 const authorInclude = {
530 model: this.sequelize.models.Author,
537 model: this.sequelize.models.Tag
544 distinct: true, // For the count, a video can have many tags
545 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
548 // Make an exact search with the magnet
549 if (field === 'magnetUri') {
550 const infoHash = magnetUtil.decode(value).infoHash
551 query.where.infoHash = infoHash
552 } else if (field === 'tags') {
553 const escapedValue = this.sequelize.escape('%' + value + '%')
556 $in: this.sequelize.literal(
557 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
561 } else if (field === 'host') {
562 // FIXME: Include our pod? (not stored in the database)
565 $like: '%' + value + '%'
568 podInclude.required = true
569 } else if (field === 'author') {
570 authorInclude.where = {
572 $like: '%' + value + '%'
576 // authorInclude.or = true
578 query.where[field] = {
579 $like: '%' + value + '%'
584 authorInclude, tagInclude
587 if (tagInclude.where) {
588 // query.include.push([ this.sequelize.models.Tag ])
591 return this.findAndCountAll(query).asCallback(function (err, result) {
592 if (err) return callback(err)
594 return callback(null, result.rows, result.count)
598 // ---------------------------------------------------------------------------
600 function removeThumbnail (video, callback) {
601 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
602 fs.unlink(thumbnailPath, callback)
605 function removeFile (video, callback) {
606 const filePath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
607 fs.unlink(filePath, callback)
610 function removeTorrent (video, callback) {
611 const torrenPath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
612 fs.unlink(torrenPath, callback)
615 function removePreview (video, callback) {
616 // Same name than video thumnail
617 fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
620 function createPreview (video, videoPath, callback) {
621 generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
624 function createThumbnail (video, videoPath, callback) {
625 generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
628 function generateImage (video, videoPath, folder, imageName, size, callback) {
642 .on('error', callback)
643 .on('end', function () {
644 callback(null, imageName)