]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video.js
Server: update express-validator
[github/Chocobozzz/PeerTube.git] / server / models / video.js
CommitLineData
aaf61f38
C
1'use strict'
2
4d324488 3const Buffer = require('safe-buffer').Buffer
052937db 4const createTorrent = require('create-torrent')
aaf61f38
C
5const ffmpeg = require('fluent-ffmpeg')
6const fs = require('fs')
f285faa0 7const magnetUtil = require('magnet-uri')
7920c273 8const map = require('lodash/map')
1a42c9e2 9const parallel = require('async/parallel')
052937db 10const parseTorrent = require('parse-torrent')
aaf61f38 11const pathUtils = require('path')
67bf9b96 12const values = require('lodash/values')
aaf61f38
C
13
14const constants = require('../initializers/constants')
aaf61f38 15const logger = require('../helpers/logger')
98ac898a 16const friends = require('../lib/friends')
0ff21c1c 17const modelUtils = require('./utils')
67bf9b96 18const customVideosValidators = require('../helpers/custom-validators').videos
aaf61f38 19
aaf61f38
C
20// ---------------------------------------------------------------------------
21
feb4bdfd 22module.exports = function (sequelize, DataTypes) {
feb4bdfd
C
23 const Video = sequelize.define('Video',
24 {
25 id: {
26 type: DataTypes.UUID,
27 defaultValue: DataTypes.UUIDV4,
67bf9b96
C
28 primaryKey: true,
29 validate: {
30 isUUID: 4
31 }
aaf61f38 32 },
feb4bdfd 33 name: {
67bf9b96
C
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 }
6a94a109 42 },
feb4bdfd 43 extname: {
67bf9b96
C
44 type: DataTypes.ENUM(values(constants.CONSTRAINTS_FIELDS.VIDEOS.EXTNAME)),
45 allowNull: false
feb4bdfd
C
46 },
47 remoteId: {
67bf9b96
C
48 type: DataTypes.UUID,
49 allowNull: true,
50 validate: {
51 isUUID: 4
52 }
feb4bdfd
C
53 },
54 description: {
67bf9b96
C
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 }
feb4bdfd
C
63 },
64 infoHash: {
67bf9b96
C
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 }
feb4bdfd
C
73 },
74 duration: {
67bf9b96
C
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 }
aaf61f38 83 }
feb4bdfd
C
84 },
85 {
319d072e
C
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 ],
feb4bdfd
C
106 classMethods: {
107 associate,
108
4d324488 109 generateThumbnailFromData,
feb4bdfd 110 getDurationFromFile,
b769007f 111 list,
feb4bdfd 112 listForApi,
7920c273 113 listOwnedAndPopulateAuthorAndTags,
feb4bdfd
C
114 listOwnedByAuthor,
115 load,
3d118fb5 116 loadByHostAndRemoteId,
feb4bdfd 117 loadAndPopulateAuthor,
7920c273
C
118 loadAndPopulateAuthorAndPodAndTags,
119 searchAndPopulateAuthorAndPodAndTags
feb4bdfd
C
120 },
121 instanceMethods: {
122 generateMagnetUri,
123 getVideoFilename,
124 getThumbnailName,
125 getPreviewName,
126 getTorrentName,
127 isOwned,
128 toFormatedJSON,
7b1f49de
C
129 toAddRemoteJSON,
130 toUpdateRemoteJSON
feb4bdfd
C
131 },
132 hooks: {
67bf9b96 133 beforeValidate,
feb4bdfd
C
134 beforeCreate,
135 afterDestroy
136 }
137 }
138 )
aaf61f38 139
feb4bdfd
C
140 return Video
141}
aaf61f38 142
67bf9b96 143function beforeValidate (video, options, next) {
7f4e7c36
C
144 // Put a fake infoHash if it does not exists yet
145 if (video.isOwned() && !video.infoHash) {
67bf9b96
C
146 // 40 hexa length
147 video.infoHash = '0123456789abcdef0123456789abcdef01234567'
148 }
149
150 return next(null)
151}
feb4bdfd
C
152
153function beforeCreate (video, options, next) {
aaf61f38
C
154 const tasks = []
155
156 if (video.isOwned()) {
f285faa0 157 const videoPath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
aaf61f38
C
158
159 tasks.push(
15103f11 160 function createVideoTorrent (callback) {
25cad919
C
161 const options = {
162 announceList: [
3737bbaf 163 [ constants.CONFIG.WEBSERVER.WS + '://' + constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
25cad919
C
164 ],
165 urlList: [
f285faa0 166 constants.CONFIG.WEBSERVER.URL + constants.STATIC_PATHS.WEBSEED + video.getVideoFilename()
25cad919
C
167 ]
168 }
169
170 createTorrent(videoPath, options, function (err, torrent) {
052937db
C
171 if (err) return callback(err)
172
15103f11
C
173 const filePath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
174 fs.writeFile(filePath, torrent, function (err) {
052937db
C
175 if (err) return callback(err)
176
177 const parsedTorrent = parseTorrent(torrent)
67bf9b96
C
178 video.set('infoHash', parsedTorrent.infoHash)
179 video.validate().asCallback(callback)
052937db
C
180 })
181 })
aaf61f38 182 },
15103f11
C
183
184 function createVideoThumbnail (callback) {
558d7c23 185 createThumbnail(video, videoPath, callback)
6a94a109 186 },
15103f11
C
187
188 function createVIdeoPreview (callback) {
558d7c23 189 createPreview(video, videoPath, callback)
aaf61f38
C
190 }
191 )
192
c77fa067 193 return parallel(tasks, next)
aaf61f38 194 }
c77fa067
C
195
196 return next()
feb4bdfd 197}
aaf61f38 198
feb4bdfd
C
199function 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(
15103f11 210 function removeVideoFile (callback) {
feb4bdfd
C
211 removeFile(video, callback)
212 },
98ac898a 213
15103f11 214 function removeVideoTorrent (callback) {
feb4bdfd
C
215 removeTorrent(video, callback)
216 },
98ac898a 217
15103f11 218 function removeVideoPreview (callback) {
feb4bdfd 219 removePreview(video, callback)
98ac898a
C
220 },
221
15103f11 222 function removeVideoToFriends (callback) {
98ac898a 223 const params = {
98ac898a
C
224 remoteId: video.id
225 }
226
227 friends.removeVideoToFriends(params)
228
229 return callback()
feb4bdfd
C
230 }
231 )
232 }
233
234 parallel(tasks, next)
235}
aaf61f38
C
236
237// ------------------------------ METHODS ------------------------------
238
feb4bdfd
C
239function associate (models) {
240 this.belongsTo(models.Author, {
241 foreignKey: {
242 name: 'authorId',
243 allowNull: false
244 },
245 onDelete: 'cascade'
246 })
7920c273
C
247
248 this.belongsToMany(models.Tag, {
249 foreignKey: 'videoId',
250 through: models.VideoTag,
251 onDelete: 'cascade'
252 })
55fa55a9
C
253
254 this.hasMany(models.VideoAbuse, {
255 foreignKey: {
256 name: 'videoId',
257 allowNull: false
258 },
259 onDelete: 'cascade'
260 })
feb4bdfd
C
261}
262
f285faa0
C
263function 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 {
feb4bdfd
C
270 baseUrlHttp = constants.REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
271 baseUrlWs = constants.REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
f285faa0
C
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,
feb4bdfd 282 infoHash: this.infoHash,
f285faa0
C
283 name: this.name
284 }
285
286 return magnetUtil.encode(magnetHash)
558d7c23
C
287}
288
f285faa0 289function getVideoFilename () {
feb4bdfd 290 if (this.isOwned()) return this.id + this.extname
f285faa0
C
291
292 return this.remoteId + this.extname
293}
294
295function getThumbnailName () {
296 // We always have a copy of the thumbnail
feb4bdfd 297 return this.id + '.jpg'
558d7c23
C
298}
299
f285faa0
C
300function getPreviewName () {
301 const extension = '.jpg'
302
feb4bdfd 303 if (this.isOwned()) return this.id + extension
f285faa0
C
304
305 return this.remoteId + extension
306}
307
558d7c23 308function getTorrentName () {
f285faa0
C
309 const extension = '.torrent'
310
feb4bdfd 311 if (this.isOwned()) return this.id + extension
f285faa0
C
312
313 return this.remoteId + extension
558d7c23
C
314}
315
aaf61f38 316function isOwned () {
558d7c23 317 return this.remoteId === null
aaf61f38
C
318}
319
320function toFormatedJSON () {
feb4bdfd
C
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
aaf61f38 330 const json = {
feb4bdfd 331 id: this.id,
aaf61f38
C
332 name: this.name,
333 description: this.description,
feb4bdfd 334 podHost,
aaf61f38 335 isLocal: this.isOwned(),
f285faa0 336 magnetUri: this.generateMagnetUri(),
feb4bdfd 337 author: this.Author.name,
aaf61f38 338 duration: this.duration,
7920c273 339 tags: map(this.Tags, 'name'),
91cc839a 340 thumbnailPath: pathUtils.join(constants.STATIC_PATHS.THUMBNAILS, this.getThumbnailName()),
79066fdf
C
341 createdAt: this.createdAt,
342 updatedAt: this.updatedAt
aaf61f38
C
343 }
344
345 return json
346}
347
7b1f49de 348function toAddRemoteJSON (callback) {
aaf61f38
C
349 const self = this
350
4d324488 351 // Get thumbnail data to send to the other pod
f285faa0 352 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
558d7c23 353 fs.readFile(thumbnailPath, function (err, thumbnailData) {
aaf61f38
C
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,
feb4bdfd
C
362 infoHash: self.infoHash,
363 remoteId: self.id,
364 author: self.Author.name,
aaf61f38 365 duration: self.duration,
4d324488 366 thumbnailData: thumbnailData.toString('binary'),
7920c273 367 tags: map(self.Tags, 'name'),
feb4bdfd 368 createdAt: self.createdAt,
79066fdf 369 updatedAt: self.updatedAt,
8f217302 370 extname: self.extname
aaf61f38
C
371 }
372
373 return callback(null, remoteVideo)
374 })
375}
376
7b1f49de
C
377function 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,
79066fdf 387 updatedAt: this.updatedAt,
7b1f49de
C
388 extname: this.extname
389 }
390
391 return json
392}
393
aaf61f38
C
394// ------------------------------ STATICS ------------------------------
395
4d324488 396function generateThumbnailFromData (video, thumbnailData, callback) {
c77fa067
C
397 // Creating the thumbnail for a remote video
398
399 const thumbnailName = video.getThumbnailName()
15103f11 400 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
4d324488 401 fs.writeFile(thumbnailPath, Buffer.from(thumbnailData, 'binary'), function (err) {
c77fa067
C
402 if (err) return callback(err)
403
404 return callback(null, thumbnailName)
405 })
406}
407
aaf61f38
C
408function 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
b769007f 416function list (callback) {
9cc99d7b 417 return this.findAll().asCallback(callback)
b769007f
C
418}
419
0ff21c1c 420function listForApi (start, count, sort, callback) {
feb4bdfd
C
421 const query = {
422 offset: start,
423 limit: count,
7920c273 424 distinct: true, // For the count, a video can have many tags
178edb20 425 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
feb4bdfd
C
426 include: [
427 {
428 model: this.sequelize.models.Author,
7920c273
C
429 include: [ { model: this.sequelize.models.Pod, required: false } ]
430 },
431
432 this.sequelize.models.Tag
feb4bdfd
C
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 })
aaf61f38
C
441}
442
3d118fb5 443function loadByHostAndRemoteId (fromHost, remoteId, callback) {
feb4bdfd
C
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,
7920c273 454 required: true,
feb4bdfd
C
455 where: {
456 host: fromHost
457 }
458 }
459 ]
460 }
461 ]
462 }
aaf61f38 463
3d118fb5 464 return this.findOne(query).asCallback(callback)
aaf61f38
C
465}
466
7920c273 467function listOwnedAndPopulateAuthorAndTags (callback) {
558d7c23 468 // If remoteId is null this is *our* video
feb4bdfd
C
469 const query = {
470 where: {
471 remoteId: null
472 },
7920c273 473 include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
feb4bdfd
C
474 }
475
476 return this.findAll(query).asCallback(callback)
aaf61f38
C
477}
478
9bd26629 479function listOwnedByAuthor (author, callback) {
feb4bdfd
C
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 }
9bd26629 493
feb4bdfd 494 return this.findAll(query).asCallback(callback)
aaf61f38
C
495}
496
497function load (id, callback) {
feb4bdfd
C
498 return this.findById(id).asCallback(callback)
499}
500
501function loadAndPopulateAuthor (id, callback) {
502 const options = {
503 include: [ this.sequelize.models.Author ]
504 }
505
506 return this.findById(id, options).asCallback(callback)
507}
508
7920c273 509function loadAndPopulateAuthorAndPodAndTags (id, callback) {
feb4bdfd
C
510 const options = {
511 include: [
512 {
513 model: this.sequelize.models.Author,
7920c273
C
514 include: [ { model: this.sequelize.models.Pod, required: false } ]
515 },
516 this.sequelize.models.Tag
feb4bdfd
C
517 ]
518 }
519
520 return this.findById(id, options).asCallback(callback)
aaf61f38
C
521}
522
7920c273 523function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
feb4bdfd 524 const podInclude = {
7920c273
C
525 model: this.sequelize.models.Pod,
526 required: false
feb4bdfd 527 }
7920c273 528
feb4bdfd
C
529 const authorInclude = {
530 model: this.sequelize.models.Author,
531 include: [
532 podInclude
533 ]
534 }
535
7920c273
C
536 const tagInclude = {
537 model: this.sequelize.models.Tag
538 }
539
feb4bdfd
C
540 const query = {
541 where: {},
feb4bdfd
C
542 offset: start,
543 limit: count,
7920c273 544 distinct: true, // For the count, a video can have many tags
178edb20 545 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
feb4bdfd
C
546 }
547
aaf61f38 548 // Make an exact search with the magnet
55723d16
C
549 if (field === 'magnetUri') {
550 const infoHash = magnetUtil.decode(value).infoHash
feb4bdfd 551 query.where.infoHash = infoHash
55723d16 552 } else if (field === 'tags') {
7920c273
C
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 )
feb4bdfd
C
559 }
560 }
7920c273
C
561 } else if (field === 'host') {
562 // FIXME: Include our pod? (not stored in the database)
563 podInclude.where = {
564 host: {
565 $like: '%' + value + '%'
feb4bdfd 566 }
feb4bdfd 567 }
7920c273 568 podInclude.required = true
feb4bdfd 569 } else if (field === 'author') {
7920c273
C
570 authorInclude.where = {
571 name: {
feb4bdfd
C
572 $like: '%' + value + '%'
573 }
574 }
7920c273
C
575
576 // authorInclude.or = true
aaf61f38 577 } else {
feb4bdfd
C
578 query.where[field] = {
579 $like: '%' + value + '%'
580 }
aaf61f38
C
581 }
582
7920c273
C
583 query.include = [
584 authorInclude, tagInclude
585 ]
586
587 if (tagInclude.where) {
588 // query.include.push([ this.sequelize.models.Tag ])
589 }
590
feb4bdfd
C
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 })
aaf61f38
C
596}
597
aaf61f38
C
598// ---------------------------------------------------------------------------
599
aaf61f38 600function removeThumbnail (video, callback) {
15103f11
C
601 const thumbnailPath = pathUtils.join(constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
602 fs.unlink(thumbnailPath, callback)
aaf61f38
C
603}
604
605function removeFile (video, callback) {
15103f11
C
606 const filePath = pathUtils.join(constants.CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
607 fs.unlink(filePath, callback)
aaf61f38
C
608}
609
aaf61f38 610function removeTorrent (video, callback) {
15103f11
C
611 const torrenPath = pathUtils.join(constants.CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
612 fs.unlink(torrenPath, callback)
aaf61f38
C
613}
614
6a94a109
C
615function removePreview (video, callback) {
616 // Same name than video thumnail
f285faa0 617 fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
6a94a109
C
618}
619
558d7c23 620function createPreview (video, videoPath, callback) {
f285faa0 621 generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
6a94a109
C
622}
623
558d7c23 624function createThumbnail (video, videoPath, callback) {
f285faa0 625 generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
aaf61f38
C
626}
627
f285faa0 628function generateImage (video, videoPath, folder, imageName, size, callback) {
558d7c23 629 const options = {
f285faa0 630 filename: imageName,
558d7c23
C
631 count: 1,
632 folder
633 }
aaf61f38 634
558d7c23
C
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 () {
f285faa0 644 callback(null, imageName)
aaf61f38 645 })
558d7c23 646 .thumbnail(options)
aaf61f38 647}