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,
54 listByHostAndRemoteId,
55 listOwnedAndPopulateAuthorAndTags,
58 loadAndPopulateAuthor,
59 loadAndPopulateAuthorAndPodAndTags,
60 searchAndPopulateAuthorAndPodAndTags
83 // VideoSchema.path('name').validate(customVideosValidators.isVideoNameValid)
84 // VideoSchema.path('description').validate(customVideosValidators.isVideoDescriptionValid)
85 // VideoSchema.path('podHost').validate(customVideosValidators.isVideoPodHostValid)
86 // VideoSchema.path('author').validate(customVideosValidators.isVideoAuthorValid)
87 // VideoSchema.path('duration').validate(customVideosValidators.isVideoDurationValid)
88 // VideoSchema.path('tags').validate(customVideosValidators.isVideoTagsValid)
90 function beforeCreate (video, options, next) {
93 if (video.isOwned()) {
94 const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
101 [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
104 constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
108 createTorrent(videoPath, options, function (err, torrent) {
109 if (err) return callback(err)
111 fs.writeFile(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), torrent, function (err) {
112 if (err) return callback(err)
114 const parsedTorrent = parseTorrent(torrent)
115 video.infoHash = parsedTorrent.infoHash
121 function (callback) {
122 createThumbnail(video, videoPath, callback)
124 function (callback) {
125 createPreview(video, videoPath, callback)
129 return parallel(tasks, next)
135 function afterDestroy (video, options, next) {
139 function (callback) {
140 removeThumbnail(video, callback)
144 if (video.isOwned()) {
146 function (callback) {
147 removeFile(video, callback)
149 function (callback) {
150 removeTorrent(video, callback)
152 function (callback) {
153 removePreview(video, callback)
158 parallel(tasks, next)
161 // ------------------------------ METHODS ------------------------------
163 function associate (models) {
164 this.belongsTo(models.Author, {
172 this.belongsToMany(models.Tag, {
173 foreignKey: 'videoId',
174 through: models.VideoTag,
179 function generateMagnetUri () {
180 let baseUrlHttp, baseUrlWs
182 if (this.isOwned()) {
183 baseUrlHttp = constants.CONFIG.WEBSERVER.URL
184 baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
186 baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
187 baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
190 const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
191 const announce = baseUrlWs + '/tracker/socket'
192 const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
198 infoHash: this.infoHash,
202 return magnetUtil.encode(magnetHash)
205 function getVideoFilename () {
206 if (this.isOwned()) return this.id + this.extname
208 return this.remoteId + this.extname
211 function getThumbnailName () {
212 // We always have a copy of the thumbnail
213 return this.id + '.jpg'
216 function getPreviewName () {
217 const extension = '.jpg'
219 if (this.isOwned()) return this.id + extension
221 return this.remoteId + extension
224 function getTorrentName () {
225 const extension = '.torrent'
227 if (this.isOwned()) return this.id + extension
229 return this.remoteId + extension
232 function isOwned () {
233 return this.remoteId === null
236 function toFormatedJSON () {
239 if (this.Author.Pod) {
240 podHost = this.Author.Pod.host
242 // It means it's our video
243 podHost = constants.CONFIG.WEBSERVER.HOST
249 description: this.description,
251 isLocal: this.isOwned(),
252 magnetUri: this.generateMagnetUri(),
253 author: this.Author.name,
254 duration: this.duration,
255 tags: map(this.Tags, 'name'),
256 thumbnailPath: constants.STATIC_PATHS.THUMBNAILS + '/' + this.getThumbnailName(),
257 createdAt: this.createdAt
263 function toRemoteJSON (callback) {
266 // Convert thumbnail to base64
267 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
268 fs.readFile(thumbnailPath, function (err, thumbnailData) {
270 logger.error('Cannot read the thumbnail of the video')
274 const remoteVideo = {
276 description: self.description,
277 infoHash: self.infoHash,
279 author: self.Author.name,
280 duration: self.duration,
281 thumbnailBase64: new Buffer(thumbnailData).toString('base64'),
282 tags: map(self.Tags, 'name'),
283 createdAt: self.createdAt,
284 extname: self.extname
287 return callback(null, remoteVideo)
291 // ------------------------------ STATICS ------------------------------
293 function generateThumbnailFromBase64 (video, thumbnailData, callback) {
294 // Creating the thumbnail for a remote video
296 const thumbnailName = video.getThumbnailName()
297 const thumbnailPath = constants.CONFIG.STORAGE.THUMBNAILS_DIR + thumbnailName
298 fs.writeFile(thumbnailPath, thumbnailData, { encoding: 'base64' }, function (err) {
299 if (err) return callback(err)
301 return callback(null, thumbnailName)
305 function getDurationFromFile (videoPath, callback) {
306 ffmpeg.ffprobe(videoPath, function (err, metadata) {
307 if (err) return callback(err)
309 return callback(null, Math.floor(metadata.format.duration))
313 function listForApi (start, count, sort, callback) {
317 distinct: true, // For the count, a video can have many tags
318 order: [ modelUtils.getSort(sort) ],
321 model: this.sequelize.models.Author,
322 include: [ { model: this.sequelize.models.Pod, required: false } ]
325 this.sequelize.models.Tag
329 return this.findAndCountAll(query).asCallback(function (err, result) {
330 if (err) return callback(err)
332 return callback(null, result.rows, result.count)
336 function listByHostAndRemoteId (fromHost, remoteId, callback) {
343 model: this.sequelize.models.Author,
346 model: this.sequelize.models.Pod,
357 return this.findAll(query).asCallback(callback)
360 function listOwnedAndPopulateAuthorAndTags (callback) {
361 // If remoteId is null this is *our* video
366 include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
369 return this.findAll(query).asCallback(callback)
372 function listOwnedByAuthor (author, callback) {
379 model: this.sequelize.models.Author,
387 return this.findAll(query).asCallback(callback)
390 function load (id, callback) {
391 return this.findById(id).asCallback(callback)
394 function loadAndPopulateAuthor (id, callback) {
396 include: [ this.sequelize.models.Author ]
399 return this.findById(id, options).asCallback(callback)
402 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
406 model: this.sequelize.models.Author,
407 include: [ { model: this.sequelize.models.Pod, required: false } ]
409 this.sequelize.models.Tag
413 return this.findById(id, options).asCallback(callback)
416 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
418 model: this.sequelize.models.Pod,
422 const authorInclude = {
423 model: this.sequelize.models.Author,
430 model: this.sequelize.models.Tag
437 distinct: true, // For the count, a video can have many tags
438 order: [ modelUtils.getSort(sort) ]
441 // Make an exact search with the magnet
442 if (field === 'magnetUri') {
443 const infoHash = magnetUtil.decode(value).infoHash
444 query.where.infoHash = infoHash
445 } else if (field === 'tags') {
446 const escapedValue = this.sequelize.escape('%' + value + '%')
449 $in: this.sequelize.literal(
450 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
454 } else if (field === 'host') {
455 // FIXME: Include our pod? (not stored in the database)
458 $like: '%' + value + '%'
461 podInclude.required = true
462 } else if (field === 'author') {
463 authorInclude.where = {
465 $like: '%' + value + '%'
469 // authorInclude.or = true
471 query.where[field] = {
472 $like: '%' + value + '%'
477 authorInclude, tagInclude
480 if (tagInclude.where) {
481 // query.include.push([ this.sequelize.models.Tag ])
484 return this.findAndCountAll(query).asCallback(function (err, result) {
485 if (err) return callback(err)
487 return callback(null, result.rows, result.count)
491 // ---------------------------------------------------------------------------
493 function removeThumbnail (video, callback) {
494 fs.unlink(constants.CONFIG.STORAGE.THUMBNAILS_DIR + video.getThumbnailName(), callback)
497 function removeFile (video, callback) {
498 fs.unlink(constants.CONFIG.STORAGE.VIDEOS_DIR + video.getVideoFilename(), callback)
501 function removeTorrent (video, callback) {
502 fs.unlink(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), callback)
505 function removePreview (video, callback) {
506 // Same name than video thumnail
507 fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
510 function createPreview (video, videoPath, callback) {
511 generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
514 function createThumbnail (video, videoPath, callback) {
515 generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
518 function generateImage (video, videoPath, folder, imageName, size, callback) {
532 .on('error', callback)
533 .on('end', function () {
534 callback(null, imageName)