1 import safeBuffer = require('safe-buffer')
2 const Buffer = safeBuffer.Buffer
3 import createTorrent = require('create-torrent')
4 import ffmpeg = require('fluent-ffmpeg')
5 import fs = require('fs')
6 import magnetUtil = require('magnet-uri')
7 import { map, values } from 'lodash'
8 import { parallel, series } from 'async'
9 import parseTorrent = require('parse-torrent')
10 import { join } from 'path'
11 import * as Sequelize from 'sequelize'
13 import { database as db } from '../initializers/database'
21 isVideoDescriptionValid,
34 } from '../initializers'
35 import { JobScheduler, removeVideoToFriends } from '../lib'
37 import { addMethodsToModel, getSort } from './utils'
44 } from './video-interface'
46 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
47 let generateMagnetUri: VideoMethods.GenerateMagnetUri
48 let getVideoFilename: VideoMethods.GetVideoFilename
49 let getThumbnailName: VideoMethods.GetThumbnailName
50 let getPreviewName: VideoMethods.GetPreviewName
51 let getTorrentName: VideoMethods.GetTorrentName
52 let isOwned: VideoMethods.IsOwned
53 let toFormatedJSON: VideoMethods.ToFormatedJSON
54 let toAddRemoteJSON: VideoMethods.ToAddRemoteJSON
55 let toUpdateRemoteJSON: VideoMethods.ToUpdateRemoteJSON
56 let transcodeVideofile: VideoMethods.TranscodeVideofile
58 let generateThumbnailFromData: VideoMethods.GenerateThumbnailFromData
59 let getDurationFromFile: VideoMethods.GetDurationFromFile
60 let list: VideoMethods.List
61 let listForApi: VideoMethods.ListForApi
62 let loadByHostAndRemoteId: VideoMethods.LoadByHostAndRemoteId
63 let listOwnedAndPopulateAuthorAndTags: VideoMethods.ListOwnedAndPopulateAuthorAndTags
64 let listOwnedByAuthor: VideoMethods.ListOwnedByAuthor
65 let load: VideoMethods.Load
66 let loadAndPopulateAuthor: VideoMethods.LoadAndPopulateAuthor
67 let loadAndPopulateAuthorAndPodAndTags: VideoMethods.LoadAndPopulateAuthorAndPodAndTags
68 let searchAndPopulateAuthorAndPodAndTags: VideoMethods.SearchAndPopulateAuthorAndPodAndTags
70 export default function (sequelize, DataTypes) {
71 Video = sequelize.define('Video',
75 defaultValue: DataTypes.UUIDV4,
82 type: DataTypes.STRING,
85 nameValid: function (value) {
86 const res = isVideoNameValid(value)
87 if (res === false) throw new Error('Video name is not valid.')
92 type: DataTypes.ENUM(values(CONSTRAINTS_FIELDS.VIDEOS.EXTNAME)),
103 type: DataTypes.INTEGER,
106 categoryValid: function (value) {
107 const res = isVideoCategoryValid(value)
108 if (res === false) throw new Error('Video category is not valid.')
113 type: DataTypes.INTEGER,
117 licenceValid: function (value) {
118 const res = isVideoLicenceValid(value)
119 if (res === false) throw new Error('Video licence is not valid.')
124 type: DataTypes.INTEGER,
127 languageValid: function (value) {
128 const res = isVideoLanguageValid(value)
129 if (res === false) throw new Error('Video language is not valid.')
134 type: DataTypes.BOOLEAN,
137 nsfwValid: function (value) {
138 const res = isVideoNSFWValid(value)
139 if (res === false) throw new Error('Video nsfw attribute is not valid.')
144 type: DataTypes.STRING,
147 descriptionValid: function (value) {
148 const res = isVideoDescriptionValid(value)
149 if (res === false) throw new Error('Video description is not valid.')
154 type: DataTypes.STRING,
157 infoHashValid: function (value) {
158 const res = isVideoInfoHashValid(value)
159 if (res === false) throw new Error('Video info hash is not valid.')
164 type: DataTypes.INTEGER,
167 durationValid: function (value) {
168 const res = isVideoDurationValid(value)
169 if (res === false) throw new Error('Video duration is not valid.')
174 type: DataTypes.INTEGER,
183 type: DataTypes.INTEGER,
192 type: DataTypes.INTEGER,
204 fields: [ 'authorId' ]
207 fields: [ 'remoteId' ]
213 fields: [ 'createdAt' ]
216 fields: [ 'duration' ]
219 fields: [ 'infoHash' ]
236 const classMethods = [
239 generateThumbnailFromData,
243 listOwnedAndPopulateAuthorAndTags,
246 loadByHostAndRemoteId,
247 loadAndPopulateAuthor,
248 loadAndPopulateAuthorAndPodAndTags,
249 searchAndPopulateAuthorAndPodAndTags
251 const instanceMethods = [
264 addMethodsToModel(Video, classMethods, instanceMethods)
269 function beforeValidate (video, options) {
270 // Put a fake infoHash if it does not exists yet
271 if (video.isOwned() && !video.infoHash) {
273 video.infoHash = '0123456789abcdef0123456789abcdef01234567'
277 function beforeCreate (video, options) {
278 return new Promise(function (resolve, reject) {
281 if (video.isOwned()) {
282 const videoPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
285 function createVideoTorrent (callback) {
286 createTorrentFromVideo(video, videoPath, callback)
289 function createVideoThumbnail (callback) {
290 createThumbnail(video, videoPath, callback)
293 function createVideoPreview (callback) {
294 createPreview(video, videoPath, callback)
298 if (CONFIG.TRANSCODING.ENABLED === true) {
300 function createVideoTranscoderJob (callback) {
305 JobScheduler.Instance.createJob(options.transaction, 'videoTranscoder', dataInput, callback)
310 return parallel(tasks, function (err) {
311 if (err) return reject(err)
321 function afterDestroy (video, options) {
322 return new Promise(function (resolve, reject) {
326 function (callback) {
327 removeThumbnail(video, callback)
331 if (video.isOwned()) {
333 function removeVideoFile (callback) {
334 removeFile(video, callback)
337 function removeVideoTorrent (callback) {
338 removeTorrent(video, callback)
341 function removeVideoPreview (callback) {
342 removePreview(video, callback)
345 function notifyFriends (callback) {
350 removeVideoToFriends(params)
357 parallel(tasks, function (err) {
358 if (err) return reject(err)
365 // ------------------------------ METHODS ------------------------------
367 function associate (models) {
368 Video.belongsTo(models.Author, {
376 Video.belongsToMany(models.Tag, {
377 foreignKey: 'videoId',
378 through: models.VideoTag,
382 Video.hasMany(models.VideoAbuse, {
391 generateMagnetUri = function () {
395 if (this.isOwned()) {
396 baseUrlHttp = CONFIG.WEBSERVER.URL
397 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
399 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
400 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
403 const xs = baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentName()
404 const announce = baseUrlWs + '/tracker/socket'
405 const urlList = [ baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
411 infoHash: this.infoHash,
415 return magnetUtil.encode(magnetHash)
418 getVideoFilename = function () {
419 if (this.isOwned()) return this.id + this.extname
421 return this.remoteId + this.extname
424 getThumbnailName = function () {
425 // We always have a copy of the thumbnail
426 return this.id + '.jpg'
429 getPreviewName = function () {
430 const extension = '.jpg'
432 if (this.isOwned()) return this.id + extension
434 return this.remoteId + extension
437 getTorrentName = function () {
438 const extension = '.torrent'
440 if (this.isOwned()) return this.id + extension
442 return this.remoteId + extension
445 isOwned = function () {
446 return this.remoteId === null
449 toFormatedJSON = function () {
452 if (this.Author.Pod) {
453 podHost = this.Author.Pod.host
455 // It means it's our video
456 podHost = CONFIG.WEBSERVER.HOST
459 // Maybe our pod is not up to date and there are new categories since our version
460 let categoryLabel = VIDEO_CATEGORIES[this.category]
461 if (!categoryLabel) categoryLabel = 'Misc'
463 // Maybe our pod is not up to date and there are new licences since our version
464 let licenceLabel = VIDEO_LICENCES[this.licence]
465 if (!licenceLabel) licenceLabel = 'Unknown'
467 // Language is an optional attribute
468 let languageLabel = VIDEO_LANGUAGES[this.language]
469 if (!languageLabel) languageLabel = 'Unknown'
474 category: this.category,
476 licence: this.licence,
478 language: this.language,
481 description: this.description,
483 isLocal: this.isOwned(),
484 magnetUri: this.generateMagnetUri(),
485 author: this.Author.name,
486 duration: this.duration,
489 dislikes: this.dislikes,
490 tags: map(this.Tags, 'name'),
491 thumbnailPath: join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName()),
492 createdAt: this.createdAt,
493 updatedAt: this.updatedAt
499 toAddRemoteJSON = function (callback) {
500 // Get thumbnail data to send to the other pod
501 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
502 fs.readFile(thumbnailPath, (err, thumbnailData) => {
504 logger.error('Cannot read the thumbnail of the video')
508 const remoteVideo = {
510 category: this.category,
511 licence: this.licence,
512 language: this.language,
514 description: this.description,
515 infoHash: this.infoHash,
517 author: this.Author.name,
518 duration: this.duration,
519 thumbnailData: thumbnailData.toString('binary'),
520 tags: map(this.Tags, 'name'),
521 createdAt: this.createdAt,
522 updatedAt: this.updatedAt,
523 extname: this.extname,
526 dislikes: this.dislikes
529 return callback(null, remoteVideo)
533 toUpdateRemoteJSON = function (callback) {
536 category: this.category,
537 licence: this.licence,
538 language: this.language,
540 description: this.description,
541 infoHash: this.infoHash,
543 author: this.Author.name,
544 duration: this.duration,
545 tags: map(this.Tags, 'name'),
546 createdAt: this.createdAt,
547 updatedAt: this.updatedAt,
548 extname: this.extname,
551 dislikes: this.dislikes
557 transcodeVideofile = function (finalCallback) {
560 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
561 const newExtname = '.mp4'
562 const videoInputPath = join(videosDirectory, video.getVideoFilename())
563 const videoOutputPath = join(videosDirectory, video.id + '-transcoded' + newExtname)
565 ffmpeg(videoInputPath)
566 .output(videoOutputPath)
567 .videoCodec('libx264')
568 .outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
569 .outputOption('-movflags faststart')
570 .on('error', finalCallback)
571 .on('end', function () {
573 function removeOldFile (callback) {
574 fs.unlink(videoInputPath, callback)
577 function moveNewFile (callback) {
578 // Important to do this before getVideoFilename() to take in account the new file extension
579 video.set('extname', newExtname)
581 const newVideoPath = join(videosDirectory, video.getVideoFilename())
582 fs.rename(videoOutputPath, newVideoPath, callback)
585 function torrent (callback) {
586 const newVideoPath = join(videosDirectory, video.getVideoFilename())
587 createTorrentFromVideo(video, newVideoPath, callback)
590 function videoExtension (callback) {
591 video.save().asCallback(callback)
596 // Autodescruction...
597 video.destroy().asCallback(function (err) {
598 if (err) logger.error('Cannot destruct video after transcoding failure.', { error: err })
601 return finalCallback(err)
604 return finalCallback(null)
610 // ------------------------------ STATICS ------------------------------
612 generateThumbnailFromData = function (video, thumbnailData, callback) {
613 // Creating the thumbnail for a remote video
615 const thumbnailName = video.getThumbnailName()
616 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
617 fs.writeFile(thumbnailPath, Buffer.from(thumbnailData, 'binary'), function (err) {
618 if (err) return callback(err)
620 return callback(null, thumbnailName)
624 getDurationFromFile = function (videoPath, callback) {
625 ffmpeg.ffprobe(videoPath, function (err, metadata) {
626 if (err) return callback(err)
628 return callback(null, Math.floor(metadata.format.duration))
632 list = function (callback) {
633 return Video.findAll().asCallback(callback)
636 listForApi = function (start, count, sort, callback) {
637 // Exclude Blakclisted videos from the list
642 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
645 model: Video['sequelize'].models.Author,
646 include: [ { model: Video['sequelize'].models.Pod, required: false } ]
649 Video['sequelize'].models.Tag
651 where: createBaseVideosWhere()
654 return Video.findAndCountAll(query).asCallback(function (err, result) {
655 if (err) return callback(err)
657 return callback(null, result.rows, result.count)
661 loadByHostAndRemoteId = function (fromHost, remoteId, callback) {
668 model: Video['sequelize'].models.Author,
671 model: Video['sequelize'].models.Pod,
682 return Video.findOne(query).asCallback(callback)
685 listOwnedAndPopulateAuthorAndTags = function (callback) {
686 // If remoteId is null this is *our* video
691 include: [ Video['sequelize'].models.Author, Video['sequelize'].models.Tag ]
694 return Video.findAll(query).asCallback(callback)
697 listOwnedByAuthor = function (author, callback) {
704 model: Video['sequelize'].models.Author,
712 return Video.findAll(query).asCallback(callback)
715 load = function (id, callback) {
716 return Video.findById(id).asCallback(callback)
719 loadAndPopulateAuthor = function (id, callback) {
721 include: [ Video['sequelize'].models.Author ]
724 return Video.findById(id, options).asCallback(callback)
727 loadAndPopulateAuthorAndPodAndTags = function (id, callback) {
731 model: Video['sequelize'].models.Author,
732 include: [ { model: Video['sequelize'].models.Pod, required: false } ]
734 Video['sequelize'].models.Tag
738 return Video.findById(id, options).asCallback(callback)
741 searchAndPopulateAuthorAndPodAndTags = function (value, field, start, count, sort, callback) {
742 const podInclude: any = {
743 model: Video['sequelize'].models.Pod,
747 const authorInclude: any = {
748 model: Video['sequelize'].models.Author,
754 const tagInclude: any = {
755 model: Video['sequelize'].models.Tag
760 where: createBaseVideosWhere(),
763 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
766 // Make an exact search with the magnet
767 if (field === 'magnetUri') {
768 const infoHash = magnetUtil.decode(value).infoHash
769 query.where.infoHash = infoHash
770 } else if (field === 'tags') {
771 const escapedValue = Video['sequelize'].escape('%' + value + '%')
772 query.where.id.$in = Video['sequelize'].literal(
773 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
775 } else if (field === 'host') {
776 // FIXME: Include our pod? (not stored in the database)
779 $like: '%' + value + '%'
782 podInclude.required = true
783 } else if (field === 'author') {
784 authorInclude.where = {
786 $like: '%' + value + '%'
790 // authorInclude.or = true
792 query.where[field] = {
793 $like: '%' + value + '%'
798 authorInclude, tagInclude
801 if (tagInclude.where) {
802 // query.include.push([ Video['sequelize'].models.Tag ])
805 return Video.findAndCountAll(query).asCallback(function (err, result) {
806 if (err) return callback(err)
808 return callback(null, result.rows, result.count)
812 // ---------------------------------------------------------------------------
814 function createBaseVideosWhere () {
817 $notIn: Video['sequelize'].literal(
818 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
824 function removeThumbnail (video, callback) {
825 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
826 fs.unlink(thumbnailPath, callback)
829 function removeFile (video, callback) {
830 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
831 fs.unlink(filePath, callback)
834 function removeTorrent (video, callback) {
835 const torrenPath = join(CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
836 fs.unlink(torrenPath, callback)
839 function removePreview (video, callback) {
840 // Same name than video thumnail
841 fs.unlink(CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
844 function createTorrentFromVideo (video, videoPath, callback) {
847 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
850 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + video.getVideoFilename()
854 createTorrent(videoPath, options, function (err, torrent) {
855 if (err) return callback(err)
857 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
858 fs.writeFile(filePath, torrent, function (err) {
859 if (err) return callback(err)
861 const parsedTorrent = parseTorrent(torrent)
862 video.set('infoHash', parsedTorrent.infoHash)
863 video.validate().asCallback(callback)
868 function createPreview (video, videoPath, callback) {
869 generateImage(video, videoPath, CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
872 function createThumbnail (video, videoPath, callback) {
873 generateImage(video, videoPath, CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), THUMBNAILS_SIZE, callback)
876 function generateImage (video, videoPath, folder, imageName, size, callback?) {
877 const options: any = {
890 .on('error', callback)
891 .on('end', function () {
892 callback(null, imageName)
897 function removeFromBlacklist (video, callback) {
898 // Find the blacklisted video
899 db.BlacklistedVideo.loadByVideoId(video.id, function (err, video) {
900 // If an error occured, stop here
902 logger.error('Error when fetching video from blacklist.', { error: err })
906 // If we found the video, remove it from the blacklist
908 video.destroy().asCallback(callback)
910 // If haven't found it, simply ignore it and do nothing