]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Fix announces when fetching the actor outbox
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
CommitLineData
39445ead 1import * as Bluebird from 'bluebird'
53abc4c2 2import { map, maxBy, truncate } from 'lodash'
571389d4 3import * as magnetUtil from 'magnet-uri'
4d4e5cd4 4import * as parseTorrent from 'parse-torrent'
65fcc311 5import { join } from 'path'
e02643f3 6import * as Sequelize from 'sequelize'
3fd3ab2d 7import {
4ba3b8ea
C
8 AfterDestroy,
9 AllowNull,
10 BeforeDestroy,
11 BelongsTo,
12 BelongsToMany,
13 Column,
14 CreatedAt,
15 DataType,
16 Default,
17 ForeignKey,
18 HasMany,
19 IFindOptions,
20 Is,
21 IsInt,
22 IsUUID,
23 Min,
24 Model,
25 Scopes,
26 Table,
27 UpdatedAt
3fd3ab2d 28} from 'sequelize-typescript'
571389d4 29import { VideoPrivacy, VideoResolution } from '../../../shared'
3fd3ab2d 30import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
d48ff09d 31import { Video, VideoDetails } from '../../../shared/models/videos'
da854ddd
C
32import { activityPubCollection } from '../../helpers/activitypub'
33import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
34import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
47564bbe 35import { isBooleanValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 36import {
4ba3b8ea
C
37 isVideoCategoryValid,
38 isVideoDescriptionValid,
39 isVideoDurationValid,
40 isVideoLanguageValid,
41 isVideoLicenceValid,
42 isVideoNameValid,
47564bbe 43 isVideoPrivacyValid
3fd3ab2d 44} from '../../helpers/custom-validators/videos'
da854ddd
C
45import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
46import { logger } from '../../helpers/logger'
f05a1c30 47import { getServerActor } from '../../helpers/utils'
65fcc311 48import {
4ba3b8ea
C
49 API_VERSION,
50 CONFIG,
51 CONSTRAINTS_FIELDS,
52 PREVIEWS_SIZE,
53 REMOTE_SCHEME,
54 STATIC_PATHS,
55 THUMBNAILS_SIZE,
56 VIDEO_CATEGORIES,
57 VIDEO_LANGUAGES,
58 VIDEO_LICENCES,
59 VIDEO_PRIVACIES
3fd3ab2d 60} from '../../initializers'
46531a0a
C
61import {
62 getVideoCommentsActivityPubUrl,
63 getVideoDislikesActivityPubUrl,
64 getVideoLikesActivityPubUrl,
65 getVideoSharesActivityPubUrl
66} from '../../lib/activitypub'
50d6de9c 67import { sendDeleteVideo } from '../../lib/activitypub/send'
3fd3ab2d
C
68import { AccountModel } from '../account/account'
69import { AccountVideoRateModel } from '../account/account-video-rate'
50d6de9c 70import { ActorModel } from '../activitypub/actor'
3fd3ab2d
C
71import { ServerModel } from '../server/server'
72import { getSort, throwIfNotValid } from '../utils'
73import { TagModel } from './tag'
74import { VideoAbuseModel } from './video-abuse'
75import { VideoChannelModel } from './video-channel'
da854ddd 76import { VideoCommentModel } from './video-comment'
3fd3ab2d
C
77import { VideoFileModel } from './video-file'
78import { VideoShareModel } from './video-share'
79import { VideoTagModel } from './video-tag'
80
d48ff09d 81enum ScopeNames {
50d6de9c 82 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
4cb6d457 83 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d
C
84 WITH_TAGS = 'WITH_TAGS',
85 WITH_FILES = 'WITH_FILES',
86 WITH_SHARES = 'WITH_SHARES',
da854ddd
C
87 WITH_RATES = 'WITH_RATES',
88 WITH_COMMENTS = 'WITH_COMMENTS'
d48ff09d
C
89}
90
91@Scopes({
f05a1c30 92 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number) => ({
d48ff09d
C
93 where: {
94 id: {
95 [Sequelize.Op.notIn]: Sequelize.literal(
96 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
2d9ab590
C
97 ),
98 [ Sequelize.Op.in ]: Sequelize.literal(
99 '(' +
100 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
101 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
102 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
103 ' UNION ' +
104 'SELECT "video"."id" AS "id" FROM "video" ' +
105 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
106 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
107 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
108 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
109 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
110 ')'
d48ff09d 111 )
50d6de9c 112 },
2d9ab590 113 privacy: VideoPrivacy.PUBLIC
f05a1c30 114 },
4cb6d457
C
115 include: [
116 {
f05a1c30
C
117 attributes: [ 'name', 'description' ],
118 model: VideoChannelModel.unscoped(),
4cb6d457
C
119 required: true,
120 include: [
121 {
122 attributes: [ 'name' ],
f05a1c30 123 model: AccountModel.unscoped(),
4cb6d457
C
124 required: true,
125 include: [
126 {
127 attributes: [ 'serverId' ],
f05a1c30 128 model: ActorModel.unscoped(),
4cb6d457
C
129 required: true,
130 include: [
131 {
f05a1c30 132 attributes: [ 'host' ],
2d9ab590 133 model: ServerModel.unscoped()
4cb6d457
C
134 }
135 ]
136 }
137 ]
138 }
139 ]
140 }
141 ]
f05a1c30 142 }),
4cb6d457 143 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
d48ff09d
C
144 include: [
145 {
6120941f 146 model: () => VideoChannelModel.unscoped(),
d48ff09d
C
147 required: true,
148 include: [
6120941f
C
149 {
150 attributes: {
151 exclude: [ 'privateKey', 'publicKey' ]
152 },
3e500247
C
153 model: () => ActorModel.unscoped(),
154 required: true,
155 include: [
156 {
157 attributes: [ 'host' ],
158 model: () => ServerModel.unscoped(),
159 required: false
160 }
161 ]
6120941f 162 },
d48ff09d 163 {
3e500247 164 model: () => AccountModel.unscoped(),
d48ff09d
C
165 required: true,
166 include: [
167 {
3e500247 168 model: () => ActorModel.unscoped(),
6120941f
C
169 attributes: {
170 exclude: [ 'privateKey', 'publicKey' ]
171 },
50d6de9c
C
172 required: true,
173 include: [
174 {
3e500247
C
175 attributes: [ 'host' ],
176 model: () => ServerModel.unscoped(),
50d6de9c
C
177 required: false
178 }
179 ]
d48ff09d
C
180 }
181 ]
182 }
183 ]
184 }
185 ]
186 },
187 [ScopeNames.WITH_TAGS]: {
188 include: [ () => TagModel ]
189 },
190 [ScopeNames.WITH_FILES]: {
191 include: [
192 {
193 model: () => VideoFileModel,
194 required: true
195 }
196 ]
197 },
198 [ScopeNames.WITH_SHARES]: {
199 include: [
200 {
201 model: () => VideoShareModel,
50d6de9c 202 include: [ () => ActorModel ]
d48ff09d
C
203 }
204 ]
205 },
206 [ScopeNames.WITH_RATES]: {
207 include: [
208 {
209 model: () => AccountVideoRateModel,
210 include: [ () => AccountModel ]
211 }
212 ]
da854ddd
C
213 },
214 [ScopeNames.WITH_COMMENTS]: {
215 include: [
216 {
217 model: () => VideoCommentModel
218 }
219 ]
d48ff09d
C
220 }
221})
3fd3ab2d
C
222@Table({
223 tableName: 'video',
224 indexes: [
feb4bdfd 225 {
3fd3ab2d 226 fields: [ 'name' ]
feb4bdfd
C
227 },
228 {
3fd3ab2d
C
229 fields: [ 'createdAt' ]
230 },
231 {
232 fields: [ 'duration' ]
233 },
234 {
235 fields: [ 'views' ]
236 },
237 {
238 fields: [ 'likes' ]
239 },
240 {
241 fields: [ 'uuid' ]
242 },
243 {
244 fields: [ 'channelId' ]
4cb6d457
C
245 },
246 {
247 fields: [ 'id', 'privacy' ]
2ccaeeb3
C
248 },
249 {
250 fields: [ 'url'],
251 unique: true
feb4bdfd 252 }
e02643f3 253 ]
3fd3ab2d
C
254})
255export class VideoModel extends Model<VideoModel> {
256
257 @AllowNull(false)
258 @Default(DataType.UUIDV4)
259 @IsUUID(4)
260 @Column(DataType.UUID)
261 uuid: string
262
263 @AllowNull(false)
264 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
265 @Column
266 name: string
267
268 @AllowNull(true)
269 @Default(null)
270 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
271 @Column
272 category: number
273
274 @AllowNull(true)
275 @Default(null)
276 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
277 @Column
278 licence: number
279
280 @AllowNull(true)
281 @Default(null)
282 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
283 @Column
284 language: number
285
286 @AllowNull(false)
287 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
288 @Column
289 privacy: number
290
291 @AllowNull(false)
47564bbe 292 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
293 @Column
294 nsfw: boolean
295
296 @AllowNull(true)
297 @Default(null)
298 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
299 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
300 description: string
301
302 @AllowNull(false)
303 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
304 @Column
305 duration: number
306
307 @AllowNull(false)
308 @Default(0)
309 @IsInt
310 @Min(0)
311 @Column
312 views: number
313
314 @AllowNull(false)
315 @Default(0)
316 @IsInt
317 @Min(0)
318 @Column
319 likes: number
320
321 @AllowNull(false)
322 @Default(0)
323 @IsInt
324 @Min(0)
325 @Column
326 dislikes: number
327
328 @AllowNull(false)
329 @Column
330 remote: boolean
331
332 @AllowNull(false)
333 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
334 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
335 url: string
336
47564bbe
C
337 @AllowNull(false)
338 @Column
339 commentsEnabled: boolean
340
3fd3ab2d
C
341 @CreatedAt
342 createdAt: Date
343
344 @UpdatedAt
345 updatedAt: Date
346
347 @ForeignKey(() => VideoChannelModel)
348 @Column
349 channelId: number
350
351 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 352 foreignKey: {
50d6de9c 353 allowNull: true
feb4bdfd
C
354 },
355 onDelete: 'cascade'
356 })
3fd3ab2d 357 VideoChannel: VideoChannelModel
7920c273 358
3fd3ab2d 359 @BelongsToMany(() => TagModel, {
7920c273 360 foreignKey: 'videoId',
3fd3ab2d
C
361 through: () => VideoTagModel,
362 onDelete: 'CASCADE'
7920c273 363 })
3fd3ab2d 364 Tags: TagModel[]
55fa55a9 365
3fd3ab2d 366 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
367 foreignKey: {
368 name: 'videoId',
369 allowNull: false
370 },
371 onDelete: 'cascade'
372 })
3fd3ab2d 373 VideoAbuses: VideoAbuseModel[]
93e1258c 374
3fd3ab2d 375 @HasMany(() => VideoFileModel, {
93e1258c
C
376 foreignKey: {
377 name: 'videoId',
378 allowNull: false
379 },
380 onDelete: 'cascade'
381 })
3fd3ab2d 382 VideoFiles: VideoFileModel[]
e71bcc0f 383
3fd3ab2d 384 @HasMany(() => VideoShareModel, {
e71bcc0f
C
385 foreignKey: {
386 name: 'videoId',
387 allowNull: false
388 },
389 onDelete: 'cascade'
390 })
3fd3ab2d 391 VideoShares: VideoShareModel[]
16b90975 392
3fd3ab2d 393 @HasMany(() => AccountVideoRateModel, {
16b90975
C
394 foreignKey: {
395 name: 'videoId',
396 allowNull: false
397 },
398 onDelete: 'cascade'
399 })
3fd3ab2d 400 AccountVideoRates: AccountVideoRateModel[]
f285faa0 401
da854ddd
C
402 @HasMany(() => VideoCommentModel, {
403 foreignKey: {
404 name: 'videoId',
405 allowNull: false
406 },
f05a1c30
C
407 onDelete: 'cascade',
408 hooks: true
da854ddd
C
409 })
410 VideoComments: VideoCommentModel[]
411
f05a1c30
C
412 @BeforeDestroy
413 static async sendDelete (instance: VideoModel, options) {
414 if (instance.isOwned()) {
415 if (!instance.VideoChannel) {
416 instance.VideoChannel = await instance.$get('VideoChannel', {
417 include: [
418 {
419 model: AccountModel,
420 include: [ ActorModel ]
421 }
422 ],
423 transaction: options.transaction
424 }) as VideoChannelModel
425 }
426
427 logger.debug('Sending delete of video %s.', instance.url)
428
429 return sendDeleteVideo(instance, options.transaction)
430 }
431
432 return undefined
433 }
434
3fd3ab2d 435 @AfterDestroy
f05a1c30
C
436 static async removeFilesAndSendDelete (instance: VideoModel) {
437 const tasks: Promise<any>[] = []
f285faa0 438
f05a1c30 439 tasks.push(instance.removeThumbnail())
93e1258c 440
3fd3ab2d 441 if (instance.isOwned()) {
f05a1c30
C
442 if (!Array.isArray(instance.VideoFiles)) {
443 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
444 }
445
446 tasks.push(instance.removePreview())
40298b02 447
3fd3ab2d
C
448 // Remove physical files and torrents
449 instance.VideoFiles.forEach(file => {
450 tasks.push(instance.removeFile(file))
451 tasks.push(instance.removeTorrent(file))
452 })
453 }
40298b02 454
3fd3ab2d
C
455 return Promise.all(tasks)
456 .catch(err => {
457 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
458 })
459 }
f285faa0 460
3fd3ab2d 461 static list () {
d48ff09d 462 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
3fd3ab2d 463 }
f285faa0 464
50d6de9c 465 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
466 function getRawQuery (select: string) {
467 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
468 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
469 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
470 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
471 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
472 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 473 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 474
3fd3ab2d
C
475 return `(${queryVideo}) UNION (${queryVideoShare})`
476 }
aaf61f38 477
3fd3ab2d
C
478 const rawQuery = getRawQuery('"Video"."id"')
479 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
480
481 const query = {
482 distinct: true,
483 offset: start,
484 limit: count,
485 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
486 where: {
487 id: {
488 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
489 }
490 },
491 include: [
492 {
1d230c44 493 attributes: [ 'id', 'url' ],
2c897999 494 model: VideoShareModel.unscoped(),
3fd3ab2d
C
495 required: false,
496 where: {
497 [Sequelize.Op.and]: [
498 {
499 id: {
500 [Sequelize.Op.not]: null
501 }
502 },
503 {
50d6de9c 504 actorId
3fd3ab2d
C
505 }
506 ]
507 },
50d6de9c
C
508 include: [
509 {
2c897999
C
510 attributes: [ 'id', 'url' ],
511 model: ActorModel.unscoped()
50d6de9c
C
512 }
513 ]
3fd3ab2d
C
514 },
515 {
2c897999 516 model: VideoChannelModel.unscoped(),
3fd3ab2d
C
517 required: true,
518 include: [
519 {
2c897999
C
520 attributes: [ 'name' ],
521 model: AccountModel.unscoped(),
522 required: true,
523 include: [
524 {
525 attributes: [ 'id', 'url' ],
526 model: ActorModel.unscoped(),
527 required: true
528 }
529 ]
530 },
531 {
532 attributes: [ 'id', 'url' ],
533 model: ActorModel.unscoped(),
3fd3ab2d
C
534 required: true
535 }
536 ]
537 },
538 {
2c897999 539 attributes: [ 'type' ],
3fd3ab2d 540 model: AccountVideoRateModel,
2c897999
C
541 required: false,
542 include: [
543 {
544 attributes: [ 'id' ],
545 model: AccountModel.unscoped(),
546 include: [
547 {
548 attributes: [ 'url' ],
549 model: ActorModel.unscoped(),
550 include: [
551 {
552 attributes: [ 'host' ],
553 model: ServerModel,
554 required: false
555 }
556 ]
557 }
558 ]
559 }
560 ]
561 },
562 {
563 attributes: [ 'url' ],
564 model: VideoCommentModel,
565 required: false
3fd3ab2d
C
566 },
567 VideoFileModel,
2c897999 568 TagModel
3fd3ab2d
C
569 ]
570 }
164174a6 571
3fd3ab2d
C
572 return Bluebird.all([
573 // FIXME: typing issue
574 VideoModel.findAll(query as any),
575 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
576 ]).then(([ rows, totals ]) => {
577 // totals: totalVideos + totalVideoShares
578 let totalVideos = 0
579 let totalVideoShares = 0
580 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
581 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
582
583 const total = totalVideos + totalVideoShares
584 return {
585 data: rows,
586 total: total
587 }
588 })
589 }
93e1258c 590
3fd3ab2d
C
591 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
592 const query = {
3fd3ab2d
C
593 offset: start,
594 limit: count,
d48ff09d 595 order: [ getSort(sort) ],
3fd3ab2d
C
596 include: [
597 {
598 model: VideoChannelModel,
599 required: true,
600 include: [
601 {
602 model: AccountModel,
603 where: {
604 userId
605 },
606 required: true
607 }
608 ]
d48ff09d 609 }
3fd3ab2d
C
610 ]
611 }
d8755eed 612
3fd3ab2d
C
613 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
614 return {
615 data: rows,
616 total: count
617 }
618 })
619 }
93e1258c 620
f05a1c30 621 static async listForApi (start: number, count: number, sort: string) {
3fd3ab2d 622 const query = {
3fd3ab2d
C
623 offset: start,
624 limit: count,
d48ff09d 625 order: [ getSort(sort) ]
3fd3ab2d 626 }
93e1258c 627
f05a1c30
C
628 const serverActor = await getServerActor()
629
630 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
d48ff09d
C
631 .findAndCountAll(query)
632 .then(({ rows, count }) => {
633 return {
634 data: rows,
635 total: count
636 }
637 })
93e1258c
C
638 }
639
f05a1c30
C
640 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
641 const query: IFindOptions<VideoModel> = {
642 offset: start,
643 limit: count,
644 order: [ getSort(sort) ],
645 where: {
646 name: {
647 [Sequelize.Op.iLike]: '%' + value + '%'
648 }
649 }
650 }
651
652 const serverActor = await getServerActor()
653
654 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
655 .findAndCountAll(query).then(({ rows, count }) => {
656 return {
657 data: rows,
658 total: count
659 }
660 })
661 }
662
3fd3ab2d
C
663 static load (id: number) {
664 return VideoModel.findById(id)
665 }
fdbda9e3 666
3fd3ab2d
C
667 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
668 const query: IFindOptions<VideoModel> = {
669 where: {
670 url
d48ff09d 671 }
3fd3ab2d 672 }
d8755eed 673
3fd3ab2d 674 if (t !== undefined) query.transaction = t
d8755eed 675
4cb6d457 676 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
3fd3ab2d 677 }
d8755eed 678
2ccaeeb3 679 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
3fd3ab2d
C
680 const query: IFindOptions<VideoModel> = {
681 where: {
682 [Sequelize.Op.or]: [
683 { uuid },
684 { url }
685 ]
d48ff09d 686 }
3fd3ab2d 687 }
feb4bdfd 688
3fd3ab2d 689 if (t !== undefined) query.transaction = t
feb4bdfd 690
2ccaeeb3 691 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
72c7248b
C
692 }
693
3fd3ab2d
C
694 static loadAndPopulateAccountAndServerAndTags (id: number) {
695 const options = {
d48ff09d 696 order: [ [ 'Tags', 'name', 'ASC' ] ]
3fd3ab2d 697 }
72c7248b 698
d48ff09d 699 return VideoModel
4cb6d457 700 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
d48ff09d 701 .findById(id, options)
3fd3ab2d 702 }
72c7248b 703
8fa5653a
C
704 static loadByUUID (uuid: string) {
705 const options = {
706 where: {
707 uuid
708 }
709 }
710
711 return VideoModel
712 .scope([ ScopeNames.WITH_FILES ])
713 .findOne(options)
714 }
715
3fd3ab2d
C
716 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
717 const options = {
718 order: [ [ 'Tags', 'name', 'ASC' ] ],
719 where: {
720 uuid
d48ff09d 721 }
3fd3ab2d 722 }
fd45e8f4 723
d48ff09d 724 return VideoModel
4cb6d457 725 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
da854ddd
C
726 .findOne(options)
727 }
728
729 static loadAndPopulateAll (id: number) {
730 const options = {
731 order: [ [ 'Tags', 'name', 'ASC' ] ],
732 where: {
733 id
734 }
735 }
736
737 return VideoModel
738 .scope([
739 ScopeNames.WITH_RATES,
740 ScopeNames.WITH_SHARES,
741 ScopeNames.WITH_TAGS,
742 ScopeNames.WITH_FILES,
4cb6d457 743 ScopeNames.WITH_ACCOUNT_DETAILS,
da854ddd
C
744 ScopeNames.WITH_COMMENTS
745 ])
d48ff09d 746 .findOne(options)
aaf61f38
C
747 }
748
3fd3ab2d
C
749 getOriginalFile () {
750 if (Array.isArray(this.VideoFiles) === false) return undefined
aaf61f38 751
3fd3ab2d
C
752 // The original file is the file that have the higher resolution
753 return maxBy(this.VideoFiles, file => file.resolution)
e4f97bab 754 }
aaf61f38 755
3fd3ab2d
C
756 getVideoFilename (videoFile: VideoFileModel) {
757 return this.uuid + '-' + videoFile.resolution + videoFile.extname
758 }
165cdc75 759
3fd3ab2d
C
760 getThumbnailName () {
761 // We always have a copy of the thumbnail
762 const extension = '.jpg'
763 return this.uuid + extension
7b1f49de
C
764 }
765
3fd3ab2d
C
766 getPreviewName () {
767 const extension = '.jpg'
768 return this.uuid + extension
769 }
7b1f49de 770
3fd3ab2d
C
771 getTorrentFileName (videoFile: VideoFileModel) {
772 const extension = '.torrent'
773 return this.uuid + '-' + videoFile.resolution + extension
774 }
8e7f08b5 775
3fd3ab2d
C
776 isOwned () {
777 return this.remote === false
9567011b
C
778 }
779
3fd3ab2d
C
780 createPreview (videoFile: VideoFileModel) {
781 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
782
783 return generateImageFromVideoFile(
784 this.getVideoFilePath(videoFile),
785 CONFIG.STORAGE.PREVIEWS_DIR,
786 this.getPreviewName(),
787 imageSize
788 )
789 }
9567011b 790
3fd3ab2d
C
791 createThumbnail (videoFile: VideoFileModel) {
792 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
227d02fe 793
3fd3ab2d
C
794 return generateImageFromVideoFile(
795 this.getVideoFilePath(videoFile),
796 CONFIG.STORAGE.THUMBNAILS_DIR,
797 this.getThumbnailName(),
798 imageSize
799 )
14d3270f
C
800 }
801
3fd3ab2d
C
802 getVideoFilePath (videoFile: VideoFileModel) {
803 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
804 }
14d3270f 805
3fd3ab2d
C
806 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
807 const options = {
808 announceList: [
0edf0581
C
809 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
810 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
3fd3ab2d
C
811 ],
812 urlList: [
813 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
814 ]
815 }
14d3270f 816
3fd3ab2d 817 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
e4f97bab 818
3fd3ab2d
C
819 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
820 logger.info('Creating torrent %s.', filePath)
e4f97bab 821
3fd3ab2d 822 await writeFilePromise(filePath, torrent)
e4f97bab 823
3fd3ab2d
C
824 const parsedTorrent = parseTorrent(torrent)
825 videoFile.infoHash = parsedTorrent.infoHash
826 }
e4f97bab 827
3fd3ab2d
C
828 getEmbedPath () {
829 return '/videos/embed/' + this.uuid
830 }
e4f97bab 831
3fd3ab2d
C
832 getThumbnailPath () {
833 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
e4f97bab 834 }
227d02fe 835
3fd3ab2d
C
836 getPreviewPath () {
837 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
838 }
40298b02 839
3fd3ab2d
C
840 toFormattedJSON () {
841 let serverHost
40298b02 842
50d6de9c
C
843 if (this.VideoChannel.Account.Actor.Server) {
844 serverHost = this.VideoChannel.Account.Actor.Server.host
3fd3ab2d
C
845 } else {
846 // It means it's our video
847 serverHost = CONFIG.WEBSERVER.HOST
848 }
14d3270f 849
3fd3ab2d
C
850 return {
851 id: this.id,
852 uuid: this.uuid,
853 name: this.name,
854 category: this.category,
855 categoryLabel: this.getCategoryLabel(),
856 licence: this.licence,
857 licenceLabel: this.getLicenceLabel(),
858 language: this.language,
859 languageLabel: this.getLanguageLabel(),
860 nsfw: this.nsfw,
861 description: this.getTruncatedDescription(),
862 serverHost,
863 isLocal: this.isOwned(),
864 accountName: this.VideoChannel.Account.name,
865 duration: this.duration,
866 views: this.views,
867 likes: this.likes,
868 dislikes: this.dislikes,
3fd3ab2d
C
869 thumbnailPath: this.getThumbnailPath(),
870 previewPath: this.getPreviewPath(),
871 embedPath: this.getEmbedPath(),
872 createdAt: this.createdAt,
873 updatedAt: this.updatedAt
d48ff09d 874 } as Video
14d3270f 875 }
14d3270f 876
3fd3ab2d
C
877 toFormattedDetailsJSON () {
878 const formattedJson = this.toFormattedJSON()
e4f97bab 879
3fd3ab2d
C
880 // Maybe our server is not up to date and there are new privacy settings since our version
881 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
882 if (!privacyLabel) privacyLabel = 'Unknown'
e4f97bab 883
3fd3ab2d
C
884 const detailsJson = {
885 privacyLabel,
886 privacy: this.privacy,
887 descriptionPath: this.getDescriptionPath(),
888 channel: this.VideoChannel.toFormattedJSON(),
889 account: this.VideoChannel.Account.toFormattedJSON(),
d48ff09d 890 tags: map<TagModel, string>(this.Tags, 'name'),
47564bbe 891 commentsEnabled: this.commentsEnabled,
3fd3ab2d
C
892 files: []
893 }
e4f97bab 894
3fd3ab2d
C
895 // Format and sort video files
896 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
897 detailsJson.files = this.VideoFiles
898 .map(videoFile => {
899 let resolutionLabel = videoFile.resolution + 'p'
900
901 return {
902 resolution: videoFile.resolution,
903 resolutionLabel,
904 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
905 size: videoFile.size,
906 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
907 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
908 }
909 })
910 .sort((a, b) => {
911 if (a.resolution < b.resolution) return 1
912 if (a.resolution === b.resolution) return 0
913 return -1
914 })
915
d48ff09d 916 return Object.assign(formattedJson, detailsJson) as VideoDetails
3fd3ab2d 917 }
e4f97bab 918
3fd3ab2d
C
919 toActivityPubObject (): VideoTorrentObject {
920 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
921 if (!this.Tags) this.Tags = []
e4f97bab 922
3fd3ab2d
C
923 const tag = this.Tags.map(t => ({
924 type: 'Hashtag' as 'Hashtag',
925 name: t.name
926 }))
40298b02 927
3fd3ab2d
C
928 let language
929 if (this.language) {
930 language = {
931 identifier: this.language + '',
932 name: this.getLanguageLabel()
933 }
934 }
40298b02 935
3fd3ab2d
C
936 let category
937 if (this.category) {
938 category = {
939 identifier: this.category + '',
940 name: this.getCategoryLabel()
941 }
942 }
40298b02 943
3fd3ab2d
C
944 let licence
945 if (this.licence) {
946 licence = {
947 identifier: this.licence + '',
948 name: this.getLicenceLabel()
949 }
950 }
9567011b 951
3fd3ab2d
C
952 let likesObject
953 let dislikesObject
e4f97bab 954
3fd3ab2d
C
955 if (Array.isArray(this.AccountVideoRates)) {
956 const likes: string[] = []
957 const dislikes: string[] = []
e4f97bab 958
3fd3ab2d
C
959 for (const rate of this.AccountVideoRates) {
960 if (rate.type === 'like') {
50d6de9c 961 likes.push(rate.Account.Actor.url)
3fd3ab2d 962 } else if (rate.type === 'dislike') {
50d6de9c 963 dislikes.push(rate.Account.Actor.url)
3fd3ab2d
C
964 }
965 }
e4f97bab 966
46531a0a
C
967 const res = this.toRatesActivityPubObjects()
968 likesObject = res.likesObject
969 dislikesObject = res.dislikesObject
3fd3ab2d 970 }
e4f97bab 971
3fd3ab2d
C
972 let sharesObject
973 if (Array.isArray(this.VideoShares)) {
46531a0a 974 sharesObject = this.toAnnouncesActivityPubObject()
3fd3ab2d 975 }
93e1258c 976
da854ddd
C
977 let commentsObject
978 if (Array.isArray(this.VideoComments)) {
46531a0a 979 commentsObject = this.toCommentsActivityPubObject()
da854ddd
C
980 }
981
3fd3ab2d
C
982 const url = []
983 for (const file of this.VideoFiles) {
984 url.push({
985 type: 'Link',
986 mimeType: 'video/' + file.extname.replace('.', ''),
9fb3abfd 987 href: this.getVideoFileUrl(file, baseUrlHttp),
3fd3ab2d
C
988 width: file.resolution,
989 size: file.size
990 })
991
992 url.push({
993 type: 'Link',
994 mimeType: 'application/x-bittorrent',
9fb3abfd 995 href: this.getTorrentUrl(file, baseUrlHttp),
3fd3ab2d
C
996 width: file.resolution
997 })
998
999 url.push({
1000 type: 'Link',
1001 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
9fb3abfd 1002 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
3fd3ab2d
C
1003 width: file.resolution
1004 })
1005 }
93e1258c 1006
3fd3ab2d
C
1007 // Add video url too
1008 url.push({
1009 type: 'Link',
1010 mimeType: 'text/html',
9fb3abfd 1011 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
3fd3ab2d 1012 })
93e1258c 1013
3fd3ab2d
C
1014 return {
1015 type: 'Video' as 'Video',
1016 id: this.url,
1017 name: this.name,
093237cf 1018 duration: this.getActivityStreamDuration(),
3fd3ab2d
C
1019 uuid: this.uuid,
1020 tag,
1021 category,
1022 licence,
1023 language,
1024 views: this.views,
0a67e28b 1025 sensitive: this.nsfw,
47564bbe 1026 commentsEnabled: this.commentsEnabled,
3fd3ab2d
C
1027 published: this.createdAt.toISOString(),
1028 updated: this.updatedAt.toISOString(),
1029 mediaType: 'text/markdown',
1030 content: this.getTruncatedDescription(),
1031 icon: {
1032 type: 'Image',
1033 url: this.getThumbnailUrl(baseUrlHttp),
1034 mediaType: 'image/jpeg',
1035 width: THUMBNAILS_SIZE.width,
1036 height: THUMBNAILS_SIZE.height
1037 },
1038 url,
1039 likes: likesObject,
1040 dislikes: dislikesObject,
50d6de9c 1041 shares: sharesObject,
da854ddd 1042 comments: commentsObject,
50d6de9c
C
1043 attributedTo: [
1044 {
1045 type: 'Group',
1046 id: this.VideoChannel.Actor.url
2ccaeeb3
C
1047 },
1048 {
1049 type: 'Person',
1050 id: this.VideoChannel.Account.Actor.url
50d6de9c
C
1051 }
1052 ]
3fd3ab2d
C
1053 }
1054 }
1055
46531a0a
C
1056 toAnnouncesActivityPubObject () {
1057 const shares: string[] = []
1058
1059 for (const videoShare of this.VideoShares) {
1060 shares.push(videoShare.url)
1061 }
1062
1063 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1064 }
1065
1066 toCommentsActivityPubObject () {
1067 const comments: string[] = []
1068
1069 for (const videoComment of this.VideoComments) {
1070 comments.push(videoComment.url)
1071 }
1072
1073 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1074 }
1075
1076 toRatesActivityPubObjects () {
1077 const likes: string[] = []
1078 const dislikes: string[] = []
1079
1080 for (const rate of this.AccountVideoRates) {
1081 if (rate.type === 'like') {
1082 likes.push(rate.Account.Actor.url)
1083 } else if (rate.type === 'dislike') {
1084 dislikes.push(rate.Account.Actor.url)
1085 }
1086 }
1087
1088 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1089 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1090
1091 return { likesObject, dislikesObject }
1092 }
1093
3fd3ab2d
C
1094 getTruncatedDescription () {
1095 if (!this.description) return null
93e1258c 1096
3fd3ab2d
C
1097 const options = {
1098 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1099 }
aaf61f38 1100
3fd3ab2d 1101 return truncate(this.description, options)
93e1258c
C
1102 }
1103
3fd3ab2d
C
1104 optimizeOriginalVideofile = async function () {
1105 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1106 const newExtname = '.mp4'
1107 const inputVideoFile = this.getOriginalFile()
1108 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1109 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
b769007f 1110
3fd3ab2d
C
1111 const transcodeOptions = {
1112 inputPath: videoInputPath,
1113 outputPath: videoOutputPath
1114 }
c46edbc2 1115
3fd3ab2d
C
1116 try {
1117 // Could be very long!
1118 await transcode(transcodeOptions)
c46edbc2 1119
3fd3ab2d 1120 await unlinkPromise(videoInputPath)
c46edbc2 1121
3fd3ab2d
C
1122 // Important to do this before getVideoFilename() to take in account the new file extension
1123 inputVideoFile.set('extname', newExtname)
e71bcc0f 1124
3fd3ab2d
C
1125 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1126 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
e71bcc0f 1127
3fd3ab2d 1128 inputVideoFile.set('size', stats.size)
e71bcc0f 1129
3fd3ab2d
C
1130 await this.createTorrentAndSetInfoHash(inputVideoFile)
1131 await inputVideoFile.save()
fd45e8f4 1132
3fd3ab2d
C
1133 } catch (err) {
1134 // Auto destruction...
1135 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
fd45e8f4 1136
3fd3ab2d
C
1137 throw err
1138 }
feb4bdfd
C
1139 }
1140
3fd3ab2d
C
1141 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1142 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1143 const extname = '.mp4'
aaf61f38 1144
3fd3ab2d
C
1145 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1146 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
feb4bdfd 1147
3fd3ab2d
C
1148 const newVideoFile = new VideoFileModel({
1149 resolution,
1150 extname,
1151 size: 0,
1152 videoId: this.id
1153 })
1154 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
a041b171 1155
3fd3ab2d
C
1156 const transcodeOptions = {
1157 inputPath: videoInputPath,
1158 outputPath: videoOutputPath,
1159 resolution
1160 }
a041b171 1161
3fd3ab2d 1162 await transcode(transcodeOptions)
a041b171 1163
3fd3ab2d 1164 const stats = await statPromise(videoOutputPath)
d7d5611c 1165
3fd3ab2d 1166 newVideoFile.set('size', stats.size)
d7d5611c 1167
3fd3ab2d 1168 await this.createTorrentAndSetInfoHash(newVideoFile)
d7d5611c 1169
3fd3ab2d
C
1170 await newVideoFile.save()
1171
1172 this.VideoFiles.push(newVideoFile)
0d0e8dd0
C
1173 }
1174
3fd3ab2d
C
1175 getOriginalFileHeight () {
1176 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
0d0e8dd0 1177
3fd3ab2d
C
1178 return getVideoFileHeight(originalFilePath)
1179 }
0d0e8dd0 1180
3fd3ab2d
C
1181 getDescriptionPath () {
1182 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1183 }
1184
3fd3ab2d
C
1185 getCategoryLabel () {
1186 let categoryLabel = VIDEO_CATEGORIES[this.category]
1187 if (!categoryLabel) categoryLabel = 'Misc'
aaf61f38 1188
3fd3ab2d 1189 return categoryLabel
0a6658fd
C
1190 }
1191
3fd3ab2d
C
1192 getLicenceLabel () {
1193 let licenceLabel = VIDEO_LICENCES[this.licence]
1194 if (!licenceLabel) licenceLabel = 'Unknown'
0a6658fd 1195
3fd3ab2d 1196 return licenceLabel
feb4bdfd 1197 }
7920c273 1198
3fd3ab2d
C
1199 getLanguageLabel () {
1200 let languageLabel = VIDEO_LANGUAGES[this.language]
1201 if (!languageLabel) languageLabel = 'Unknown'
1202
1203 return languageLabel
72c7248b
C
1204 }
1205
3fd3ab2d
C
1206 removeThumbnail () {
1207 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1208 return unlinkPromise(thumbnailPath)
feb4bdfd
C
1209 }
1210
3fd3ab2d
C
1211 removePreview () {
1212 // Same name than video thumbnail
1213 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
7920c273
C
1214 }
1215
3fd3ab2d
C
1216 removeFile (videoFile: VideoFileModel) {
1217 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1218 return unlinkPromise(filePath)
feb4bdfd
C
1219 }
1220
3fd3ab2d
C
1221 removeTorrent (videoFile: VideoFileModel) {
1222 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1223 return unlinkPromise(torrentPath)
aaf61f38
C
1224 }
1225
093237cf
C
1226 getActivityStreamDuration () {
1227 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1228 return 'PT' + this.duration + 'S'
1229 }
1230
3fd3ab2d
C
1231 private getBaseUrls () {
1232 let baseUrlHttp
1233 let baseUrlWs
7920c273 1234
3fd3ab2d
C
1235 if (this.isOwned()) {
1236 baseUrlHttp = CONFIG.WEBSERVER.URL
1237 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1238 } else {
50d6de9c
C
1239 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1240 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
6fcd19ba 1241 }
aaf61f38 1242
3fd3ab2d 1243 return { baseUrlHttp, baseUrlWs }
15d4ee04 1244 }
a96aed15 1245
3fd3ab2d
C
1246 private getThumbnailUrl (baseUrlHttp: string) {
1247 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
a96aed15
C
1248 }
1249
3fd3ab2d
C
1250 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1251 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1252 }
e4f97bab 1253
3fd3ab2d
C
1254 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1255 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1256 }
a96aed15 1257
3fd3ab2d
C
1258 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1259 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1260 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1261 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1262
1263 const magnetHash = {
1264 xs,
1265 announce,
1266 urlList,
1267 infoHash: videoFile.infoHash,
1268 name: this.name
1269 }
a96aed15 1270
3fd3ab2d 1271 return magnetUtil.encode(magnetHash)
a96aed15 1272 }
a96aed15 1273}