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.')
88 generateThumbnailFromBase64,
92 listByHostAndRemoteId,
93 listOwnedAndPopulateAuthorAndTags,
96 loadAndPopulateAuthor,
97 loadAndPopulateAuthorAndPodAndTags,
98 searchAndPopulateAuthorAndPodAndTags
121 function beforeValidate (video, options, next) {
122 if (video.isOwned()) {
124 video.infoHash = '0123456789abcdef0123456789abcdef01234567'
130 function beforeCreate (video, options, next) {
133 if (video.isOwned()) {
134 const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
137 // TODO: refractoring
138 function (callback) {
141 [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
144 constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
148 createTorrent(videoPath, options, function (err, torrent) {
149 if (err) return callback(err)
151 fs.writeFile(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), torrent, function (err) {
152 if (err) return callback(err)
154 const parsedTorrent = parseTorrent(torrent)
155 video.set('infoHash', parsedTorrent.infoHash)
156 video.validate().asCallback(callback)
160 function (callback) {
161 createThumbnail(video, videoPath, callback)
163 function (callback) {
164 createPreview(video, videoPath, callback)
168 return parallel(tasks, next)
174 function afterDestroy (video, options, next) {
178 function (callback) {
179 removeThumbnail(video, callback)
183 if (video.isOwned()) {
185 function (callback) {
186 removeFile(video, callback)
188 function (callback) {
189 removeTorrent(video, callback)
191 function (callback) {
192 removePreview(video, callback)
197 parallel(tasks, next)
200 // ------------------------------ METHODS ------------------------------
202 function associate (models) {
203 this.belongsTo(models.Author, {
211 this.belongsToMany(models.Tag, {
212 foreignKey: 'videoId',
213 through: models.VideoTag,
218 function generateMagnetUri () {
219 let baseUrlHttp, baseUrlWs
221 if (this.isOwned()) {
222 baseUrlHttp = constants.CONFIG.WEBSERVER.URL
223 baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
225 baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
226 baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
229 const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
230 const announce = baseUrlWs + '/tracker/socket'
231 const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
237 infoHash: this.infoHash,
241 return magnetUtil.encode(magnetHash)
244 function getVideoFilename () {
245 if (this.isOwned()) return this.id + this.extname
247 return this.remoteId + this.extname
250 function getThumbnailName () {
251 // We always have a copy of the thumbnail
252 return this.id + '.jpg'
255 function getPreviewName () {
256 const extension = '.jpg'
258 if (this.isOwned()) return this.id + extension
260 return this.remoteId + extension
263 function getTorrentName () {
264 const extension = '.torrent'
266 if (this.isOwned()) return this.id + extension
268 return this.remoteId + extension
271 function isOwned () {
272 return this.remoteId === null
275 function toFormatedJSON () {
278 if (this.Author.Pod) {
279 podHost = this.Author.Pod.host
281 // It means it's our video
282 podHost = constants.CONFIG.WEBSERVER.HOST
288 description: this.description,
290 isLocal: this.isOwned(),
291 magnetUri: this.generateMagnetUri(),
292 author: this.Author.name,
293 duration: this.duration,
294 tags: map(this.Tags, 'name'),
295 thumbnailPath: constants.STATIC_PATHS.THUMBNAILS + '/' + this.getThumbnailName(),
296 createdAt: this.createdAt
302 function toRemoteJSON (callback) {
305 // Convert thumbnail to base64
306 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
307 fs.readFile(thumbnailPath, function (err, thumbnailData) {
309 logger.error('Cannot read the thumbnail of the video')
313 const remoteVideo = {
315 description: self.description,
316 infoHash: self.infoHash,
318 author: self.Author.name,
319 duration: self.duration,
320 thumbnailBase64: new Buffer(thumbnailData).toString('base64'),
321 tags: map(self.Tags, 'name'),
322 createdAt: self.createdAt,
323 extname: self.extname
326 return callback(null, remoteVideo)
330 // ------------------------------ STATICS ------------------------------
332 function generateThumbnailFromBase64 (video, thumbnailData, callback) {
333 // Creating the thumbnail for a remote video
335 const thumbnailName = video.getThumbnailName()
336 const thumbnailPath = constants.CONFIG.STORAGE.THUMBNAILS_DIR + thumbnailName
337 fs.writeFile(thumbnailPath, thumbnailData, { encoding: 'base64' }, function (err) {
338 if (err) return callback(err)
340 return callback(null, thumbnailName)
344 function getDurationFromFile (videoPath, callback) {
345 ffmpeg.ffprobe(videoPath, function (err, metadata) {
346 if (err) return callback(err)
348 return callback(null, Math.floor(metadata.format.duration))
352 function list (callback) {
353 return this.find().asCallback()
356 function listForApi (start, count, sort, callback) {
360 distinct: true, // For the count, a video can have many tags
361 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
364 model: this.sequelize.models.Author,
365 include: [ { model: this.sequelize.models.Pod, required: false } ]
368 this.sequelize.models.Tag
372 return this.findAndCountAll(query).asCallback(function (err, result) {
373 if (err) return callback(err)
375 return callback(null, result.rows, result.count)
379 function listByHostAndRemoteId (fromHost, remoteId, callback) {
386 model: this.sequelize.models.Author,
389 model: this.sequelize.models.Pod,
400 return this.findAll(query).asCallback(callback)
403 function listOwnedAndPopulateAuthorAndTags (callback) {
404 // If remoteId is null this is *our* video
409 include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
412 return this.findAll(query).asCallback(callback)
415 function listOwnedByAuthor (author, callback) {
422 model: this.sequelize.models.Author,
430 return this.findAll(query).asCallback(callback)
433 function load (id, callback) {
434 return this.findById(id).asCallback(callback)
437 function loadAndPopulateAuthor (id, callback) {
439 include: [ this.sequelize.models.Author ]
442 return this.findById(id, options).asCallback(callback)
445 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
449 model: this.sequelize.models.Author,
450 include: [ { model: this.sequelize.models.Pod, required: false } ]
452 this.sequelize.models.Tag
456 return this.findById(id, options).asCallback(callback)
459 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
461 model: this.sequelize.models.Pod,
465 const authorInclude = {
466 model: this.sequelize.models.Author,
473 model: this.sequelize.models.Tag
480 distinct: true, // For the count, a video can have many tags
481 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
484 // Make an exact search with the magnet
485 if (field === 'magnetUri') {
486 const infoHash = magnetUtil.decode(value).infoHash
487 query.where.infoHash = infoHash
488 } else if (field === 'tags') {
489 const escapedValue = this.sequelize.escape('%' + value + '%')
492 $in: this.sequelize.literal(
493 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
497 } else if (field === 'host') {
498 // FIXME: Include our pod? (not stored in the database)
501 $like: '%' + value + '%'
504 podInclude.required = true
505 } else if (field === 'author') {
506 authorInclude.where = {
508 $like: '%' + value + '%'
512 // authorInclude.or = true
514 query.where[field] = {
515 $like: '%' + value + '%'
520 authorInclude, tagInclude
523 if (tagInclude.where) {
524 // query.include.push([ this.sequelize.models.Tag ])
527 return this.findAndCountAll(query).asCallback(function (err, result) {
528 if (err) return callback(err)
530 return callback(null, result.rows, result.count)
534 // ---------------------------------------------------------------------------
536 function removeThumbnail (video, callback) {
537 fs.unlink(constants.CONFIG.STORAGE.THUMBNAILS_DIR + video.getThumbnailName(), callback)
540 function removeFile (video, callback) {
541 fs.unlink(constants.CONFIG.STORAGE.VIDEOS_DIR + video.getVideoFilename(), callback)
544 function removeTorrent (video, callback) {
545 fs.unlink(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), callback)
548 function removePreview (video, callback) {
549 // Same name than video thumnail
550 fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
553 function createPreview (video, videoPath, callback) {
554 generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
557 function createThumbnail (video, videoPath, callback) {
558 generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
561 function generateImage (video, videoPath, folder, imageName, size, callback) {
575 .on('error', callback)
576 .on('end', function () {
577 callback(null, imageName)