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 parallel = require('async/parallel')
8 const parseTorrent = require('parse-torrent')
9 const pathUtils = require('path')
11 const constants = require('../initializers/constants')
12 const logger = require('../helpers/logger')
13 const modelUtils = require('./utils')
15 // ---------------------------------------------------------------------------
17 module.exports = function (sequelize, DataTypes) {
18 // TODO: add indexes on searchable columns
19 const Video = sequelize.define('Video',
23 defaultValue: DataTypes.UUIDV4,
27 type: DataTypes.STRING
31 type: DataTypes.STRING
37 type: DataTypes.STRING
40 type: DataTypes.STRING
43 type: DataTypes.INTEGER
46 type: DataTypes.ARRAY(DataTypes.STRING)
53 generateThumbnailFromBase64,
56 listByHostAndRemoteId,
57 listOwnedAndPopulateAuthor,
60 loadAndPopulateAuthor,
61 loadAndPopulateAuthorAndPod,
62 searchAndPopulateAuthorAndPod
85 // VideoSchema.path('name').validate(customVideosValidators.isVideoNameValid)
86 // VideoSchema.path('description').validate(customVideosValidators.isVideoDescriptionValid)
87 // VideoSchema.path('podHost').validate(customVideosValidators.isVideoPodHostValid)
88 // VideoSchema.path('author').validate(customVideosValidators.isVideoAuthorValid)
89 // VideoSchema.path('duration').validate(customVideosValidators.isVideoDurationValid)
90 // VideoSchema.path('tags').validate(customVideosValidators.isVideoTagsValid)
92 function beforeCreate (video, options, next) {
95 if (video.isOwned()) {
96 const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
100 function (callback) {
103 [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
106 constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
110 createTorrent(videoPath, options, function (err, torrent) {
111 if (err) return callback(err)
113 fs.writeFile(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), torrent, function (err) {
114 if (err) return callback(err)
116 const parsedTorrent = parseTorrent(torrent)
117 video.infoHash = parsedTorrent.infoHash
123 function (callback) {
124 createThumbnail(video, videoPath, callback)
126 function (callback) {
127 createPreview(video, videoPath, callback)
131 return parallel(tasks, next)
137 function afterDestroy (video, options, next) {
141 function (callback) {
142 removeThumbnail(video, callback)
146 if (video.isOwned()) {
148 function (callback) {
149 removeFile(video, callback)
151 function (callback) {
152 removeTorrent(video, callback)
154 function (callback) {
155 removePreview(video, callback)
160 parallel(tasks, next)
163 // ------------------------------ METHODS ------------------------------
165 function associate (models) {
166 this.belongsTo(models.Author, {
175 function generateMagnetUri () {
176 let baseUrlHttp, baseUrlWs
178 if (this.isOwned()) {
179 baseUrlHttp = constants.CONFIG.WEBSERVER.URL
180 baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
182 baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
183 baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
186 const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
187 const announce = baseUrlWs + '/tracker/socket'
188 const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
194 infoHash: this.infoHash,
198 return magnetUtil.encode(magnetHash)
201 function getVideoFilename () {
202 if (this.isOwned()) return this.id + this.extname
204 return this.remoteId + this.extname
207 function getThumbnailName () {
208 // We always have a copy of the thumbnail
209 return this.id + '.jpg'
212 function getPreviewName () {
213 const extension = '.jpg'
215 if (this.isOwned()) return this.id + extension
217 return this.remoteId + extension
220 function getTorrentName () {
221 const extension = '.torrent'
223 if (this.isOwned()) return this.id + extension
225 return this.remoteId + extension
228 function isOwned () {
229 return this.remoteId === null
232 function toFormatedJSON () {
235 if (this.Author.Pod) {
236 podHost = this.Author.Pod.host
238 // It means it's our video
239 podHost = constants.CONFIG.WEBSERVER.HOST
245 description: this.description,
247 isLocal: this.isOwned(),
248 magnetUri: this.generateMagnetUri(),
249 author: this.Author.name,
250 duration: this.duration,
252 thumbnailPath: constants.STATIC_PATHS.THUMBNAILS + '/' + this.getThumbnailName(),
253 createdAt: this.createdAt
259 function toRemoteJSON (callback) {
262 // Convert thumbnail to base64
263 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
264 fs.readFile(thumbnailPath, function (err, thumbnailData) {
266 logger.error('Cannot read the thumbnail of the video')
270 const remoteVideo = {
272 description: self.description,
273 infoHash: self.infoHash,
275 author: self.Author.name,
276 duration: self.duration,
277 thumbnailBase64: new Buffer(thumbnailData).toString('base64'),
279 createdAt: self.createdAt,
280 extname: self.extname
283 return callback(null, remoteVideo)
287 // ------------------------------ STATICS ------------------------------
289 function generateThumbnailFromBase64 (video, thumbnailData, callback) {
290 // Creating the thumbnail for a remote video
292 const thumbnailName = video.getThumbnailName()
293 const thumbnailPath = constants.CONFIG.STORAGE.THUMBNAILS_DIR + thumbnailName
294 fs.writeFile(thumbnailPath, thumbnailData, { encoding: 'base64' }, function (err) {
295 if (err) return callback(err)
297 return callback(null, thumbnailName)
301 function getDurationFromFile (videoPath, callback) {
302 ffmpeg.ffprobe(videoPath, function (err, metadata) {
303 if (err) return callback(err)
305 return callback(null, Math.floor(metadata.format.duration))
309 function listForApi (start, count, sort, callback) {
313 order: [ modelUtils.getSort(sort) ],
316 model: this.sequelize.models.Author,
317 include: [ this.sequelize.models.Pod ]
322 return this.findAndCountAll(query).asCallback(function (err, result) {
323 if (err) return callback(err)
325 return callback(null, result.rows, result.count)
329 function listByHostAndRemoteId (fromHost, remoteId, callback) {
336 model: this.sequelize.models.Author,
339 model: this.sequelize.models.Pod,
349 return this.findAll(query).asCallback(callback)
352 function listOwnedAndPopulateAuthor (callback) {
353 // If remoteId is null this is *our* video
358 include: [ this.sequelize.models.Author ]
361 return this.findAll(query).asCallback(callback)
364 function listOwnedByAuthor (author, callback) {
371 model: this.sequelize.models.Author,
379 return this.findAll(query).asCallback(callback)
382 function load (id, callback) {
383 return this.findById(id).asCallback(callback)
386 function loadAndPopulateAuthor (id, callback) {
388 include: [ this.sequelize.models.Author ]
391 return this.findById(id, options).asCallback(callback)
394 function loadAndPopulateAuthorAndPod (id, callback) {
398 model: this.sequelize.models.Author,
399 include: [ this.sequelize.models.Pod ]
404 return this.findById(id, options).asCallback(callback)
407 function searchAndPopulateAuthorAndPod (value, field, start, count, sort, callback) {
409 model: this.sequelize.models.Pod
411 const authorInclude = {
412 model: this.sequelize.models.Author,
425 order: [ modelUtils.getSort(sort) ]
428 // TODO: include our pod for podHost searches (we are not stored in the database)
429 // Make an exact search with the magnet
430 if (field === 'magnetUri') {
431 const infoHash = magnetUtil.decode(value).infoHash
432 query.where.infoHash = infoHash
433 } else if (field === 'tags') {
434 query.where[field] = value
435 } else if (field === 'host') {
437 '$Author.Pod.host$': {
438 $like: '%' + value + '%'
442 // Include our pod? (not stored in the database)
443 if (constants.CONFIG.WEBSERVER.HOST.indexOf(value) !== -1) {
453 query.where = whereQuery
455 } else if (field === 'author') {
458 $like: '%' + value + '%'
462 query.where[field] = {
463 $like: '%' + value + '%'
467 return this.findAndCountAll(query).asCallback(function (err, result) {
468 if (err) return callback(err)
470 return callback(null, result.rows, result.count)
474 // ---------------------------------------------------------------------------
476 function removeThumbnail (video, callback) {
477 fs.unlink(constants.CONFIG.STORAGE.THUMBNAILS_DIR + video.getThumbnailName(), callback)
480 function removeFile (video, callback) {
481 fs.unlink(constants.CONFIG.STORAGE.VIDEOS_DIR + video.getVideoFilename(), callback)
484 function removeTorrent (video, callback) {
485 fs.unlink(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), callback)
488 function removePreview (video, callback) {
489 // Same name than video thumnail
490 fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
493 function createPreview (video, videoPath, callback) {
494 generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
497 function createThumbnail (video, videoPath, callback) {
498 generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
501 function generateImage (video, videoPath, folder, imageName, size, callback) {
515 .on('error', callback)
516 .on('end', function () {
517 callback(null, imageName)