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