]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Add previews cache system between pods
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
CommitLineData
4d4e5cd4 1import * as safeBuffer from 'safe-buffer'
65fcc311 2const Buffer = safeBuffer.Buffer
4d4e5cd4 3import * as ffmpeg from 'fluent-ffmpeg'
4d4e5cd4 4import * as magnetUtil from 'magnet-uri'
65fcc311 5import { map, values } from 'lodash'
4d4e5cd4 6import * as parseTorrent from 'parse-torrent'
65fcc311 7import { join } from 'path'
e02643f3 8import * as Sequelize from 'sequelize'
6fcd19ba 9import * as Promise from 'bluebird'
65fcc311 10
74889a71 11import { database as db } from '../../initializers/database'
6fcd19ba 12import { TagInstance } from './tag-interface'
65fcc311
C
13import {
14 logger,
15 isVideoNameValid,
16 isVideoCategoryValid,
17 isVideoLicenceValid,
18 isVideoLanguageValid,
19 isVideoNSFWValid,
20 isVideoDescriptionValid,
21 isVideoInfoHashValid,
6fcd19ba
C
22 isVideoDurationValid,
23 readFileBufferPromise,
24 unlinkPromise,
25 renamePromise,
26 writeFilePromise,
27 createTorrentPromise
74889a71 28} from '../../helpers'
65fcc311
C
29import {
30 CONSTRAINTS_FIELDS,
31 CONFIG,
32 REMOTE_SCHEME,
33 STATIC_PATHS,
34 VIDEO_CATEGORIES,
35 VIDEO_LICENCES,
36 VIDEO_LANGUAGES,
37 THUMBNAILS_SIZE
74889a71
C
38} from '../../initializers'
39import { JobScheduler, removeVideoToFriends } from '../../lib'
aaf61f38 40
74889a71 41import { addMethodsToModel, getSort } from '../utils'
e02643f3 42import {
e02643f3
C
43 VideoInstance,
44 VideoAttributes,
45
46 VideoMethods
47} from './video-interface'
48
49let Video: Sequelize.Model<VideoInstance, VideoAttributes>
50let generateMagnetUri: VideoMethods.GenerateMagnetUri
51let getVideoFilename: VideoMethods.GetVideoFilename
52let getThumbnailName: VideoMethods.GetThumbnailName
53let getPreviewName: VideoMethods.GetPreviewName
54let getTorrentName: VideoMethods.GetTorrentName
55let isOwned: VideoMethods.IsOwned
56let toFormatedJSON: VideoMethods.ToFormatedJSON
57let toAddRemoteJSON: VideoMethods.ToAddRemoteJSON
58let toUpdateRemoteJSON: VideoMethods.ToUpdateRemoteJSON
59let transcodeVideofile: VideoMethods.TranscodeVideofile
60
61let generateThumbnailFromData: VideoMethods.GenerateThumbnailFromData
62let getDurationFromFile: VideoMethods.GetDurationFromFile
63let list: VideoMethods.List
64let listForApi: VideoMethods.ListForApi
0a6658fd 65let loadByHostAndUUID: VideoMethods.LoadByHostAndUUID
e02643f3
C
66let listOwnedAndPopulateAuthorAndTags: VideoMethods.ListOwnedAndPopulateAuthorAndTags
67let listOwnedByAuthor: VideoMethods.ListOwnedByAuthor
68let load: VideoMethods.Load
0a6658fd 69let loadByUUID: VideoMethods.LoadByUUID
e02643f3
C
70let loadAndPopulateAuthor: VideoMethods.LoadAndPopulateAuthor
71let loadAndPopulateAuthorAndPodAndTags: VideoMethods.LoadAndPopulateAuthorAndPodAndTags
0a6658fd 72let loadByUUIDAndPopulateAuthorAndPodAndTags: VideoMethods.LoadByUUIDAndPopulateAuthorAndPodAndTags
e02643f3
C
73let searchAndPopulateAuthorAndPodAndTags: VideoMethods.SearchAndPopulateAuthorAndPodAndTags
74
127944aa
C
75export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
76 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
feb4bdfd 77 {
0a6658fd 78 uuid: {
feb4bdfd
C
79 type: DataTypes.UUID,
80 defaultValue: DataTypes.UUIDV4,
0a6658fd 81 allowNull: false,
67bf9b96
C
82 validate: {
83 isUUID: 4
84 }
aaf61f38 85 },
feb4bdfd 86 name: {
67bf9b96
C
87 type: DataTypes.STRING,
88 allowNull: false,
89 validate: {
075f16ca 90 nameValid: value => {
65fcc311 91 const res = isVideoNameValid(value)
67bf9b96
C
92 if (res === false) throw new Error('Video name is not valid.')
93 }
94 }
6a94a109 95 },
feb4bdfd 96 extname: {
65fcc311 97 type: DataTypes.ENUM(values(CONSTRAINTS_FIELDS.VIDEOS.EXTNAME)),
67bf9b96 98 allowNull: false
feb4bdfd 99 },
6e07c3de
C
100 category: {
101 type: DataTypes.INTEGER,
102 allowNull: false,
103 validate: {
075f16ca 104 categoryValid: value => {
65fcc311 105 const res = isVideoCategoryValid(value)
6e07c3de
C
106 if (res === false) throw new Error('Video category is not valid.')
107 }
108 }
109 },
6f0c39e2
C
110 licence: {
111 type: DataTypes.INTEGER,
112 allowNull: false,
3092476e 113 defaultValue: null,
6f0c39e2 114 validate: {
075f16ca 115 licenceValid: value => {
65fcc311 116 const res = isVideoLicenceValid(value)
6f0c39e2
C
117 if (res === false) throw new Error('Video licence is not valid.')
118 }
119 }
120 },
3092476e
C
121 language: {
122 type: DataTypes.INTEGER,
123 allowNull: true,
124 validate: {
075f16ca 125 languageValid: value => {
65fcc311 126 const res = isVideoLanguageValid(value)
3092476e
C
127 if (res === false) throw new Error('Video language is not valid.')
128 }
129 }
130 },
31b59b47
C
131 nsfw: {
132 type: DataTypes.BOOLEAN,
133 allowNull: false,
134 validate: {
075f16ca 135 nsfwValid: value => {
65fcc311 136 const res = isVideoNSFWValid(value)
31b59b47
C
137 if (res === false) throw new Error('Video nsfw attribute is not valid.')
138 }
139 }
140 },
feb4bdfd 141 description: {
67bf9b96
C
142 type: DataTypes.STRING,
143 allowNull: false,
144 validate: {
075f16ca 145 descriptionValid: value => {
65fcc311 146 const res = isVideoDescriptionValid(value)
67bf9b96
C
147 if (res === false) throw new Error('Video description is not valid.')
148 }
149 }
feb4bdfd
C
150 },
151 infoHash: {
67bf9b96
C
152 type: DataTypes.STRING,
153 allowNull: false,
154 validate: {
075f16ca 155 infoHashValid: value => {
65fcc311 156 const res = isVideoInfoHashValid(value)
67bf9b96
C
157 if (res === false) throw new Error('Video info hash is not valid.')
158 }
159 }
feb4bdfd
C
160 },
161 duration: {
67bf9b96
C
162 type: DataTypes.INTEGER,
163 allowNull: false,
164 validate: {
075f16ca 165 durationValid: value => {
65fcc311 166 const res = isVideoDurationValid(value)
67bf9b96
C
167 if (res === false) throw new Error('Video duration is not valid.')
168 }
169 }
9e167724
C
170 },
171 views: {
172 type: DataTypes.INTEGER,
173 allowNull: false,
174 defaultValue: 0,
175 validate: {
176 min: 0,
177 isInt: true
178 }
d38b8281
C
179 },
180 likes: {
181 type: DataTypes.INTEGER,
182 allowNull: false,
183 defaultValue: 0,
184 validate: {
185 min: 0,
186 isInt: true
187 }
188 },
189 dislikes: {
190 type: DataTypes.INTEGER,
191 allowNull: false,
192 defaultValue: 0,
193 validate: {
194 min: 0,
195 isInt: true
196 }
0a6658fd
C
197 },
198 remote: {
199 type: DataTypes.BOOLEAN,
200 allowNull: false,
201 defaultValue: false
aaf61f38 202 }
feb4bdfd
C
203 },
204 {
319d072e
C
205 indexes: [
206 {
207 fields: [ 'authorId' ]
208 },
319d072e
C
209 {
210 fields: [ 'name' ]
211 },
212 {
213 fields: [ 'createdAt' ]
214 },
215 {
216 fields: [ 'duration' ]
217 },
218 {
219 fields: [ 'infoHash' ]
9e167724
C
220 },
221 {
222 fields: [ 'views' ]
d38b8281
C
223 },
224 {
225 fields: [ 'likes' ]
0a6658fd
C
226 },
227 {
228 fields: [ 'uuid' ]
319d072e
C
229 }
230 ],
feb4bdfd 231 hooks: {
67bf9b96 232 beforeValidate,
feb4bdfd
C
233 beforeCreate,
234 afterDestroy
235 }
236 }
237 )
aaf61f38 238
e02643f3
C
239 const classMethods = [
240 associate,
241
242 generateThumbnailFromData,
243 getDurationFromFile,
244 list,
245 listForApi,
246 listOwnedAndPopulateAuthorAndTags,
247 listOwnedByAuthor,
248 load,
0a6658fd
C
249 loadByUUID,
250 loadByHostAndUUID,
e02643f3
C
251 loadAndPopulateAuthor,
252 loadAndPopulateAuthorAndPodAndTags,
0a6658fd 253 loadByUUIDAndPopulateAuthorAndPodAndTags,
70c065d6
C
254 searchAndPopulateAuthorAndPodAndTags,
255 removeFromBlacklist
e02643f3
C
256 ]
257 const instanceMethods = [
258 generateMagnetUri,
259 getVideoFilename,
260 getThumbnailName,
261 getPreviewName,
262 getTorrentName,
263 isOwned,
264 toFormatedJSON,
265 toAddRemoteJSON,
266 toUpdateRemoteJSON,
6fcd19ba 267 transcodeVideofile
e02643f3
C
268 ]
269 addMethodsToModel(Video, classMethods, instanceMethods)
270
feb4bdfd
C
271 return Video
272}
aaf61f38 273
69818c93 274function beforeValidate (video: VideoInstance) {
7f4e7c36
C
275 // Put a fake infoHash if it does not exists yet
276 if (video.isOwned() && !video.infoHash) {
67bf9b96
C
277 // 40 hexa length
278 video.infoHash = '0123456789abcdef0123456789abcdef01234567'
279 }
67bf9b96 280}
feb4bdfd 281
69818c93 282function beforeCreate (video: VideoInstance, options: { transaction: Sequelize.Transaction }) {
6fcd19ba
C
283 if (video.isOwned()) {
284 const videoPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
e02643f3 285 const tasks = []
15103f11 286
6fcd19ba
C
287 tasks.push(
288 createTorrentFromVideo(video, videoPath),
289 createThumbnail(video, videoPath),
290 createPreview(video, videoPath)
291 )
c77fa067 292
6fcd19ba 293 if (CONFIG.TRANSCODING.ENABLED === true) {
0a6658fd 294 // Put uuid because we don't have id auto incremented for now
6fcd19ba 295 const dataInput = {
0a6658fd 296 videoUUID: video.uuid
e02643f3 297 }
aaf61f38 298
6fcd19ba
C
299 tasks.push(
300 JobScheduler.Instance.createJob(options.transaction, 'videoTranscoder', dataInput)
301 )
feb4bdfd 302 }
feb4bdfd 303
6fcd19ba
C
304 return Promise.all(tasks)
305 }
306
307 return Promise.resolve()
e02643f3
C
308}
309
69818c93 310function afterDestroy (video: VideoInstance) {
6fcd19ba 311 const tasks = []
98ac898a 312
6fcd19ba
C
313 tasks.push(
314 removeThumbnail(video)
315 )
feb4bdfd 316
6fcd19ba
C
317 if (video.isOwned()) {
318 const removeVideoToFriendsParams = {
0a6658fd 319 uuid: video.uuid
e02643f3
C
320 }
321
6fcd19ba
C
322 tasks.push(
323 removeFile(video),
324 removeTorrent(video),
325 removePreview(video),
326 removeVideoToFriends(removeVideoToFriendsParams)
327 )
328 }
e02643f3 329
6fcd19ba 330 return Promise.all(tasks)
feb4bdfd 331}
aaf61f38
C
332
333// ------------------------------ METHODS ------------------------------
334
feb4bdfd 335function associate (models) {
e02643f3 336 Video.belongsTo(models.Author, {
feb4bdfd
C
337 foreignKey: {
338 name: 'authorId',
339 allowNull: false
340 },
341 onDelete: 'cascade'
342 })
7920c273 343
e02643f3 344 Video.belongsToMany(models.Tag, {
7920c273
C
345 foreignKey: 'videoId',
346 through: models.VideoTag,
347 onDelete: 'cascade'
348 })
55fa55a9 349
e02643f3 350 Video.hasMany(models.VideoAbuse, {
55fa55a9
C
351 foreignKey: {
352 name: 'videoId',
353 allowNull: false
354 },
355 onDelete: 'cascade'
356 })
feb4bdfd
C
357}
358
70c065d6 359generateMagnetUri = function (this: VideoInstance) {
65fcc311
C
360 let baseUrlHttp
361 let baseUrlWs
f285faa0
C
362
363 if (this.isOwned()) {
65fcc311
C
364 baseUrlHttp = CONFIG.WEBSERVER.URL
365 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
f285faa0 366 } else {
65fcc311
C
367 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.Author.Pod.host
368 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.Author.Pod.host
f285faa0
C
369 }
370
65fcc311 371 const xs = baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentName()
69818c93 372 const announce = [ baseUrlWs + '/tracker/socket' ]
65fcc311 373 const urlList = [ baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename() ]
f285faa0
C
374
375 const magnetHash = {
376 xs,
377 announce,
378 urlList,
feb4bdfd 379 infoHash: this.infoHash,
f285faa0
C
380 name: this.name
381 }
382
383 return magnetUtil.encode(magnetHash)
558d7c23
C
384}
385
70c065d6 386getVideoFilename = function (this: VideoInstance) {
0a6658fd 387 return this.uuid + this.extname
f285faa0
C
388}
389
70c065d6 390getThumbnailName = function (this: VideoInstance) {
f285faa0 391 // We always have a copy of the thumbnail
0a6658fd
C
392 const extension = '.jpg'
393 return this.uuid + extension
558d7c23
C
394}
395
70c065d6 396getPreviewName = function (this: VideoInstance) {
f285faa0 397 const extension = '.jpg'
0a6658fd 398 return this.uuid + extension
f285faa0
C
399}
400
70c065d6 401getTorrentName = function (this: VideoInstance) {
f285faa0 402 const extension = '.torrent'
0a6658fd 403 return this.uuid + extension
558d7c23
C
404}
405
70c065d6 406isOwned = function (this: VideoInstance) {
0a6658fd 407 return this.remote === false
aaf61f38
C
408}
409
69f616ab 410toFormatedJSON = function (this: VideoInstance) {
feb4bdfd
C
411 let podHost
412
413 if (this.Author.Pod) {
414 podHost = this.Author.Pod.host
415 } else {
416 // It means it's our video
65fcc311 417 podHost = CONFIG.WEBSERVER.HOST
feb4bdfd
C
418 }
419
6e07c3de 420 // Maybe our pod is not up to date and there are new categories since our version
65fcc311 421 let categoryLabel = VIDEO_CATEGORIES[this.category]
6e07c3de
C
422 if (!categoryLabel) categoryLabel = 'Misc'
423
6f0c39e2 424 // Maybe our pod is not up to date and there are new licences since our version
65fcc311 425 let licenceLabel = VIDEO_LICENCES[this.licence]
6f0c39e2
C
426 if (!licenceLabel) licenceLabel = 'Unknown'
427
3092476e 428 // Language is an optional attribute
65fcc311 429 let languageLabel = VIDEO_LANGUAGES[this.language]
3092476e
C
430 if (!languageLabel) languageLabel = 'Unknown'
431
aaf61f38 432 const json = {
feb4bdfd 433 id: this.id,
0a6658fd 434 uuid: this.uuid,
aaf61f38 435 name: this.name,
6e07c3de
C
436 category: this.category,
437 categoryLabel,
6f0c39e2
C
438 licence: this.licence,
439 licenceLabel,
3092476e
C
440 language: this.language,
441 languageLabel,
31b59b47 442 nsfw: this.nsfw,
aaf61f38 443 description: this.description,
feb4bdfd 444 podHost,
aaf61f38 445 isLocal: this.isOwned(),
f285faa0 446 magnetUri: this.generateMagnetUri(),
feb4bdfd 447 author: this.Author.name,
aaf61f38 448 duration: this.duration,
9e167724 449 views: this.views,
d38b8281
C
450 likes: this.likes,
451 dislikes: this.dislikes,
6fcd19ba 452 tags: map<TagInstance, string>(this.Tags, 'name'),
65fcc311 453 thumbnailPath: join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName()),
f981dae8 454 previewPath: join(STATIC_PATHS.PREVIEWS, this.getPreviewName()),
79066fdf
C
455 createdAt: this.createdAt,
456 updatedAt: this.updatedAt
aaf61f38
C
457 }
458
459 return json
460}
461
6fcd19ba 462toAddRemoteJSON = function (this: VideoInstance) {
4d324488 463 // Get thumbnail data to send to the other pod
65fcc311 464 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
aaf61f38 465
6fcd19ba 466 return readFileBufferPromise(thumbnailPath).then(thumbnailData => {
aaf61f38 467 const remoteVideo = {
0a6658fd 468 uuid: this.uuid,
e02643f3
C
469 name: this.name,
470 category: this.category,
471 licence: this.licence,
472 language: this.language,
473 nsfw: this.nsfw,
474 description: this.description,
475 infoHash: this.infoHash,
e02643f3
C
476 author: this.Author.name,
477 duration: this.duration,
4d324488 478 thumbnailData: thumbnailData.toString('binary'),
6fcd19ba 479 tags: map<TagInstance, string>(this.Tags, 'name'),
e02643f3
C
480 createdAt: this.createdAt,
481 updatedAt: this.updatedAt,
482 extname: this.extname,
483 views: this.views,
484 likes: this.likes,
485 dislikes: this.dislikes
aaf61f38
C
486 }
487
6fcd19ba 488 return remoteVideo
aaf61f38
C
489 })
490}
491
70c065d6 492toUpdateRemoteJSON = function (this: VideoInstance) {
7b1f49de 493 const json = {
0a6658fd 494 uuid: this.uuid,
7b1f49de 495 name: this.name,
6e07c3de 496 category: this.category,
6f0c39e2 497 licence: this.licence,
3092476e 498 language: this.language,
31b59b47 499 nsfw: this.nsfw,
7b1f49de
C
500 description: this.description,
501 infoHash: this.infoHash,
7b1f49de
C
502 author: this.Author.name,
503 duration: this.duration,
6fcd19ba 504 tags: map<TagInstance, string>(this.Tags, 'name'),
7b1f49de 505 createdAt: this.createdAt,
79066fdf 506 updatedAt: this.updatedAt,
e3d156b3 507 extname: this.extname,
d38b8281
C
508 views: this.views,
509 likes: this.likes,
510 dislikes: this.dislikes
7b1f49de
C
511 }
512
513 return json
514}
515
6fcd19ba 516transcodeVideofile = function (this: VideoInstance) {
227d02fe
C
517 const video = this
518
65fcc311 519 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
227d02fe 520 const newExtname = '.mp4'
65fcc311
C
521 const videoInputPath = join(videosDirectory, video.getVideoFilename())
522 const videoOutputPath = join(videosDirectory, video.id + '-transcoded' + newExtname)
227d02fe 523
6fcd19ba
C
524 return new Promise<void>((res, rej) => {
525 ffmpeg(videoInputPath)
526 .output(videoOutputPath)
527 .videoCodec('libx264')
528 .outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
529 .outputOption('-movflags faststart')
530 .on('error', rej)
531 .on('end', () => {
532
533 return unlinkPromise(videoInputPath)
534 .then(() => {
535 // Important to do this before getVideoFilename() to take in account the new file extension
536 video.set('extname', newExtname)
537
538 const newVideoPath = join(videosDirectory, video.getVideoFilename())
539 return renamePromise(videoOutputPath, newVideoPath)
227d02fe 540 })
6fcd19ba
C
541 .then(() => {
542 const newVideoPath = join(videosDirectory, video.getVideoFilename())
543 return createTorrentFromVideo(video, newVideoPath)
544 })
545 .then(() => {
546 return video.save()
547 })
548 .then(() => {
549 return res()
550 })
551 .catch(err => {
552 // Autodesctruction...
075f16ca 553 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
227d02fe 554
6fcd19ba
C
555 return rej(err)
556 })
227d02fe 557 })
6fcd19ba
C
558 .run()
559 })
227d02fe
C
560}
561
aaf61f38
C
562// ------------------------------ STATICS ------------------------------
563
6fcd19ba 564generateThumbnailFromData = function (video: VideoInstance, thumbnailData: string) {
c77fa067
C
565 // Creating the thumbnail for a remote video
566
567 const thumbnailName = video.getThumbnailName()
65fcc311 568 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
6fcd19ba
C
569 return writeFilePromise(thumbnailPath, Buffer.from(thumbnailData, 'binary')).then(() => {
570 return thumbnailName
c77fa067
C
571 })
572}
573
6fcd19ba
C
574getDurationFromFile = function (videoPath: string) {
575 return new Promise<number>((res, rej) => {
075f16ca 576 ffmpeg.ffprobe(videoPath, (err, metadata) => {
6fcd19ba 577 if (err) return rej(err)
aaf61f38 578
6fcd19ba
C
579 return res(Math.floor(metadata.format.duration))
580 })
aaf61f38
C
581 })
582}
583
6fcd19ba
C
584list = function () {
585 return Video.findAll()
b769007f
C
586}
587
6fcd19ba 588listForApi = function (start: number, count: number, sort: string) {
198b205c 589 // Exclude Blakclisted videos from the list
feb4bdfd 590 const query = {
e02643f3 591 distinct: true,
feb4bdfd
C
592 offset: start,
593 limit: count,
e02643f3 594 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
feb4bdfd
C
595 include: [
596 {
e02643f3
C
597 model: Video['sequelize'].models.Author,
598 include: [ { model: Video['sequelize'].models.Pod, required: false } ]
7920c273
C
599 },
600
e02643f3 601 Video['sequelize'].models.Tag
198b205c 602 ],
e02643f3 603 where: createBaseVideosWhere()
feb4bdfd
C
604 }
605
6fcd19ba
C
606 return Video.findAndCountAll(query).then(({ rows, count }) => {
607 return {
608 data: rows,
609 total: count
610 }
feb4bdfd 611 })
aaf61f38
C
612}
613
0a6658fd 614loadByHostAndUUID = function (fromHost: string, uuid: string) {
feb4bdfd
C
615 const query = {
616 where: {
0a6658fd 617 uuid
feb4bdfd
C
618 },
619 include: [
620 {
e02643f3 621 model: Video['sequelize'].models.Author,
feb4bdfd
C
622 include: [
623 {
e02643f3 624 model: Video['sequelize'].models.Pod,
7920c273 625 required: true,
feb4bdfd
C
626 where: {
627 host: fromHost
628 }
629 }
630 ]
631 }
632 ]
633 }
aaf61f38 634
6fcd19ba 635 return Video.findOne(query)
aaf61f38
C
636}
637
6fcd19ba 638listOwnedAndPopulateAuthorAndTags = function () {
feb4bdfd
C
639 const query = {
640 where: {
0a6658fd 641 remote: false
feb4bdfd 642 },
e02643f3 643 include: [ Video['sequelize'].models.Author, Video['sequelize'].models.Tag ]
feb4bdfd
C
644 }
645
6fcd19ba 646 return Video.findAll(query)
aaf61f38
C
647}
648
6fcd19ba 649listOwnedByAuthor = function (author: string) {
feb4bdfd
C
650 const query = {
651 where: {
0a6658fd 652 remote: false
feb4bdfd
C
653 },
654 include: [
655 {
e02643f3 656 model: Video['sequelize'].models.Author,
feb4bdfd
C
657 where: {
658 name: author
659 }
660 }
661 ]
662 }
9bd26629 663
6fcd19ba 664 return Video.findAll(query)
aaf61f38
C
665}
666
0a6658fd 667load = function (id: number) {
6fcd19ba 668 return Video.findById(id)
feb4bdfd
C
669}
670
0a6658fd
C
671loadByUUID = function (uuid: string) {
672 const query = {
673 where: {
674 uuid
675 }
676 }
677 return Video.findOne(query)
678}
679
680loadAndPopulateAuthor = function (id: number) {
feb4bdfd 681 const options = {
e02643f3 682 include: [ Video['sequelize'].models.Author ]
feb4bdfd
C
683 }
684
6fcd19ba 685 return Video.findById(id, options)
feb4bdfd
C
686}
687
0a6658fd 688loadAndPopulateAuthorAndPodAndTags = function (id: number) {
feb4bdfd
C
689 const options = {
690 include: [
691 {
e02643f3
C
692 model: Video['sequelize'].models.Author,
693 include: [ { model: Video['sequelize'].models.Pod, required: false } ]
7920c273 694 },
e02643f3 695 Video['sequelize'].models.Tag
feb4bdfd
C
696 ]
697 }
698
6fcd19ba 699 return Video.findById(id, options)
aaf61f38
C
700}
701
0a6658fd
C
702loadByUUIDAndPopulateAuthorAndPodAndTags = function (uuid: string) {
703 const options = {
704 where: {
705 uuid
706 },
707 include: [
708 {
709 model: Video['sequelize'].models.Author,
710 include: [ { model: Video['sequelize'].models.Pod, required: false } ]
711 },
712 Video['sequelize'].models.Tag
713 ]
714 }
715
716 return Video.findOne(options)
717}
718
6fcd19ba 719searchAndPopulateAuthorAndPodAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
e6d4b0ff 720 const podInclude: Sequelize.IncludeOptions = {
e02643f3 721 model: Video['sequelize'].models.Pod,
7920c273 722 required: false
feb4bdfd 723 }
7920c273 724
e6d4b0ff 725 const authorInclude: Sequelize.IncludeOptions = {
e02643f3 726 model: Video['sequelize'].models.Author,
feb4bdfd
C
727 include: [
728 podInclude
729 ]
730 }
731
e6d4b0ff 732 const tagInclude: Sequelize.IncludeOptions = {
e02643f3 733 model: Video['sequelize'].models.Tag
7920c273
C
734 }
735
e6d4b0ff 736 const query: Sequelize.FindOptions = {
e02643f3
C
737 distinct: true,
738 where: createBaseVideosWhere(),
feb4bdfd
C
739 offset: start,
740 limit: count,
e02643f3 741 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
feb4bdfd
C
742 }
743
aaf61f38 744 // Make an exact search with the magnet
55723d16
C
745 if (field === 'magnetUri') {
746 const infoHash = magnetUtil.decode(value).infoHash
e6d4b0ff 747 query.where['infoHash'] = infoHash
55723d16 748 } else if (field === 'tags') {
e02643f3 749 const escapedValue = Video['sequelize'].escape('%' + value + '%')
e6d4b0ff 750 query.where['id'].$in = Video['sequelize'].literal(
6fcd19ba
C
751 `(SELECT "VideoTags"."videoId"
752 FROM "Tags"
753 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
18c8e945 754 WHERE name ILIKE ${escapedValue}
6fcd19ba 755 )`
198b205c 756 )
7920c273
C
757 } else if (field === 'host') {
758 // FIXME: Include our pod? (not stored in the database)
759 podInclude.where = {
760 host: {
18c8e945 761 $iLike: '%' + value + '%'
feb4bdfd 762 }
feb4bdfd 763 }
7920c273 764 podInclude.required = true
feb4bdfd 765 } else if (field === 'author') {
7920c273
C
766 authorInclude.where = {
767 name: {
18c8e945 768 $iLike: '%' + value + '%'
feb4bdfd
C
769 }
770 }
7920c273
C
771
772 // authorInclude.or = true
aaf61f38 773 } else {
feb4bdfd 774 query.where[field] = {
18c8e945 775 $iLike: '%' + value + '%'
feb4bdfd 776 }
aaf61f38
C
777 }
778
7920c273
C
779 query.include = [
780 authorInclude, tagInclude
781 ]
782
6fcd19ba
C
783 return Video.findAndCountAll(query).then(({ rows, count }) => {
784 return {
785 data: rows,
786 total: count
787 }
feb4bdfd 788 })
aaf61f38
C
789}
790
aaf61f38
C
791// ---------------------------------------------------------------------------
792
15d4ee04
C
793function createBaseVideosWhere () {
794 return {
795 id: {
e02643f3 796 $notIn: Video['sequelize'].literal(
15d4ee04
C
797 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
798 )
799 }
800 }
801}
802
6fcd19ba 803function removeThumbnail (video: VideoInstance) {
65fcc311 804 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
6fcd19ba 805 return unlinkPromise(thumbnailPath)
aaf61f38
C
806}
807
6fcd19ba 808function removeFile (video: VideoInstance) {
65fcc311 809 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename())
6fcd19ba 810 return unlinkPromise(filePath)
aaf61f38
C
811}
812
6fcd19ba 813function removeTorrent (video: VideoInstance) {
65fcc311 814 const torrenPath = join(CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
6fcd19ba 815 return unlinkPromise(torrenPath)
aaf61f38
C
816}
817
6fcd19ba 818function removePreview (video: VideoInstance) {
6a94a109 819 // Same name than video thumnail
6fcd19ba 820 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + video.getPreviewName())
6a94a109
C
821}
822
6fcd19ba 823function createTorrentFromVideo (video: VideoInstance, videoPath: string) {
227d02fe
C
824 const options = {
825 announceList: [
65fcc311 826 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
227d02fe
C
827 ],
828 urlList: [
65fcc311 829 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + video.getVideoFilename()
227d02fe
C
830 ]
831 }
832
6fcd19ba
C
833 return createTorrentPromise(videoPath, options)
834 .then(torrent => {
835 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, video.getTorrentName())
836 return writeFilePromise(filePath, torrent).then(() => torrent)
837 })
838 .then(torrent => {
227d02fe
C
839 const parsedTorrent = parseTorrent(torrent)
840 video.set('infoHash', parsedTorrent.infoHash)
6fcd19ba 841 return video.validate()
227d02fe 842 })
227d02fe
C
843}
844
6fcd19ba
C
845function createPreview (video: VideoInstance, videoPath: string) {
846 return generateImage(video, videoPath, CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName(), null)
6a94a109
C
847}
848
6fcd19ba
C
849function createThumbnail (video: VideoInstance, videoPath: string) {
850 return generateImage(video, videoPath, CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName(), THUMBNAILS_SIZE)
aaf61f38
C
851}
852
6fcd19ba 853function generateImage (video: VideoInstance, videoPath: string, folder: string, imageName: string, size: string) {
e6d4b0ff 854 const options = {
f285faa0 855 filename: imageName,
558d7c23
C
856 count: 1,
857 folder
858 }
aaf61f38 859
69818c93 860 if (size) {
e6d4b0ff 861 options['size'] = size
558d7c23
C
862 }
863
6fcd19ba
C
864 return new Promise<string>((res, rej) => {
865 ffmpeg(videoPath)
866 .on('error', rej)
075f16ca 867 .on('end', () => res(imageName))
6fcd19ba
C
868 .thumbnail(options)
869 })
aaf61f38 870}
198b205c 871
6fcd19ba 872function removeFromBlacklist (video: VideoInstance) {
198b205c 873 // Find the blacklisted video
6fcd19ba
C
874 return db.BlacklistedVideo.loadByVideoId(video.id).then(video => {
875 // Not found the video, skip
876 if (!video) {
877 return null
198b205c
GS
878 }
879
880 // If we found the video, remove it from the blacklist
6fcd19ba 881 return video.destroy()
198b205c
GS
882 })
883}