Server: paths refractoring
[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   // Put a fake infoHash if it does not exists yet
145   if (video.isOwned() && !video.infoHash) {
146     // 40 hexa length
147     video.infoHash = '0123456789abcdef0123456789abcdef01234567'
148   }
149
150   return next(null)
151 }
152
153 function beforeCreate (video, options, next) {
154   const tasks = []
155
156   if (video.isOwned()) {
157     const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
158
159     tasks.push(
160       function createVideoTorrent (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           const filePath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
174           fs.writeFile(filePath, torrent, function (err) {
175             if (err) return callback(err)
176
177             const parsedTorrent = parseTorrent(torrent)
178             video.set('infoHash', parsedTorrent.infoHash)
179             video.validate().asCallback(callback)
180           })
181         })
182       },
183
184       function createVideoThumbnail (callback) {
185         createThumbnail(video, videoPath, callback)
186       },
187
188       function createVIdeoPreview (callback) {
189         createPreview(video, videoPath, callback)
190       }
191     )
192
193     return parallel(tasks, next)
194   }
195
196   return next()
197 }
198
199 function afterDestroy (video, options, next) {
200   const tasks = []
201
202   tasks.push(
203     function (callback) {
204       removeThumbnail(video, callback)
205     }
206   )
207
208   if (video.isOwned()) {
209     tasks.push(
210       function removeVideoFile (callback) {
211         removeFile(video, callback)
212       },
213
214       function removeVideoTorrent (callback) {
215         removeTorrent(video, callback)
216       },
217
218       function removeVideoPreview (callback) {
219         removePreview(video, callback)
220       },
221
222       function removeVideoToFriends (callback) {
223         const params = {
224           remoteId: video.id
225         }
226
227         friends.removeVideoToFriends(params)
228
229         return callback()
230       }
231     )
232   }
233
234   parallel(tasks, next)
235 }
236
237 // ------------------------------ METHODS ------------------------------
238
239 function associate (models) {
240   this.belongsTo(models.Author, {
241     foreignKey: {
242       name: 'authorId',
243       allowNull: false
244     },
245     onDelete: 'cascade'
246   })
247
248   this.belongsToMany(models.Tag, {
249     foreignKey: 'videoId',
250     through: models.VideoTag,
251     onDelete: 'cascade'
252   })
253
254   this.hasMany(models.VideoAbuse, {
255     foreignKey: {
256       name: 'videoId',
257       allowNull: false
258     },
259     onDelete: 'cascade'
260   })
261 }
262
263 function generateMagnetUri () {
264   let baseUrlHttp, baseUrlWs
265
266   if (this.isOwned()) {
267     baseUrlHttp = constants.CONFIG.WEBSERVER.URL
268     baseUrlWs = constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
269   } else {
270     baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
271     baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
272   }
273
274   const xs = baseUrlHttp + constants.STATIC_PATHS.TORRENTS + this.getTorrentName()
275   const announce = baseUrlWs + '/tracker/socket'
276   const urlList = [ baseUrlHttp + constants.STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
277
278   const magnetHash = {
279     xs,
280     announce,
281     urlList,
282     infoHash: this.infoHash,
283     name: this.name
284   }
285
286   return magnetUtil.encode(magnetHash)
287 }
288
289 function getVideoFilename () {
290   if (this.isOwned()) return this.id + this.extname
291
292   return this.remoteId + this.extname
293 }
294
295 function getThumbnailName () {
296   // We always have a copy of the thumbnail
297   return this.id + '.jpg'
298 }
299
300 function getPreviewName () {
301   const extension = '.jpg'
302
303   if (this.isOwned()) return this.id + extension
304
305   return this.remoteId + extension
306 }
307
308 function getTorrentName () {
309   const extension = '.torrent'
310
311   if (this.isOwned()) return this.id + extension
312
313   return this.remoteId + extension
314 }
315
316 function isOwned () {
317   return this.remoteId === null
318 }
319
320 function toFormatedJSON () {
321   let podHost
322
323   if (this.Author.Pod) {
324     podHost = this.Author.Pod.host
325   } else {
326     // It means it's our video
327     podHost = constants.CONFIG.WEBSERVER.HOST
328   }
329
330   const json = {
331     id: this.id,
332     name: this.name,
333     description: this.description,
334     podHost,
335     isLocal: this.isOwned(),
336     magnetUri: this.generateMagnetUri(),
337     author: this.Author.name,
338     duration: this.duration,
339     tags: map(this.Tags, 'name'),
340     thumbnailPath: pathUtils.join(constants.STATIC_PATHS.THUMBNAILS, this.getThumbnailName()),
341     createdAt: this.createdAt,
342     updatedAt: this.updatedAt
343   }
344
345   return json
346 }
347
348 function toAddRemoteJSON (callback) {
349   const self = this
350
351   // Get thumbnail data to send to the other pod
352   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
353   fs.readFile(thumbnailPath, function (err, thumbnailData) {
354     if (err) {
355       logger.error('Cannot read the thumbnail of the video')
356       return callback(err)
357     }
358
359     const remoteVideo = {
360       name: self.name,
361       description: self.description,
362       infoHash: self.infoHash,
363       remoteId: self.id,
364       author: self.Author.name,
365       duration: self.duration,
366       thumbnailData: thumbnailData.toString('binary'),
367       tags: map(self.Tags, 'name'),
368       createdAt: self.createdAt,
369       updatedAt: self.updatedAt,
370       extname: self.extname
371     }
372
373     return callback(null, remoteVideo)
374   })
375 }
376
377 function toUpdateRemoteJSON (callback) {
378   const json = {
379     name: this.name,
380     description: this.description,
381     infoHash: this.infoHash,
382     remoteId: this.id,
383     author: this.Author.name,
384     duration: this.duration,
385     tags: map(this.Tags, 'name'),
386     createdAt: this.createdAt,
387     updatedAt: this.updatedAt,
388     extname: this.extname
389   }
390
391   return json
392 }
393
394 // ------------------------------ STATICS ------------------------------
395
396 function generateThumbnailFromData (video, thumbnailData, callback) {
397   // Creating the thumbnail for a remote video
398
399   const thumbnailName = video.getThumbnailName()
400   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
401   fs.writeFile(thumbnailPath, Buffer.from(thumbnailData, 'binary'), function (err) {
402     if (err) return callback(err)
403
404     return callback(null, thumbnailName)
405   })
406 }
407
408 function getDurationFromFile (videoPath, callback) {
409   ffmpeg.ffprobe(videoPath, function (err, metadata) {
410     if (err) return callback(err)
411
412     return callback(null, Math.floor(metadata.format.duration))
413   })
414 }
415
416 function list (callback) {
417   return this.find().asCallback()
418 }
419
420 function listForApi (start, count, sort, callback) {
421   const query = {
422     offset: start,
423     limit: count,
424     distinct: true, // For the count, a video can have many tags
425     order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
426     include: [
427       {
428         model: this.sequelize.models.Author,
429         include: [ { model: this.sequelize.models.Pod, required: false } ]
430       },
431
432       this.sequelize.models.Tag
433     ]
434   }
435
436   return this.findAndCountAll(query).asCallback(function (err, result) {
437     if (err) return callback(err)
438
439     return callback(null, result.rows, result.count)
440   })
441 }
442
443 function loadByHostAndRemoteId (fromHost, remoteId, callback) {
444   const query = {
445     where: {
446       remoteId: remoteId
447     },
448     include: [
449       {
450         model: this.sequelize.models.Author,
451         include: [
452           {
453             model: this.sequelize.models.Pod,
454             required: true,
455             where: {
456               host: fromHost
457             }
458           }
459         ]
460       }
461     ]
462   }
463
464   return this.findOne(query).asCallback(callback)
465 }
466
467 function listOwnedAndPopulateAuthorAndTags (callback) {
468   // If remoteId is null this is *our* video
469   const query = {
470     where: {
471       remoteId: null
472     },
473     include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
474   }
475
476   return this.findAll(query).asCallback(callback)
477 }
478
479 function listOwnedByAuthor (author, callback) {
480   const query = {
481     where: {
482       remoteId: null
483     },
484     include: [
485       {
486         model: this.sequelize.models.Author,
487         where: {
488           name: author
489         }
490       }
491     ]
492   }
493
494   return this.findAll(query).asCallback(callback)
495 }
496
497 function load (id, callback) {
498   return this.findById(id).asCallback(callback)
499 }
500
501 function loadAndPopulateAuthor (id, callback) {
502   const options = {
503     include: [ this.sequelize.models.Author ]
504   }
505
506   return this.findById(id, options).asCallback(callback)
507 }
508
509 function loadAndPopulateAuthorAndPodAndTags (id, callback) {
510   const options = {
511     include: [
512       {
513         model: this.sequelize.models.Author,
514         include: [ { model: this.sequelize.models.Pod, required: false } ]
515       },
516       this.sequelize.models.Tag
517     ]
518   }
519
520   return this.findById(id, options).asCallback(callback)
521 }
522
523 function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
524   const podInclude = {
525     model: this.sequelize.models.Pod,
526     required: false
527   }
528
529   const authorInclude = {
530     model: this.sequelize.models.Author,
531     include: [
532       podInclude
533     ]
534   }
535
536   const tagInclude = {
537     model: this.sequelize.models.Tag
538   }
539
540   const query = {
541     where: {},
542     offset: start,
543     limit: count,
544     distinct: true, // For the count, a video can have many tags
545     order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
546   }
547
548   // Make an exact search with the magnet
549   if (field === 'magnetUri') {
550     const infoHash = magnetUtil.decode(value).infoHash
551     query.where.infoHash = infoHash
552   } else if (field === 'tags') {
553     const escapedValue = this.sequelize.escape('%' + value + '%')
554     query.where = {
555       id: {
556         $in: this.sequelize.literal(
557           '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
558         )
559       }
560     }
561   } else if (field === 'host') {
562     // FIXME: Include our pod? (not stored in the database)
563     podInclude.where = {
564       host: {
565         $like: '%' + value + '%'
566       }
567     }
568     podInclude.required = true
569   } else if (field === 'author') {
570     authorInclude.where = {
571       name: {
572         $like: '%' + value + '%'
573       }
574     }
575
576     // authorInclude.or = true
577   } else {
578     query.where[field] = {
579       $like: '%' + value + '%'
580     }
581   }
582
583   query.include = [
584     authorInclude, tagInclude
585   ]
586
587   if (tagInclude.where) {
588     // query.include.push([ this.sequelize.models.Tag ])
589   }
590
591   return this.findAndCountAll(query).asCallback(function (err, result) {
592     if (err) return callback(err)
593
594     return callback(null, result.rows, result.count)
595   })
596 }
597
598 // ---------------------------------------------------------------------------
599
600 function removeThumbnail (video, callback) {
601   const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
602   fs.unlink(thumbnailPath, callback)
603 }
604
605 function removeFile (video, callback) {
606   const filePath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
607   fs.unlink(filePath, callback)
608 }
609
610 function removeTorrent (video, callback) {
611   const torrenPath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
612   fs.unlink(torrenPath, callback)
613 }
614
615 function removePreview (video, callback) {
616   // Same name than video thumnail
617   fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
618 }
619
620 function createPreview (video, videoPath, callback) {
621   generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
622 }
623
624 function createThumbnail (video, videoPath, callback) {
625   generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
626 }
627
628 function generateImage (video, videoPath, folder, imageName, size, callback) {
629   const options = {
630     filename: imageName,
631     count: 1,
632     folder
633   }
634
635   if (!callback) {
636     callback = size
637   } else {
638     options.size = size
639   }
640
641   ffmpeg(videoPath)
642     .on('error', callback)
643     .on('end', function () {
644       callback(null, imageName)
645     })
646     .thumbnail(options)
647 }