Server: add video abuse support
[oweals/peertube.git] / server / models / video.js
1 'use strict'
2
3 const Buffer = require('safe-buffer').Buffer
4 const createTorrent = require('create-torrent')
5 const ffmpeg = require('fluent-ffmpeg')
6 const fs = require('fs')
7 const magnetUtil = require('magnet-uri')
8 const map = require('lodash/map')
9 const parallel = require('async/parallel')
10 const parseTorrent = require('parse-torrent')
11 const pathUtils = require('path')
12 const values = require('lodash/values')
13
14 const constants = require('../initializers/constants')
15 const logger = require('../helpers/logger')
16 const friends = require('../lib/friends')
17 const modelUtils = require('./utils')
18 const customVideosValidators = require('../helpers/custom-validators').videos
19
20 // ---------------------------------------------------------------------------
21
22 module.exports = function (sequelize, DataTypes) {
23   const Video = sequelize.define('Video',
24     {
25       id: {
26         type: DataTypes.UUID,
27         defaultValue: DataTypes.UUIDV4,
28         primaryKey: true,
29         validate: {
30           isUUID: 4
31         }
32       },
33       name: {
34         type: DataTypes.STRING,
35         allowNull: false,
36         validate: {
37           nameValid: function (value) {
38             const res = customVideosValidators.isVideoNameValid(value)
39             if (res === false) throw new Error('Video name is not valid.')
40           }
41         }
42       },
43       extname: {
44         type: DataTypes.ENUM(values(constants.CONSTRAINTS_FIELDS.VIDEOS.EXTNAME)),
45         allowNull: false
46       },
47       remoteId: {
48         type: DataTypes.UUID,
49         allowNull: true,
50         validate: {
51           isUUID: 4
52         }
53       },
54       description: {
55         type: DataTypes.STRING,
56         allowNull: false,
57         validate: {
58           descriptionValid: function (value) {
59             const res = customVideosValidators.isVideoDescriptionValid(value)
60             if (res === false) throw new Error('Video description is not valid.')
61           }
62         }
63       },
64       infoHash: {
65         type: DataTypes.STRING,
66         allowNull: false,
67         validate: {
68           infoHashValid: function (value) {
69             const res = customVideosValidators.isVideoInfoHashValid(value)
70             if (res === false) throw new Error('Video info hash is not valid.')
71           }
72         }
73       },
74       duration: {
75         type: DataTypes.INTEGER,
76         allowNull: false,
77         validate: {
78           durationValid: function (value) {
79             const res = customVideosValidators.isVideoDurationValid(value)
80             if (res === false) throw new Error('Video duration is not valid.')
81           }
82         }
83       }
84     },
85     {
86       indexes: [
87         {
88           fields: [ 'authorId' ]
89         },
90         {
91           fields: [ 'remoteId' ]
92         },
93         {
94           fields: [ 'name' ]
95         },
96         {
97           fields: [ 'createdAt' ]
98         },
99         {
100           fields: [ 'duration' ]
101         },
102         {
103           fields: [ 'infoHash' ]
104         }
105       ],
106       classMethods: {
107         associate,
108
109         generateThumbnailFromData,
110         getDurationFromFile,
111         list,
112         listForApi,
113         listOwnedAndPopulateAuthorAndTags,
114         listOwnedByAuthor,
115         load,
116         loadByHostAndRemoteId,
117         loadAndPopulateAuthor,
118         loadAndPopulateAuthorAndPodAndTags,
119         searchAndPopulateAuthorAndPodAndTags
120       },
121       instanceMethods: {
122         generateMagnetUri,
123         getVideoFilename,
124         getThumbnailName,
125         getPreviewName,
126         getTorrentName,
127         isOwned,
128         toFormatedJSON,
129         toAddRemoteJSON,
130         toUpdateRemoteJSON
131       },
132       hooks: {
133         beforeValidate,
134         beforeCreate,
135         afterDestroy
136       }
137     }
138   )
139
140   return Video
141 }
142
143 function beforeValidate (video, options, next) {
144   if (video.isOwned()) {
145     // 40 hexa length
146     video.infoHash = '0123456789abcdef0123456789abcdef01234567'
147   }
148
149   return next(null)
150 }
151
152 function beforeCreate (video, options, next) {
153   const tasks = []
154
155   if (video.isOwned()) {
156     const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
157
158     tasks.push(
159       // TODO: refractoring
160       function (callback) {
161         const options = {
162           announceList: [
163             [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
164           ],
165           urlList: [
166             constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
167           ]
168         }
169
170         createTorrent(videoPath, options, function (err, torrent) {
171           if (err) return callback(err)
172
173           fs.writeFile(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), torrent, function (err) {
174             if (err) return callback(err)
175
176             const parsedTorrent = parseTorrent(torrent)
177             video.set('infoHash', parsedTorrent.infoHash)
178             video.validate().asCallback(callback)
179           })
180         })
181       },
182       function (callback) {
183         createThumbnail(video, videoPath, callback)
184       },
185       function (callback) {
186         createPreview(video, videoPath, callback)
187       }
188     )
189
190     return parallel(tasks, next)
191   }
192
193   return next()
194 }
195
196 function afterDestroy (video, options, next) {
197   const tasks = []
198
199   tasks.push(
200     function (callback) {
201       removeThumbnail(video, callback)
202     }
203   )
204
205   if (video.isOwned()) {
206     tasks.push(
207       function (callback) {
208         removeFile(video, callback)
209       },
210
211       function (callback) {
212         removeTorrent(video, callback)
213       },
214
215       function (callback) {
216         removePreview(video, callback)
217       },
218
219       function (callback) {
220         const params = {
221           name: video.name,
222           remoteId: video.id
223         }
224
225         friends.removeVideoToFriends(params)
226
227         return callback()
228       }
229     )
230   }
231
232   parallel(tasks, next)
233 }
234
235 // ------------------------------ METHODS ------------------------------
236
237 function associate (models) {
238   this.belongsTo(models.Author, {
239     foreignKey: {
240       name: 'authorId',
241       allowNull: false
242     },
243     onDelete: 'cascade'
244   })
245
246   this.belongsToMany(models.Tag, {
247     foreignKey: 'videoId',
248     through: models.VideoTag,
249     onDelete: 'cascade'
250   })
251
252   this.hasMany(models.VideoAbuse, {
253     foreignKey: {
254       name: 'videoId',
255       allowNull: false
256     },
257     onDelete: 'cascade'
258   })
259 }
260
261 function generateMagnetUri () {
262   let baseUrlHttp, baseUrlWs
263
264   if (this.isOwned()) {
265     baseUrlHttp = constants.CONFIG.WEBSERVER.URL
266     baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
267   } else {
268     baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
269     baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
270   }
271
272   const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
273   const announce = baseUrlWs + '/tracker/socket'
274   const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
275
276   const magnetHash = {
277     xs,
278     announce,
279     urlList,
280     infoHash: this.infoHash,
281     name: this.name
282   }
283
284   return magnetUtil.encode(magnetHash)
285 }
286
287 function getVideoFilename () {
288   if (this.isOwned()) return this.id + this.extname
289
290   return this.remoteId + this.extname
291 }
292
293 function getThumbnailName () {
294   // We always have a copy of the thumbnail
295   return this.id + '.jpg'
296 }
297
298 function getPreviewName () {
299   const extension = '.jpg'
300
301   if (this.isOwned()) return this.id + extension
302
303   return this.remoteId + extension
304 }
305
306 function getTorrentName () {
307   const extension = '.torrent'
308
309   if (this.isOwned()) return this.id + extension
310
311   return this.remoteId + extension
312 }
313
314 function isOwned () {
315   return this.remoteId === null
316 }
317
318 function toFormatedJSON () {
319   let podHost
320
321   if (this.Author.Pod) {
322     podHost = this.Author.Pod.host
323   } else {
324     // It means it's our video
325     podHost = constants.CONFIG.WEBSERVER.HOST
326   }
327
328   const json = {
329     id: this.id,
330     name: this.name,
331     description: this.description,
332     podHost,
333     isLocal: this.isOwned(),
334     magnetUri: this.generateMagnetUri(),
335     author: this.Author.name,
336     duration: this.duration,
337     tags: map(this.Tags, 'name'),
338     thumbnailPath: constants.STATIC_PATHS.THUMBNAILS + '/' + this.getThumbnailName(),
339     createdAt: this.createdAt,
340     updatedAt: this.updatedAt
341   }
342
343   return json
344 }
345
346 function toAddRemoteJSON (callback) {
347   const self = this
348
349   // Get thumbnail data to send to the other pod
350   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
351   fs.readFile(thumbnailPath, function (err, thumbnailData) {
352     if (err) {
353       logger.error('Cannot read the thumbnail of the video')
354       return callback(err)
355     }
356
357     const remoteVideo = {
358       name: self.name,
359       description: self.description,
360       infoHash: self.infoHash,
361       remoteId: self.id,
362       author: self.Author.name,
363       duration: self.duration,
364       thumbnailData: thumbnailData.toString('binary'),
365       tags: map(self.Tags, 'name'),
366       createdAt: self.createdAt,
367       updatedAt: self.updatedAt,
368       extname: self.extname
369     }
370
371     return callback(null, remoteVideo)
372   })
373 }
374
375 function toUpdateRemoteJSON (callback) {
376   const json = {
377     name: this.name,
378     description: this.description,
379     infoHash: this.infoHash,
380     remoteId: this.id,
381     author: this.Author.name,
382     duration: this.duration,
383     tags: map(this.Tags, 'name'),
384     createdAt: this.createdAt,
385     updatedAt: this.updatedAt,
386     extname: this.extname
387   }
388
389   return json
390 }
391
392 // ------------------------------ STATICS ------------------------------
393
394 function generateThumbnailFromData (video, thumbnailData, callback) {
395   // Creating the thumbnail for a remote video
396
397   const thumbnailName = video.getThumbnailName()
398   const thumbnailPath = constants.CONFIG.STORAGE.THUMBNAILS_DIR + thumbnailName
399   fs.writeFile(thumbnailPath, Buffer.from(thumbnailData, 'binary'), function (err) {
400     if (err) return callback(err)
401
402     return callback(null, thumbnailName)
403   })
404 }
405
406 function getDurationFromFile (videoPath, callback) {
407   ffmpeg.ffprobe(videoPath, function (err, metadata) {
408     if (err) return callback(err)
409
410     return callback(null, Math.floor(metadata.format.duration))
411   })
412 }
413
414 function list (callback) {
415   return this.find().asCallback()
416 }
417
418 function listForApi (start, count, sort, callback) {
419   const query = {
420     offset: start,
421     limit: count,
422     distinct: true, // For the count, a video can have many tags
423     order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
424     include: [
425       {
426         model: this.sequelize.models.Author,
427         include: [ { model: this.sequelize.models.Pod, required: false } ]
428       },
429
430       this.sequelize.models.Tag
431     ]
432   }
433
434   return this.findAndCountAll(query).asCallback(function (err, result) {
435     if (err) return callback(err)
436
437     return callback(null, result.rows, result.count)
438   })
439 }
440
441 function loadByHostAndRemoteId (fromHost, remoteId, callback) {
442   const query = {
443     where: {
444       remoteId: remoteId
445     },
446     include: [
447       {
448         model: this.sequelize.models.Author,
449         include: [
450           {
451             model: this.sequelize.models.Pod,
452             required: true,
453             where: {
454               host: fromHost
455             }
456           }
457         ]
458       }
459     ]
460   }
461
462   return this.findOne(query).asCallback(callback)
463 }
464
465 function listOwnedAndPopulateAuthorAndTags (callback) {
466   // If remoteId is null this is *our* video
467   const query = {
468     where: {
469       remoteId: null
470     },
471     include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
472   }
473
474   return this.findAll(query).asCallback(callback)
475 }
476
477 function listOwnedByAuthor (author, callback) {
478   const query = {
479     where: {
480       remoteId: null
481     },
482     include: [
483       {
484         model: this.sequelize.models.Author,
485         where: {
486           name: author
487         }
488       }
489     ]
490   }
491
492   return this.findAll(query).asCallback(callback)
493 }
494
495 function load (id, callback) {
496   return this.findById(id).asCallback(callback)
497 }
498
499 function loadAndPopulateAuthor (id, callback) {
500   const options = {
501     include: [ this.sequelize.models.Author ]
502   }
503
504   return this.findById(id, options).asCallback(callback)
505 }
506
507 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
508   const options = {
509     include: [
510       {
511         model: this.sequelize.models.Author,
512         include: [ { model: this.sequelize.models.Pod, required: false } ]
513       },
514       this.sequelize.models.Tag
515     ]
516   }
517
518   return this.findById(id, options).asCallback(callback)
519 }
520
521 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
522   const podInclude = {
523     model: this.sequelize.models.Pod,
524     required: false
525   }
526
527   const authorInclude = {
528     model: this.sequelize.models.Author,
529     include: [
530       podInclude
531     ]
532   }
533
534   const tagInclude = {
535     model: this.sequelize.models.Tag
536   }
537
538   const query = {
539     where: {},
540     offset: start,
541     limit: count,
542     distinct: true, // For the count, a video can have many tags
543     order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
544   }
545
546   // Make an exact search with the magnet
547   if (field === 'magnetUri') {
548     const infoHash = magnetUtil.decode(value).infoHash
549     query.where.infoHash = infoHash
550   } else if (field === 'tags') {
551     const escapedValue = this.sequelize.escape('%' + value + '%')
552     query.where = {
553       id: {
554         $in: this.sequelize.literal(
555           '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
556         )
557       }
558     }
559   } else if (field === 'host') {
560     // FIXME: Include our pod? (not stored in the database)
561     podInclude.where = {
562       host: {
563         $like: '%' + value + '%'
564       }
565     }
566     podInclude.required = true
567   } else if (field === 'author') {
568     authorInclude.where = {
569       name: {
570         $like: '%' + value + '%'
571       }
572     }
573
574     // authorInclude.or = true
575   } else {
576     query.where[field] = {
577       $like: '%' + value + '%'
578     }
579   }
580
581   query.include = [
582     authorInclude, tagInclude
583   ]
584
585   if (tagInclude.where) {
586     // query.include.push([ this.sequelize.models.Tag ])
587   }
588
589   return this.findAndCountAll(query).asCallback(function (err, result) {
590     if (err) return callback(err)
591
592     return callback(null, result.rows, result.count)
593   })
594 }
595
596 // ---------------------------------------------------------------------------
597
598 function removeThumbnail (video, callback) {
599   fs.unlink(constants.CONFIG.STORAGE.THUMBNAILS_DIR + video.getThumbnailName(), callback)
600 }
601
602 function removeFile (video, callback) {
603   fs.unlink(constants.CONFIG.STORAGE.VIDEOS_DIR + video.getVideoFilename(), callback)
604 }
605
606 function removeTorrent (video, callback) {
607   fs.unlink(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), callback)
608 }
609
610 function removePreview (video, callback) {
611   // Same name than video thumnail
612   fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
613 }
614
615 function createPreview (video, videoPath, callback) {
616   generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
617 }
618
619 function createThumbnail (video, videoPath, callback) {
620   generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
621 }
622
623 function generateImage (video, videoPath, folder, imageName, size, callback) {
624   const options = {
625     filename: imageName,
626     count: 1,
627     folder
628   }
629
630   if (!callback) {
631     callback = size
632   } else {
633     options.size = size
634   }
635
636   ffmpeg(videoPath)
637     .on('error', callback)
638     .on('end', function () {
639       callback(null, imageName)
640     })
641     .thumbnail(options)
642 }