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.')
85 type: DataTypes.INTEGER,
97 fields: [ 'authorId' ]
100 fields: [ 'remoteId' ]
106 fields: [ 'createdAt' ]
109 fields: [ 'duration' ]
112 fields: [ 'infoHash' ]
121 generateThumbnailFromData,
125 listOwnedAndPopulateAuthorAndTags,
128 loadByHostAndRemoteId,
129 loadAndPopulateAuthor,
130 loadAndPopulateAuthorAndPodAndTags,
131 searchAndPopulateAuthorAndPodAndTags
155 function beforeValidate (video, options, next) {
156 // Put a fake infoHash if it does not exists yet
157 if (video.isOwned() && !video.infoHash) {
159 video.infoHash = '0123456789abcdef0123456789abcdef01234567'
165 function beforeCreate (video, options, next) {
168 if (video.isOwned()) {
169 const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
172 function createVideoTorrent (callback) {
175 [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
178 constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
182 createTorrent(videoPath, options, function (err, torrent) {
183 if (err) return callback(err)
185 const filePath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
186 fs.writeFile(filePath, torrent, function (err) {
187 if (err) return callback(err)
189 const parsedTorrent = parseTorrent(torrent)
190 video.set('infoHash', parsedTorrent.infoHash)
191 video.validate().asCallback(callback)
196 function createVideoThumbnail (callback) {
197 createThumbnail(video, videoPath, callback)
200 function createVIdeoPreview (callback) {
201 createPreview(video, videoPath, callback)
205 return parallel(tasks, next)
211 function afterDestroy (video, options, next) {
215 function (callback) {
216 removeThumbnail(video, callback)
220 if (video.isOwned()) {
222 function removeVideoFile (callback) {
223 removeFile(video, callback)
226 function removeVideoTorrent (callback) {
227 removeTorrent(video, callback)
230 function removeVideoPreview (callback) {
231 removePreview(video, callback)
234 function removeVideoToFriends (callback) {
239 friends.removeVideoToFriends(params)
246 parallel(tasks, next)
249 // ------------------------------ METHODS ------------------------------
251 function associate (models) {
252 this.belongsTo(models.Author, {
260 this.belongsToMany(models.Tag, {
261 foreignKey: 'videoId',
262 through: models.VideoTag,
266 this.hasMany(models.VideoAbuse, {
275 function generateMagnetUri () {
276 let baseUrlHttp, baseUrlWs
278 if (this.isOwned()) {
279 baseUrlHttp = constants.CONFIG.WEBSERVER.URL
280 baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
282 baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
283 baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
286 const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
287 const announce = baseUrlWs + '/tracker/socket'
288 const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
294 infoHash: this.infoHash,
298 return magnetUtil.encode(magnetHash)
301 function getVideoFilename () {
302 if (this.isOwned()) return this.id + this.extname
304 return this.remoteId + this.extname
307 function getThumbnailName () {
308 // We always have a copy of the thumbnail
309 return this.id + '.jpg'
312 function getPreviewName () {
313 const extension = '.jpg'
315 if (this.isOwned()) return this.id + extension
317 return this.remoteId + extension
320 function getTorrentName () {
321 const extension = '.torrent'
323 if (this.isOwned()) return this.id + extension
325 return this.remoteId + extension
328 function isOwned () {
329 return this.remoteId === null
332 function toFormatedJSON () {
335 if (this.Author.Pod) {
336 podHost = this.Author.Pod.host
338 // It means it's our video
339 podHost = constants.CONFIG.WEBSERVER.HOST
345 description: this.description,
347 isLocal: this.isOwned(),
348 magnetUri: this.generateMagnetUri(),
349 author: this.Author.name,
350 duration: this.duration,
352 tags: map(this.Tags, 'name'),
353 thumbnailPath: pathUtils.join(constants.STATIC_PATHS.THUMBNAILS, this.getThumbnailName()),
354 createdAt: this.createdAt,
355 updatedAt: this.updatedAt
361 function toAddRemoteJSON (callback) {
364 // Get thumbnail data to send to the other pod
365 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
366 fs.readFile(thumbnailPath, function (err, thumbnailData) {
368 logger.error('Cannot read the thumbnail of the video')
372 const remoteVideo = {
374 description: self.description,
375 infoHash: self.infoHash,
377 author: self.Author.name,
378 duration: self.duration,
379 thumbnailData: thumbnailData.toString('binary'),
380 tags: map(self.Tags, 'name'),
381 createdAt: self.createdAt,
382 updatedAt: self.updatedAt,
383 extname: self.extname
386 return callback(null, remoteVideo)
390 function toUpdateRemoteJSON (callback) {
393 description: this.description,
394 infoHash: this.infoHash,
396 author: this.Author.name,
397 duration: this.duration,
398 tags: map(this.Tags, 'name'),
399 createdAt: this.createdAt,
400 updatedAt: this.updatedAt,
401 extname: this.extname
407 // ------------------------------ STATICS ------------------------------
409 function generateThumbnailFromData (video, thumbnailData, callback) {
410 // Creating the thumbnail for a remote video
412 const thumbnailName = video.getThumbnailName()
413 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
414 fs.writeFile(thumbnailPath, Buffer.from(thumbnailData, 'binary'), function (err) {
415 if (err) return callback(err)
417 return callback(null, thumbnailName)
421 function getDurationFromFile (videoPath, callback) {
422 ffmpeg.ffprobe(videoPath, function (err, metadata) {
423 if (err) return callback(err)
425 return callback(null, Math.floor(metadata.format.duration))
429 function list (callback) {
430 return this.findAll().asCallback(callback)
433 function listForApi (start, count, sort, callback) {
437 distinct: true, // For the count, a video can have many tags
438 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
441 model: this.sequelize.models.Author,
442 include: [ { model: this.sequelize.models.Pod, required: false } ]
445 this.sequelize.models.Tag
449 return this.findAndCountAll(query).asCallback(function (err, result) {
450 if (err) return callback(err)
452 return callback(null, result.rows, result.count)
456 function loadByHostAndRemoteId (fromHost, remoteId, callback) {
463 model: this.sequelize.models.Author,
466 model: this.sequelize.models.Pod,
477 return this.findOne(query).asCallback(callback)
480 function listOwnedAndPopulateAuthorAndTags (callback) {
481 // If remoteId is null this is *our* video
486 include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
489 return this.findAll(query).asCallback(callback)
492 function listOwnedByAuthor (author, callback) {
499 model: this.sequelize.models.Author,
507 return this.findAll(query).asCallback(callback)
510 function load (id, callback) {
511 return this.findById(id).asCallback(callback)
514 function loadAndPopulateAuthor (id, callback) {
516 include: [ this.sequelize.models.Author ]
519 return this.findById(id, options).asCallback(callback)
522 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
526 model: this.sequelize.models.Author,
527 include: [ { model: this.sequelize.models.Pod, required: false } ]
529 this.sequelize.models.Tag
533 return this.findById(id, options).asCallback(callback)
536 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
538 model: this.sequelize.models.Pod,
542 const authorInclude = {
543 model: this.sequelize.models.Author,
550 model: this.sequelize.models.Tag
557 distinct: true, // For the count, a video can have many tags
558 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
561 // Make an exact search with the magnet
562 if (field === 'magnetUri') {
563 const infoHash = magnetUtil.decode(value).infoHash
564 query.where.infoHash = infoHash
565 } else if (field === 'tags') {
566 const escapedValue = this.sequelize.escape('%' + value + '%')
569 $in: this.sequelize.literal(
570 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
574 } else if (field === 'host') {
575 // FIXME: Include our pod? (not stored in the database)
578 $like: '%' + value + '%'
581 podInclude.required = true
582 } else if (field === 'author') {
583 authorInclude.where = {
585 $like: '%' + value + '%'
589 // authorInclude.or = true
591 query.where[field] = {
592 $like: '%' + value + '%'
597 authorInclude, tagInclude
600 if (tagInclude.where) {
601 // query.include.push([ this.sequelize.models.Tag ])
604 return this.findAndCountAll(query).asCallback(function (err, result) {
605 if (err) return callback(err)
607 return callback(null, result.rows, result.count)
611 // ---------------------------------------------------------------------------
613 function removeThumbnail (video, callback) {
614 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
615 fs.unlink(thumbnailPath, callback)
618 function removeFile (video, callback) {
619 const filePath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
620 fs.unlink(filePath, callback)
623 function removeTorrent (video, callback) {
624 const torrenPath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
625 fs.unlink(torrenPath, callback)
628 function removePreview (video, callback) {
629 // Same name than video thumnail
630 fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
633 function createPreview (video, videoPath, callback) {
634 generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
637 function createThumbnail (video, videoPath, callback) {
638 generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
641 function generateImage (video, videoPath, folder, imageName, size, callback) {
655 .on('error', callback)
656 .on('end', function () {
657 callback(null, imageName)