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 modelUtils = require('./utils')
16 const customVideosValidators = require('../helpers/custom-validators').videos
18 // ---------------------------------------------------------------------------
20 module.exports = function (sequelize, DataTypes) {
21 // TODO: add indexes on searchable columns
22 const Video = sequelize.define('Video',
26 defaultValue: DataTypes.UUIDV4,
33 type: DataTypes.STRING,
36 nameValid: function (value) {
37 const res = customVideosValidators.isVideoNameValid(value)
38 if (res === false) throw new Error('Video name is not valid.')
43 type: DataTypes.ENUM(values(constants.CONSTRAINTS_FIELDS.VIDEOS.EXTNAME)),
54 type: DataTypes.STRING,
57 descriptionValid: function (value) {
58 const res = customVideosValidators.isVideoDescriptionValid(value)
59 if (res === false) throw new Error('Video description is not valid.')
64 type: DataTypes.STRING,
67 infoHashValid: function (value) {
68 const res = customVideosValidators.isVideoInfoHashValid(value)
69 if (res === false) throw new Error('Video info hash is not valid.')
74 type: DataTypes.INTEGER,
77 durationValid: function (value) {
78 const res = customVideosValidators.isVideoDurationValid(value)
79 if (res === false) throw new Error('Video duration is not valid.')
87 fields: [ 'authorId' ]
90 fields: [ 'remoteId' ]
96 fields: [ 'createdAt' ]
99 fields: [ 'duration' ]
102 fields: [ 'infoHash' ]
108 generateThumbnailFromBase64,
112 listByHostAndRemoteId,
113 listOwnedAndPopulateAuthorAndTags,
116 loadAndPopulateAuthor,
117 loadAndPopulateAuthorAndPodAndTags,
118 searchAndPopulateAuthorAndPodAndTags
141 function beforeValidate (video, options, next) {
142 if (video.isOwned()) {
144 video.infoHash = '0123456789abcdef0123456789abcdef01234567'
150 function beforeCreate (video, options, next) {
153 if (video.isOwned()) {
154 const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
157 // TODO: refractoring
158 function (callback) {
161 [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
164 constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
168 createTorrent(videoPath, options, function (err, torrent) {
169 if (err) return callback(err)
171 fs.writeFile(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), torrent, function (err) {
172 if (err) return callback(err)
174 const parsedTorrent = parseTorrent(torrent)
175 video.set('infoHash', parsedTorrent.infoHash)
176 video.validate().asCallback(callback)
180 function (callback) {
181 createThumbnail(video, videoPath, callback)
183 function (callback) {
184 createPreview(video, videoPath, callback)
188 return parallel(tasks, next)
194 function afterDestroy (video, options, next) {
198 function (callback) {
199 removeThumbnail(video, callback)
203 if (video.isOwned()) {
205 function (callback) {
206 removeFile(video, callback)
208 function (callback) {
209 removeTorrent(video, callback)
211 function (callback) {
212 removePreview(video, callback)
217 parallel(tasks, next)
220 // ------------------------------ METHODS ------------------------------
222 function associate (models) {
223 this.belongsTo(models.Author, {
231 this.belongsToMany(models.Tag, {
232 foreignKey: 'videoId',
233 through: models.VideoTag,
238 function generateMagnetUri () {
239 let baseUrlHttp, baseUrlWs
241 if (this.isOwned()) {
242 baseUrlHttp = constants.CONFIG.WEBSERVER.URL
243 baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
245 baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
246 baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
249 const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
250 const announce = baseUrlWs + '/tracker/socket'
251 const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
257 infoHash: this.infoHash,
261 return magnetUtil.encode(magnetHash)
264 function getVideoFilename () {
265 if (this.isOwned()) return this.id + this.extname
267 return this.remoteId + this.extname
270 function getThumbnailName () {
271 // We always have a copy of the thumbnail
272 return this.id + '.jpg'
275 function getPreviewName () {
276 const extension = '.jpg'
278 if (this.isOwned()) return this.id + extension
280 return this.remoteId + extension
283 function getTorrentName () {
284 const extension = '.torrent'
286 if (this.isOwned()) return this.id + extension
288 return this.remoteId + extension
291 function isOwned () {
292 return this.remoteId === null
295 function toFormatedJSON () {
298 if (this.Author.Pod) {
299 podHost = this.Author.Pod.host
301 // It means it's our video
302 podHost = constants.CONFIG.WEBSERVER.HOST
308 description: this.description,
310 isLocal: this.isOwned(),
311 magnetUri: this.generateMagnetUri(),
312 author: this.Author.name,
313 duration: this.duration,
314 tags: map(this.Tags, 'name'),
315 thumbnailPath: constants.STATIC_PATHS.THUMBNAILS + '/' + this.getThumbnailName(),
316 createdAt: this.createdAt
322 function toRemoteJSON (callback) {
325 // Convert thumbnail to base64
326 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
327 fs.readFile(thumbnailPath, function (err, thumbnailData) {
329 logger.error('Cannot read the thumbnail of the video')
333 const remoteVideo = {
335 description: self.description,
336 infoHash: self.infoHash,
338 author: self.Author.name,
339 duration: self.duration,
340 thumbnailBase64: new Buffer(thumbnailData).toString('base64'),
341 tags: map(self.Tags, 'name'),
342 createdAt: self.createdAt,
343 extname: self.extname
346 return callback(null, remoteVideo)
350 // ------------------------------ STATICS ------------------------------
352 function generateThumbnailFromBase64 (video, thumbnailData, callback) {
353 // Creating the thumbnail for a remote video
355 const thumbnailName = video.getThumbnailName()
356 const thumbnailPath = constants.CONFIG.STORAGE.THUMBNAILS_DIR + thumbnailName
357 fs.writeFile(thumbnailPath, thumbnailData, { encoding: 'base64' }, function (err) {
358 if (err) return callback(err)
360 return callback(null, thumbnailName)
364 function getDurationFromFile (videoPath, callback) {
365 ffmpeg.ffprobe(videoPath, function (err, metadata) {
366 if (err) return callback(err)
368 return callback(null, Math.floor(metadata.format.duration))
372 function list (callback) {
373 return this.find().asCallback()
376 function listForApi (start, count, sort, callback) {
380 distinct: true, // For the count, a video can have many tags
381 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
384 model: this.sequelize.models.Author,
385 include: [ { model: this.sequelize.models.Pod, required: false } ]
388 this.sequelize.models.Tag
392 return this.findAndCountAll(query).asCallback(function (err, result) {
393 if (err) return callback(err)
395 return callback(null, result.rows, result.count)
399 function listByHostAndRemoteId (fromHost, remoteId, callback) {
406 model: this.sequelize.models.Author,
409 model: this.sequelize.models.Pod,
420 return this.findAll(query).asCallback(callback)
423 function listOwnedAndPopulateAuthorAndTags (callback) {
424 // If remoteId is null this is *our* video
429 include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
432 return this.findAll(query).asCallback(callback)
435 function listOwnedByAuthor (author, callback) {
442 model: this.sequelize.models.Author,
450 return this.findAll(query).asCallback(callback)
453 function load (id, callback) {
454 return this.findById(id).asCallback(callback)
457 function loadAndPopulateAuthor (id, callback) {
459 include: [ this.sequelize.models.Author ]
462 return this.findById(id, options).asCallback(callback)
465 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
469 model: this.sequelize.models.Author,
470 include: [ { model: this.sequelize.models.Pod, required: false } ]
472 this.sequelize.models.Tag
476 return this.findById(id, options).asCallback(callback)
479 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
481 model: this.sequelize.models.Pod,
485 const authorInclude = {
486 model: this.sequelize.models.Author,
493 model: this.sequelize.models.Tag
500 distinct: true, // For the count, a video can have many tags
501 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
504 // Make an exact search with the magnet
505 if (field === 'magnetUri') {
506 const infoHash = magnetUtil.decode(value).infoHash
507 query.where.infoHash = infoHash
508 } else if (field === 'tags') {
509 const escapedValue = this.sequelize.escape('%' + value + '%')
512 $in: this.sequelize.literal(
513 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
517 } else if (field === 'host') {
518 // FIXME: Include our pod? (not stored in the database)
521 $like: '%' + value + '%'
524 podInclude.required = true
525 } else if (field === 'author') {
526 authorInclude.where = {
528 $like: '%' + value + '%'
532 // authorInclude.or = true
534 query.where[field] = {
535 $like: '%' + value + '%'
540 authorInclude, tagInclude
543 if (tagInclude.where) {
544 // query.include.push([ this.sequelize.models.Tag ])
547 return this.findAndCountAll(query).asCallback(function (err, result) {
548 if (err) return callback(err)
550 return callback(null, result.rows, result.count)
554 // ---------------------------------------------------------------------------
556 function removeThumbnail (video, callback) {
557 fs.unlink(constants.CONFIG.STORAGE.THUMBNAILS_DIR + video.getThumbnailName(), callback)
560 function removeFile (video, callback) {
561 fs.unlink(constants.CONFIG.STORAGE.VIDEOS_DIR + video.getVideoFilename(), callback)
564 function removeTorrent (video, callback) {
565 fs.unlink(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), callback)
568 function removePreview (video, callback) {
569 // Same name than video thumnail
570 fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
573 function createPreview (video, videoPath, callback) {
574 generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
577 function createThumbnail (video, videoPath, callback) {
578 generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
581 function generateImage (video, videoPath, folder, imageName, size, callback) {
595 .on('error', callback)
596 .on('end', function () {
597 callback(null, imageName)