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