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