]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video.js
Server: move remote routes in their own directory
[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 = {
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(),
79066fdf
C
331 createdAt: this.createdAt,
332 updatedAt: this.updatedAt
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,
79066fdf 359 updatedAt: self.updatedAt,
8f217302 360 extname: self.extname
aaf61f38
C
361 }
362
363 return callback(null, remoteVideo)
364 })
365}
366
7b1f49de
C
367function toUpdateRemoteJSON (callback) {
368 const json = {
369 name: this.name,
370 description: this.description,
371 infoHash: this.infoHash,
372 remoteId: this.id,
373 author: this.Author.name,
374 duration: this.duration,
375 tags: map(this.Tags, 'name'),
376 createdAt: this.createdAt,
79066fdf 377 updatedAt: this.updatedAt,
7b1f49de
C
378 extname: this.extname
379 }
380
381 return json
382}
383
aaf61f38
C
384// ------------------------------ STATICS ------------------------------
385
4d324488 386function generateThumbnailFromData (video, thumbnailData, callback) {
c77fa067
C
387 // Creating the thumbnail for a remote video
388
389 const thumbnailName = video.getThumbnailName()
390 const thumbnailPath = constants.CONFIG.STORAGE.THUMBNAILS_DIR + thumbnailName
4d324488 391 fs.writeFile(thumbnailPath, Buffer.from(thumbnailData, 'binary'), function (err) {
c77fa067
C
392 if (err) return callback(err)
393
394 return callback(null, thumbnailName)
395 })
396}
397
aaf61f38
C
398function getDurationFromFile (videoPath, callback) {
399 ffmpeg.ffprobe(videoPath, function (err, metadata) {
400 if (err) return callback(err)
401
402 return callback(null, Math.floor(metadata.format.duration))
403 })
404}
405
b769007f
C
406function list (callback) {
407 return this.find().asCallback()
408}
409
0ff21c1c 410function listForApi (start, count, sort, callback) {
feb4bdfd
C
411 const query = {
412 offset: start,
413 limit: count,
7920c273 414 distinct: true, // For the count, a video can have many tags
178edb20 415 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ],
feb4bdfd
C
416 include: [
417 {
418 model: this.sequelize.models.Author,
7920c273
C
419 include: [ { model: this.sequelize.models.Pod, required: false } ]
420 },
421
422 this.sequelize.models.Tag
feb4bdfd
C
423 ]
424 }
425
426 return this.findAndCountAll(query).asCallback(function (err, result) {
427 if (err) return callback(err)
428
429 return callback(null, result.rows, result.count)
430 })
aaf61f38
C
431}
432
3d118fb5 433function loadByHostAndRemoteId (fromHost, remoteId, callback) {
feb4bdfd
C
434 const query = {
435 where: {
436 remoteId: remoteId
437 },
438 include: [
439 {
440 model: this.sequelize.models.Author,
441 include: [
442 {
443 model: this.sequelize.models.Pod,
7920c273 444 required: true,
feb4bdfd
C
445 where: {
446 host: fromHost
447 }
448 }
449 ]
450 }
451 ]
452 }
aaf61f38 453
3d118fb5 454 return this.findOne(query).asCallback(callback)
aaf61f38
C
455}
456
7920c273 457function listOwnedAndPopulateAuthorAndTags (callback) {
558d7c23 458 // If remoteId is null this is *our* video
feb4bdfd
C
459 const query = {
460 where: {
461 remoteId: null
462 },
7920c273 463 include: [ this.sequelize.models.Author, this.sequelize.models.Tag ]
feb4bdfd
C
464 }
465
466 return this.findAll(query).asCallback(callback)
aaf61f38
C
467}
468
9bd26629 469function listOwnedByAuthor (author, callback) {
feb4bdfd
C
470 const query = {
471 where: {
472 remoteId: null
473 },
474 include: [
475 {
476 model: this.sequelize.models.Author,
477 where: {
478 name: author
479 }
480 }
481 ]
482 }
9bd26629 483
feb4bdfd 484 return this.findAll(query).asCallback(callback)
aaf61f38
C
485}
486
487function load (id, callback) {
feb4bdfd
C
488 return this.findById(id).asCallback(callback)
489}
490
491function loadAndPopulateAuthor (id, callback) {
492 const options = {
493 include: [ this.sequelize.models.Author ]
494 }
495
496 return this.findById(id, options).asCallback(callback)
497}
498
7920c273 499function loadAndPopulateAuthorAndPodAndTags (id, callback) {
feb4bdfd
C
500 const options = {
501 include: [
502 {
503 model: this.sequelize.models.Author,
7920c273
C
504 include: [ { model: this.sequelize.models.Pod, required: false } ]
505 },
506 this.sequelize.models.Tag
feb4bdfd
C
507 ]
508 }
509
510 return this.findById(id, options).asCallback(callback)
aaf61f38
C
511}
512
7920c273 513function searchAndPopulateAuthorAndPodAndTags (value, field, start, count, sort, callback) {
feb4bdfd 514 const podInclude = {
7920c273
C
515 model: this.sequelize.models.Pod,
516 required: false
feb4bdfd 517 }
7920c273 518
feb4bdfd
C
519 const authorInclude = {
520 model: this.sequelize.models.Author,
521 include: [
522 podInclude
523 ]
524 }
525
7920c273
C
526 const tagInclude = {
527 model: this.sequelize.models.Tag
528 }
529
feb4bdfd
C
530 const query = {
531 where: {},
feb4bdfd
C
532 offset: start,
533 limit: count,
7920c273 534 distinct: true, // For the count, a video can have many tags
178edb20 535 order: [ modelUtils.getSort(sort), [ this.sequelize.models.Tag, 'name', 'ASC' ] ]
feb4bdfd
C
536 }
537
aaf61f38 538 // Make an exact search with the magnet
55723d16
C
539 if (field === 'magnetUri') {
540 const infoHash = magnetUtil.decode(value).infoHash
feb4bdfd 541 query.where.infoHash = infoHash
55723d16 542 } else if (field === 'tags') {
7920c273
C
543 const escapedValue = this.sequelize.escape('%' + value + '%')
544 query.where = {
545 id: {
546 $in: this.sequelize.literal(
547 '(SELECT "VideoTags"."videoId" FROM "Tags" INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" WHERE name LIKE ' + escapedValue + ')'
548 )
feb4bdfd
C
549 }
550 }
7920c273
C
551 } else if (field === 'host') {
552 // FIXME: Include our pod? (not stored in the database)
553 podInclude.where = {
554 host: {
555 $like: '%' + value + '%'
feb4bdfd 556 }
feb4bdfd 557 }
7920c273 558 podInclude.required = true
feb4bdfd 559 } else if (field === 'author') {
7920c273
C
560 authorInclude.where = {
561 name: {
feb4bdfd
C
562 $like: '%' + value + '%'
563 }
564 }
7920c273
C
565
566 // authorInclude.or = true
aaf61f38 567 } else {
feb4bdfd
C
568 query.where[field] = {
569 $like: '%' + value + '%'
570 }
aaf61f38
C
571 }
572
7920c273
C
573 query.include = [
574 authorInclude, tagInclude
575 ]
576
577 if (tagInclude.where) {
578 // query.include.push([ this.sequelize.models.Tag ])
579 }
580
feb4bdfd
C
581 return this.findAndCountAll(query).asCallback(function (err, result) {
582 if (err) return callback(err)
583
584 return callback(null, result.rows, result.count)
585 })
aaf61f38
C
586}
587
aaf61f38
C
588// ---------------------------------------------------------------------------
589
aaf61f38 590function removeThumbnail (video, callback) {
f285faa0 591 fs.unlink(constants.CONFIG.STORAGE.THUMBNAILS_DIR + video.getThumbnailName(), callback)
aaf61f38
C
592}
593
594function removeFile (video, callback) {
f285faa0 595 fs.unlink(constants.CONFIG.STORAGE.VIDEOS_DIR + video.getVideoFilename(), callback)
aaf61f38
C
596}
597
aaf61f38 598function removeTorrent (video, callback) {
558d7c23 599 fs.unlink(constants.CONFIG.STORAGE.TORRENTS_DIR + video.getTorrentName(), callback)
aaf61f38
C
600}
601
6a94a109
C
602function removePreview (video, callback) {
603 // Same name than video thumnail
f285faa0 604 fs.unlink(constants.CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName(), callback)
6a94a109
C
605}
606
558d7c23 607function createPreview (video, videoPath, callback) {
f285faa0 608 generateImage(video, videoPath, constants.CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), callback)
6a94a109
C
609}
610
558d7c23 611function createThumbnail (video, videoPath, callback) {
f285faa0 612 generateImage(video, videoPath, constants.CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), constants.THUMBNAILS_SIZE, callback)
aaf61f38
C
613}
614
f285faa0 615function generateImage (video, videoPath, folder, imageName, size, callback) {
558d7c23 616 const options = {
f285faa0 617 filename: imageName,
558d7c23
C
618 count: 1,
619 folder
620 }
aaf61f38 621
558d7c23
C
622 if (!callback) {
623 callback = size
624 } else {
625 options.size = size
626 }
627
628 ffmpeg(videoPath)
629 .on('error', callback)
630 .on('end', function () {
f285faa0 631 callback(null, imageName)
aaf61f38 632 })
558d7c23 633 .thumbnail(options)
aaf61f38 634}