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