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