]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Optimize SQL queries
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
CommitLineData
39445ead 1import * as Bluebird from 'bluebird'
c73e83da 2import { map, maxBy } from 'lodash'
571389d4 3import * as magnetUtil from 'magnet-uri'
4d4e5cd4 4import * as parseTorrent from 'parse-torrent'
28be8916 5import { extname, join } from 'path'
e02643f3 6import * as Sequelize from 'sequelize'
3fd3ab2d 7import {
4ba3b8ea
C
8 AllowNull,
9 BeforeDestroy,
10 BelongsTo,
11 BelongsToMany,
12 Column,
13 CreatedAt,
14 DataType,
15 Default,
16 ForeignKey,
17 HasMany,
2baea0c7 18 HasOne,
4ba3b8ea
C
19 IFindOptions,
20 Is,
21 IsInt,
22 IsUUID,
23 Min,
24 Model,
25 Scopes,
26 Table,
27 UpdatedAt
3fd3ab2d 28} from 'sequelize-typescript'
2186386c 29import { VideoPrivacy, VideoResolution, VideoState } from '../../../shared'
3fd3ab2d 30import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
a8462c8e 31import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
066e94c5 32import { VideoFilter } from '../../../shared/models/videos/video-query.type'
c73e83da 33import {
28be8916 34 copyFilePromise,
06be7ed0
C
35 createTorrentPromise,
36 peertubeTruncate,
37 renamePromise,
38 statPromise,
39 unlinkPromise,
c73e83da
C
40 writeFilePromise
41} from '../../helpers/core-utils'
da854ddd 42import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
47564bbe 43import { isBooleanValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 44import {
4ba3b8ea
C
45 isVideoCategoryValid,
46 isVideoDescriptionValid,
47 isVideoDurationValid,
48 isVideoLanguageValid,
49 isVideoLicenceValid,
50 isVideoNameValid,
2baea0c7
C
51 isVideoPrivacyValid,
52 isVideoStateValid,
b64c950a 53 isVideoSupportValid
3fd3ab2d 54} from '../../helpers/custom-validators/videos'
3a6f351b 55import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
da854ddd 56import { logger } from '../../helpers/logger'
f05a1c30 57import { getServerActor } from '../../helpers/utils'
65fcc311 58import {
4ba3b8ea
C
59 API_VERSION,
60 CONFIG,
61 CONSTRAINTS_FIELDS,
62 PREVIEWS_SIZE,
63 REMOTE_SCHEME,
02756fbd 64 STATIC_DOWNLOAD_PATHS,
4ba3b8ea
C
65 STATIC_PATHS,
66 THUMBNAILS_SIZE,
67 VIDEO_CATEGORIES,
28be8916 68 VIDEO_EXT_MIMETYPE,
4ba3b8ea
C
69 VIDEO_LANGUAGES,
70 VIDEO_LICENCES,
2baea0c7
C
71 VIDEO_PRIVACIES,
72 VIDEO_STATES
3fd3ab2d 73} from '../../initializers'
46531a0a
C
74import {
75 getVideoCommentsActivityPubUrl,
76 getVideoDislikesActivityPubUrl,
77 getVideoLikesActivityPubUrl,
78 getVideoSharesActivityPubUrl
79} from '../../lib/activitypub'
50d6de9c 80import { sendDeleteVideo } from '../../lib/activitypub/send'
3fd3ab2d
C
81import { AccountModel } from '../account/account'
82import { AccountVideoRateModel } from '../account/account-video-rate'
50d6de9c 83import { ActorModel } from '../activitypub/actor'
b6a4fd6b 84import { AvatarModel } from '../avatar/avatar'
3fd3ab2d 85import { ServerModel } from '../server/server'
57c36b27 86import { buildTrigramSearchIndex, createSearchTrigramQuery, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
3fd3ab2d
C
87import { TagModel } from './tag'
88import { VideoAbuseModel } from './video-abuse'
89import { VideoChannelModel } from './video-channel'
da854ddd 90import { VideoCommentModel } from './video-comment'
3fd3ab2d
C
91import { VideoFileModel } from './video-file'
92import { VideoShareModel } from './video-share'
93import { VideoTagModel } from './video-tag'
2baea0c7 94import { ScheduleVideoUpdateModel } from './schedule-video-update'
40e87e9e 95import { VideoCaptionModel } from './video-caption'
d525fc39 96import { VideosSearchQuery } from '../../../shared/models/search'
3fd3ab2d 97
57c36b27
C
98// FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
99const indexes: Sequelize.DefineIndexesOptions[] = [
100 buildTrigramSearchIndex('video_name_trigram', 'name'),
101
8cd72bd3
C
102 { fields: [ 'createdAt' ] },
103 { fields: [ 'publishedAt' ] },
104 { fields: [ 'duration' ] },
105 { fields: [ 'category' ] },
106 { fields: [ 'licence' ] },
107 { fields: [ 'nsfw' ] },
108 { fields: [ 'language' ] },
109 { fields: [ 'waitTranscoding' ] },
110 { fields: [ 'state' ] },
111 { fields: [ 'remote' ] },
112 { fields: [ 'views' ] },
113 { fields: [ 'likes' ] },
114 { fields: [ 'channelId' ] },
57c36b27 115 {
8cd72bd3
C
116 fields: [ 'uuid' ],
117 unique: true
57c36b27
C
118 },
119 {
120 fields: [ 'url'],
121 unique: true
122 }
123]
124
2baea0c7 125export enum ScopeNames {
50d6de9c 126 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
4cb6d457 127 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d 128 WITH_TAGS = 'WITH_TAGS',
bbe0f064
C
129 WITH_FILES = 'WITH_FILES',
130 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE'
d48ff09d
C
131}
132
d525fc39
C
133type AvailableForListOptions = {
134 actorId: number,
135 filter?: VideoFilter,
136 categoryOneOf?: number[],
137 nsfw?: boolean,
138 licenceOneOf?: number[],
139 languageOneOf?: string[],
140 tagsOneOf?: string[],
141 tagsAllOf?: string[],
142 withFiles?: boolean,
143 accountId?: number,
144 videoChannelId?: number
145}
146
d48ff09d 147@Scopes({
d525fc39 148 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
0626e7af 149 const accountInclude = {
03e12d7c 150 attributes: [ 'id', 'name' ],
0626e7af
C
151 model: AccountModel.unscoped(),
152 required: true,
153 where: {},
154 include: [
155 {
03e12d7c 156 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
0626e7af
C
157 model: ActorModel.unscoped(),
158 required: true,
48dce1c9 159 where: VideoModel.buildActorWhereWithFilter(options.filter),
0626e7af
C
160 include: [
161 {
162 attributes: [ 'host' ],
163 model: ServerModel.unscoped(),
164 required: false
165 },
166 {
167 model: AvatarModel.unscoped(),
168 required: false
169 }
170 ]
171 }
172 ]
173 }
174
48dce1c9 175 const videoChannelInclude = {
0f320037 176 attributes: [ 'name', 'description', 'id' ],
48dce1c9
C
177 model: VideoChannelModel.unscoped(),
178 required: true,
179 where: {},
180 include: [
0f320037
C
181 {
182 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
183 model: ActorModel.unscoped(),
184 required: true,
185 include: [
186 {
187 attributes: [ 'host' ],
188 model: ServerModel.unscoped(),
189 required: false
190 },
191 {
192 model: AvatarModel.unscoped(),
193 required: false
194 }
195 ]
196 },
48dce1c9
C
197 accountInclude
198 ]
199 }
200
201 // Force actorId to be a number to avoid SQL injections
202 const actorIdNumber = parseInt(options.actorId.toString(), 10)
244e76a5
RK
203 const query: IFindOptions<VideoModel> = {
204 where: {
205 id: {
206 [Sequelize.Op.notIn]: Sequelize.literal(
207 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
208 ),
209 [ Sequelize.Op.in ]: Sequelize.literal(
210 '(' +
8cd72bd3
C
211 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
212 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
213 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
214 ' UNION ' +
215 'SELECT "video"."id" AS "id" FROM "video" ' +
216 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
217 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
218 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
219 'WHERE "actor"."serverId" IS NULL OR ' +
220 '"actor"."id" IN (SELECT "targetActorId" FROM "actorFollow" WHERE "actorId" = 1)' + // Subquery for optimization
244e76a5
RK
221 ')'
222 )
223 },
2186386c
C
224 // Always list public videos
225 privacy: VideoPrivacy.PUBLIC,
226 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
227 [ Sequelize.Op.or ]: [
228 {
229 state: VideoState.PUBLISHED
230 },
231 {
232 [ Sequelize.Op.and ]: {
233 state: VideoState.TO_TRANSCODE,
234 waitTranscoding: false
235 }
236 }
237 ]
50d6de9c 238 },
48dce1c9 239 include: [ videoChannelInclude ]
244e76a5
RK
240 }
241
48dce1c9 242 if (options.withFiles === true) {
244e76a5
RK
243 query.include.push({
244 model: VideoFileModel.unscoped(),
245 required: true
246 })
247 }
248
d525fc39
C
249 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
250 if (options.tagsAllOf || options.tagsOneOf) {
251 const createTagsIn = (tags: string[]) => {
252 return tags.map(t => VideoModel.sequelize.escape(t))
253 .join(', ')
254 }
255
256 if (options.tagsOneOf) {
257 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
258 '(' +
259 'SELECT "videoId" FROM "videoTag" ' +
260 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
261 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
262 ')'
263 )
264 }
265
266 if (options.tagsAllOf) {
267 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
268 '(' +
269 'SELECT "videoId" FROM "videoTag" ' +
270 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
271 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
272 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
273 ')'
274 )
275 }
276 }
277
278 if (options.nsfw === true || options.nsfw === false) {
279 query.where['nsfw'] = options.nsfw
280 }
281
282 if (options.categoryOneOf) {
283 query.where['category'] = {
284 [Sequelize.Op.or]: options.categoryOneOf
285 }
286 }
287
288 if (options.licenceOneOf) {
289 query.where['licence'] = {
290 [Sequelize.Op.or]: options.licenceOneOf
291 }
0883b324
C
292 }
293
d525fc39
C
294 if (options.languageOneOf) {
295 query.where['language'] = {
296 [Sequelize.Op.or]: options.languageOneOf
297 }
61b909b9
P
298 }
299
48dce1c9 300 if (options.accountId) {
0626e7af 301 accountInclude.where = {
48dce1c9
C
302 id: options.accountId
303 }
304 }
305
306 if (options.videoChannelId) {
307 videoChannelInclude.where = {
308 id: options.videoChannelId
0626e7af
C
309 }
310 }
311
244e76a5
RK
312 return query
313 },
4cb6d457 314 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
d48ff09d
C
315 include: [
316 {
6120941f 317 model: () => VideoChannelModel.unscoped(),
d48ff09d
C
318 required: true,
319 include: [
6120941f
C
320 {
321 attributes: {
322 exclude: [ 'privateKey', 'publicKey' ]
323 },
3e500247
C
324 model: () => ActorModel.unscoped(),
325 required: true,
326 include: [
327 {
328 attributes: [ 'host' ],
329 model: () => ServerModel.unscoped(),
330 required: false
52d9f792
C
331 },
332 {
333 model: () => AvatarModel.unscoped(),
334 required: false
3e500247
C
335 }
336 ]
6120941f 337 },
d48ff09d 338 {
3e500247 339 model: () => AccountModel.unscoped(),
d48ff09d
C
340 required: true,
341 include: [
342 {
3e500247 343 model: () => ActorModel.unscoped(),
6120941f
C
344 attributes: {
345 exclude: [ 'privateKey', 'publicKey' ]
346 },
50d6de9c
C
347 required: true,
348 include: [
349 {
3e500247
C
350 attributes: [ 'host' ],
351 model: () => ServerModel.unscoped(),
50d6de9c 352 required: false
b6a4fd6b
C
353 },
354 {
355 model: () => AvatarModel.unscoped(),
356 required: false
50d6de9c
C
357 }
358 ]
d48ff09d
C
359 }
360 ]
361 }
362 ]
363 }
364 ]
365 },
366 [ScopeNames.WITH_TAGS]: {
367 include: [ () => TagModel ]
368 },
369 [ScopeNames.WITH_FILES]: {
370 include: [
371 {
e53f952e 372 model: () => VideoFileModel.unscoped(),
d48ff09d
C
373 required: true
374 }
375 ]
bbe0f064
C
376 },
377 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
378 include: [
379 {
380 model: () => ScheduleVideoUpdateModel.unscoped(),
381 required: false
382 }
383 ]
d48ff09d
C
384 }
385})
3fd3ab2d
C
386@Table({
387 tableName: 'video',
57c36b27 388 indexes
3fd3ab2d
C
389})
390export class VideoModel extends Model<VideoModel> {
391
392 @AllowNull(false)
393 @Default(DataType.UUIDV4)
394 @IsUUID(4)
395 @Column(DataType.UUID)
396 uuid: string
397
398 @AllowNull(false)
399 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
400 @Column
401 name: string
402
403 @AllowNull(true)
404 @Default(null)
405 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
406 @Column
407 category: number
408
409 @AllowNull(true)
410 @Default(null)
411 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
412 @Column
413 licence: number
414
415 @AllowNull(true)
416 @Default(null)
417 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
9d3ef9fe
C
418 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
419 language: string
3fd3ab2d
C
420
421 @AllowNull(false)
422 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
423 @Column
424 privacy: number
425
426 @AllowNull(false)
47564bbe 427 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
428 @Column
429 nsfw: boolean
430
431 @AllowNull(true)
432 @Default(null)
433 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
434 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
435 description: string
436
2422c46b
C
437 @AllowNull(true)
438 @Default(null)
439 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
440 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
441 support: string
442
3fd3ab2d
C
443 @AllowNull(false)
444 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
445 @Column
446 duration: number
447
448 @AllowNull(false)
449 @Default(0)
450 @IsInt
451 @Min(0)
452 @Column
453 views: number
454
455 @AllowNull(false)
456 @Default(0)
457 @IsInt
458 @Min(0)
459 @Column
460 likes: number
461
462 @AllowNull(false)
463 @Default(0)
464 @IsInt
465 @Min(0)
466 @Column
467 dislikes: number
468
469 @AllowNull(false)
470 @Column
471 remote: boolean
472
473 @AllowNull(false)
474 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
475 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
476 url: string
477
47564bbe
C
478 @AllowNull(false)
479 @Column
480 commentsEnabled: boolean
481
2186386c
C
482 @AllowNull(false)
483 @Column
484 waitTranscoding: boolean
485
486 @AllowNull(false)
487 @Default(null)
488 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
489 @Column
490 state: VideoState
491
3fd3ab2d
C
492 @CreatedAt
493 createdAt: Date
494
495 @UpdatedAt
496 updatedAt: Date
497
2922e048
JLB
498 @AllowNull(false)
499 @Default(Sequelize.NOW)
500 @Column
501 publishedAt: Date
502
3fd3ab2d
C
503 @ForeignKey(() => VideoChannelModel)
504 @Column
505 channelId: number
506
507 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 508 foreignKey: {
50d6de9c 509 allowNull: true
feb4bdfd 510 },
6b738c7a 511 hooks: true
feb4bdfd 512 })
3fd3ab2d 513 VideoChannel: VideoChannelModel
7920c273 514
3fd3ab2d 515 @BelongsToMany(() => TagModel, {
7920c273 516 foreignKey: 'videoId',
3fd3ab2d
C
517 through: () => VideoTagModel,
518 onDelete: 'CASCADE'
7920c273 519 })
3fd3ab2d 520 Tags: TagModel[]
55fa55a9 521
3fd3ab2d 522 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
523 foreignKey: {
524 name: 'videoId',
525 allowNull: false
526 },
527 onDelete: 'cascade'
528 })
3fd3ab2d 529 VideoAbuses: VideoAbuseModel[]
93e1258c 530
3fd3ab2d 531 @HasMany(() => VideoFileModel, {
93e1258c
C
532 foreignKey: {
533 name: 'videoId',
534 allowNull: false
535 },
536 onDelete: 'cascade'
537 })
3fd3ab2d 538 VideoFiles: VideoFileModel[]
e71bcc0f 539
3fd3ab2d 540 @HasMany(() => VideoShareModel, {
e71bcc0f
C
541 foreignKey: {
542 name: 'videoId',
543 allowNull: false
544 },
545 onDelete: 'cascade'
546 })
3fd3ab2d 547 VideoShares: VideoShareModel[]
16b90975 548
3fd3ab2d 549 @HasMany(() => AccountVideoRateModel, {
16b90975
C
550 foreignKey: {
551 name: 'videoId',
552 allowNull: false
553 },
554 onDelete: 'cascade'
555 })
3fd3ab2d 556 AccountVideoRates: AccountVideoRateModel[]
f285faa0 557
da854ddd
C
558 @HasMany(() => VideoCommentModel, {
559 foreignKey: {
560 name: 'videoId',
561 allowNull: false
562 },
f05a1c30
C
563 onDelete: 'cascade',
564 hooks: true
da854ddd
C
565 })
566 VideoComments: VideoCommentModel[]
567
2baea0c7
C
568 @HasOne(() => ScheduleVideoUpdateModel, {
569 foreignKey: {
570 name: 'videoId',
571 allowNull: false
572 },
573 onDelete: 'cascade'
574 })
575 ScheduleVideoUpdate: ScheduleVideoUpdateModel
576
40e87e9e
C
577 @HasMany(() => VideoCaptionModel, {
578 foreignKey: {
579 name: 'videoId',
580 allowNull: false
581 },
582 onDelete: 'cascade',
583 hooks: true,
584 ['separate' as any]: true
585 })
586 VideoCaptions: VideoCaptionModel[]
587
f05a1c30
C
588 @BeforeDestroy
589 static async sendDelete (instance: VideoModel, options) {
590 if (instance.isOwned()) {
591 if (!instance.VideoChannel) {
592 instance.VideoChannel = await instance.$get('VideoChannel', {
593 include: [
594 {
595 model: AccountModel,
596 include: [ ActorModel ]
597 }
598 ],
599 transaction: options.transaction
600 }) as VideoChannelModel
601 }
602
603 logger.debug('Sending delete of video %s.', instance.url)
604
605 return sendDeleteVideo(instance, options.transaction)
606 }
607
608 return undefined
609 }
610
6b738c7a 611 @BeforeDestroy
40e87e9e 612 static async removeFiles (instance: VideoModel) {
f05a1c30 613 const tasks: Promise<any>[] = []
f285faa0 614
6b738c7a
C
615 logger.debug('Removing files of video %s.', instance.url)
616
f05a1c30 617 tasks.push(instance.removeThumbnail())
93e1258c 618
3fd3ab2d 619 if (instance.isOwned()) {
f05a1c30
C
620 if (!Array.isArray(instance.VideoFiles)) {
621 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
622 }
623
624 tasks.push(instance.removePreview())
40298b02 625
3fd3ab2d
C
626 // Remove physical files and torrents
627 instance.VideoFiles.forEach(file => {
628 tasks.push(instance.removeFile(file))
629 tasks.push(instance.removeTorrent(file))
630 })
631 }
40298b02 632
6b738c7a
C
633 // Do not wait video deletion because we could be in a transaction
634 Promise.all(tasks)
3fd3ab2d 635 .catch(err => {
d5b7d911 636 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
3fd3ab2d 637 })
6b738c7a
C
638
639 return undefined
3fd3ab2d 640 }
f285faa0 641
3fd3ab2d 642 static list () {
d48ff09d 643 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
3fd3ab2d 644 }
f285faa0 645
50d6de9c 646 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
647 function getRawQuery (select: string) {
648 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
649 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
650 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
651 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
652 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
653 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 654 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 655
3fd3ab2d
C
656 return `(${queryVideo}) UNION (${queryVideoShare})`
657 }
aaf61f38 658
3fd3ab2d
C
659 const rawQuery = getRawQuery('"Video"."id"')
660 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
661
662 const query = {
663 distinct: true,
664 offset: start,
665 limit: count,
3bb6c526 666 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
3fd3ab2d
C
667 where: {
668 id: {
669 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
3c75ce12
C
670 },
671 [Sequelize.Op.or]: [
672 { privacy: VideoPrivacy.PUBLIC },
673 { privacy: VideoPrivacy.UNLISTED }
674 ]
3fd3ab2d
C
675 },
676 include: [
40e87e9e
C
677 {
678 attributes: [ 'language' ],
679 model: VideoCaptionModel.unscoped(),
680 required: false
681 },
3fd3ab2d 682 {
1d230c44 683 attributes: [ 'id', 'url' ],
2c897999 684 model: VideoShareModel.unscoped(),
3fd3ab2d 685 required: false,
e3d5ea4f
C
686 // We only want videos shared by this actor
687 where: {
688 [Sequelize.Op.and]: [
689 {
690 id: {
691 [Sequelize.Op.not]: null
692 }
693 },
694 {
695 actorId
696 }
697 ]
698 },
50d6de9c
C
699 include: [
700 {
2c897999
C
701 attributes: [ 'id', 'url' ],
702 model: ActorModel.unscoped()
50d6de9c
C
703 }
704 ]
3fd3ab2d
C
705 },
706 {
2c897999 707 model: VideoChannelModel.unscoped(),
3fd3ab2d
C
708 required: true,
709 include: [
710 {
2c897999
C
711 attributes: [ 'name' ],
712 model: AccountModel.unscoped(),
713 required: true,
714 include: [
715 {
e3d5ea4f 716 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999
C
717 model: ActorModel.unscoped(),
718 required: true
719 }
720 ]
721 },
722 {
e3d5ea4f 723 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999 724 model: ActorModel.unscoped(),
3fd3ab2d
C
725 required: true
726 }
727 ]
728 },
3fd3ab2d 729 VideoFileModel,
2c897999 730 TagModel
3fd3ab2d
C
731 ]
732 }
164174a6 733
3fd3ab2d
C
734 return Bluebird.all([
735 // FIXME: typing issue
736 VideoModel.findAll(query as any),
737 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
738 ]).then(([ rows, totals ]) => {
739 // totals: totalVideos + totalVideoShares
740 let totalVideos = 0
741 let totalVideoShares = 0
742 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
743 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
744
745 const total = totalVideos + totalVideoShares
746 return {
747 data: rows,
748 total: total
749 }
750 })
751 }
93e1258c 752
2186386c 753 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
244e76a5 754 const query: IFindOptions<VideoModel> = {
3fd3ab2d
C
755 offset: start,
756 limit: count,
3bb6c526 757 order: getSort(sort),
3fd3ab2d
C
758 include: [
759 {
760 model: VideoChannelModel,
761 required: true,
762 include: [
763 {
764 model: AccountModel,
765 where: {
7b87d2d5 766 id: accountId
3fd3ab2d
C
767 },
768 required: true
769 }
770 ]
2baea0c7
C
771 },
772 {
773 model: ScheduleVideoUpdateModel,
774 required: false
d48ff09d 775 }
3fd3ab2d
C
776 ]
777 }
d8755eed 778
244e76a5
RK
779 if (withFiles === true) {
780 query.include.push({
781 model: VideoFileModel.unscoped(),
782 required: true
783 })
784 }
785
0883b324
C
786 if (hideNSFW === true) {
787 query.where = {
788 nsfw: false
789 }
790 }
791
3fd3ab2d
C
792 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
793 return {
794 data: rows,
795 total: count
796 }
797 })
798 }
93e1258c 799
48dce1c9 800 static async listForApi (options: {
0626e7af
C
801 start: number,
802 count: number,
803 sort: string,
d525fc39 804 nsfw: boolean,
48dce1c9 805 withFiles: boolean,
d525fc39
C
806 categoryOneOf?: number[],
807 licenceOneOf?: number[],
808 languageOneOf?: string[],
809 tagsOneOf?: string[],
810 tagsAllOf?: string[],
0626e7af 811 filter?: VideoFilter,
48dce1c9
C
812 accountId?: number,
813 videoChannelId?: number
814 }) {
3fd3ab2d 815 const query = {
48dce1c9
C
816 offset: options.start,
817 limit: options.count,
818 order: getSort(options.sort)
3fd3ab2d 819 }
93e1258c 820
f05a1c30 821 const serverActor = await getServerActor()
48dce1c9
C
822 const scopes = {
823 method: [
824 ScopeNames.AVAILABLE_FOR_LIST, {
825 actorId: serverActor.id,
d525fc39
C
826 nsfw: options.nsfw,
827 categoryOneOf: options.categoryOneOf,
828 licenceOneOf: options.licenceOneOf,
829 languageOneOf: options.languageOneOf,
830 tagsOneOf: options.tagsOneOf,
831 tagsAllOf: options.tagsAllOf,
48dce1c9
C
832 filter: options.filter,
833 withFiles: options.withFiles,
834 accountId: options.accountId,
835 videoChannelId: options.videoChannelId
d525fc39 836 } as AvailableForListOptions
48dce1c9
C
837 ]
838 }
839
840 return VideoModel.scope(scopes)
d48ff09d
C
841 .findAndCountAll(query)
842 .then(({ rows, count }) => {
843 return {
844 data: rows,
845 total: count
846 }
847 })
93e1258c
C
848 }
849
0b18f4aa
C
850 static async searchAndPopulateAccountAndServer (options: {
851 search: string
852 start?: number
853 count?: number
854 sort?: string
855 startDate?: string // ISO 8601
856 endDate?: string // ISO 8601
857 nsfw?: boolean
858 categoryOneOf?: number[]
859 licenceOneOf?: number[]
860 languageOneOf?: string[]
861 tagsOneOf?: string[]
862 tagsAllOf?: string[]
863 durationMin?: number // seconds
864 durationMax?: number // seconds
865 }) {
d525fc39
C
866 const whereAnd = [ ]
867
868 if (options.startDate || options.endDate) {
869 const publishedAtRange = { }
870
871 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
872 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
873
874 whereAnd.push({ publishedAt: publishedAtRange })
875 }
876
877 if (options.durationMin || options.durationMax) {
878 const durationRange = { }
879
880 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
881 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
882
883 whereAnd.push({ duration: durationRange })
884 }
885
886 whereAnd.push(createSearchTrigramQuery('VideoModel.name', options.search))
887
f05a1c30 888 const query: IFindOptions<VideoModel> = {
57c36b27 889 attributes: {
d525fc39 890 include: [ createSimilarityAttribute('VideoModel.name', options.search) ]
57c36b27 891 },
d525fc39
C
892 offset: options.start,
893 limit: options.count,
894 order: getSort(options.sort),
895 where: {
896 [ Sequelize.Op.and ]: whereAnd
897 }
f05a1c30
C
898 }
899
900 const serverActor = await getServerActor()
48dce1c9
C
901 const scopes = {
902 method: [
903 ScopeNames.AVAILABLE_FOR_LIST, {
904 actorId: serverActor.id,
d525fc39
C
905 nsfw: options.nsfw,
906 categoryOneOf: options.categoryOneOf,
907 licenceOneOf: options.licenceOneOf,
908 languageOneOf: options.languageOneOf,
909 tagsOneOf: options.tagsOneOf,
910 tagsAllOf: options.tagsAllOf
911 } as AvailableForListOptions
48dce1c9
C
912 ]
913 }
f05a1c30 914
48dce1c9 915 return VideoModel.scope(scopes)
244e76a5
RK
916 .findAndCountAll(query)
917 .then(({ rows, count }) => {
f05a1c30
C
918 return {
919 data: rows,
920 total: count
921 }
922 })
923 }
924
3fd3ab2d
C
925 static load (id: number) {
926 return VideoModel.findById(id)
927 }
fdbda9e3 928
3fd3ab2d
C
929 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
930 const query: IFindOptions<VideoModel> = {
931 where: {
932 url
d48ff09d 933 }
3fd3ab2d 934 }
d8755eed 935
3fd3ab2d 936 if (t !== undefined) query.transaction = t
d8755eed 937
4cb6d457 938 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
3fd3ab2d 939 }
d8755eed 940
2ccaeeb3 941 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
3fd3ab2d
C
942 const query: IFindOptions<VideoModel> = {
943 where: {
944 [Sequelize.Op.or]: [
945 { uuid },
946 { url }
947 ]
d48ff09d 948 }
3fd3ab2d 949 }
feb4bdfd 950
3fd3ab2d 951 if (t !== undefined) query.transaction = t
feb4bdfd 952
2ccaeeb3 953 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
72c7248b
C
954 }
955
3fd3ab2d
C
956 static loadAndPopulateAccountAndServerAndTags (id: number) {
957 const options = {
d48ff09d 958 order: [ [ 'Tags', 'name', 'ASC' ] ]
3fd3ab2d 959 }
72c7248b 960
d48ff09d 961 return VideoModel
bbe0f064 962 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
d48ff09d 963 .findById(id, options)
3fd3ab2d 964 }
72c7248b 965
8fa5653a
C
966 static loadByUUID (uuid: string) {
967 const options = {
968 where: {
969 uuid
970 }
971 }
972
973 return VideoModel
974 .scope([ ScopeNames.WITH_FILES ])
975 .findOne(options)
976 }
977
2186386c 978 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
3fd3ab2d
C
979 const options = {
980 order: [ [ 'Tags', 'name', 'ASC' ] ],
981 where: {
982 uuid
2186386c
C
983 },
984 transaction: t
3fd3ab2d 985 }
fd45e8f4 986
d48ff09d 987 return VideoModel
bbe0f064 988 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
da854ddd
C
989 .findOne(options)
990 }
991
09cababd
C
992 static async getStats () {
993 const totalLocalVideos = await VideoModel.count({
994 where: {
995 remote: false
996 }
997 })
998 const totalVideos = await VideoModel.count()
999
1000 let totalLocalVideoViews = await VideoModel.sum('views', {
1001 where: {
1002 remote: false
1003 }
1004 })
1005 // Sequelize could return null...
1006 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1007
1008 return {
1009 totalLocalVideos,
1010 totalLocalVideoViews,
1011 totalVideos
1012 }
1013 }
1014
066e94c5
C
1015 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1016 if (filter && filter === 'local') {
1017 return {
1018 serverId: null
1019 }
1020 }
1021
1022 return {}
1023 }
1024
ae5a3dd6 1025 private static getCategoryLabel (id: number) {
2186386c 1026 return VIDEO_CATEGORIES[id] || 'Misc'
ae5a3dd6
C
1027 }
1028
1029 private static getLicenceLabel (id: number) {
2186386c 1030 return VIDEO_LICENCES[id] || 'Unknown'
ae5a3dd6
C
1031 }
1032
9d3ef9fe 1033 private static getLanguageLabel (id: string) {
2186386c 1034 return VIDEO_LANGUAGES[id] || 'Unknown'
ae5a3dd6
C
1035 }
1036
2243730c 1037 private static getPrivacyLabel (id: number) {
2186386c
C
1038 return VIDEO_PRIVACIES[id] || 'Unknown'
1039 }
2243730c 1040
2186386c
C
1041 private static getStateLabel (id: number) {
1042 return VIDEO_STATES[id] || 'Unknown'
2243730c
C
1043 }
1044
3fd3ab2d
C
1045 getOriginalFile () {
1046 if (Array.isArray(this.VideoFiles) === false) return undefined
aaf61f38 1047
3fd3ab2d
C
1048 // The original file is the file that have the higher resolution
1049 return maxBy(this.VideoFiles, file => file.resolution)
e4f97bab 1050 }
aaf61f38 1051
3fd3ab2d
C
1052 getVideoFilename (videoFile: VideoFileModel) {
1053 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1054 }
165cdc75 1055
3fd3ab2d
C
1056 getThumbnailName () {
1057 // We always have a copy of the thumbnail
1058 const extension = '.jpg'
1059 return this.uuid + extension
7b1f49de
C
1060 }
1061
3fd3ab2d
C
1062 getPreviewName () {
1063 const extension = '.jpg'
1064 return this.uuid + extension
1065 }
7b1f49de 1066
3fd3ab2d
C
1067 getTorrentFileName (videoFile: VideoFileModel) {
1068 const extension = '.torrent'
1069 return this.uuid + '-' + videoFile.resolution + extension
1070 }
8e7f08b5 1071
3fd3ab2d
C
1072 isOwned () {
1073 return this.remote === false
9567011b
C
1074 }
1075
3fd3ab2d 1076 createPreview (videoFile: VideoFileModel) {
3fd3ab2d
C
1077 return generateImageFromVideoFile(
1078 this.getVideoFilePath(videoFile),
1079 CONFIG.STORAGE.PREVIEWS_DIR,
1080 this.getPreviewName(),
26670720 1081 PREVIEWS_SIZE
3fd3ab2d
C
1082 )
1083 }
9567011b 1084
3fd3ab2d 1085 createThumbnail (videoFile: VideoFileModel) {
3fd3ab2d
C
1086 return generateImageFromVideoFile(
1087 this.getVideoFilePath(videoFile),
1088 CONFIG.STORAGE.THUMBNAILS_DIR,
1089 this.getThumbnailName(),
26670720 1090 THUMBNAILS_SIZE
3fd3ab2d 1091 )
14d3270f
C
1092 }
1093
02756fbd
C
1094 getTorrentFilePath (videoFile: VideoFileModel) {
1095 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1096 }
1097
3fd3ab2d
C
1098 getVideoFilePath (videoFile: VideoFileModel) {
1099 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1100 }
14d3270f 1101
81e504b3 1102 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
3fd3ab2d 1103 const options = {
6cced8f9
C
1104 // Keep the extname, it's used by the client to stream the file inside a web browser
1105 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
81e504b3 1106 createdBy: 'PeerTube',
3fd3ab2d 1107 announceList: [
0edf0581
C
1108 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1109 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
3fd3ab2d
C
1110 ],
1111 urlList: [
1112 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1113 ]
1114 }
14d3270f 1115
3fd3ab2d 1116 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
e4f97bab 1117
3fd3ab2d
C
1118 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1119 logger.info('Creating torrent %s.', filePath)
e4f97bab 1120
3fd3ab2d 1121 await writeFilePromise(filePath, torrent)
e4f97bab 1122
3fd3ab2d
C
1123 const parsedTorrent = parseTorrent(torrent)
1124 videoFile.infoHash = parsedTorrent.infoHash
1125 }
e4f97bab 1126
40e87e9e 1127 getEmbedStaticPath () {
3fd3ab2d
C
1128 return '/videos/embed/' + this.uuid
1129 }
e4f97bab 1130
40e87e9e 1131 getThumbnailStaticPath () {
3fd3ab2d 1132 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
e4f97bab 1133 }
227d02fe 1134
40e87e9e 1135 getPreviewStaticPath () {
3fd3ab2d
C
1136 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1137 }
40298b02 1138
2186386c
C
1139 toFormattedJSON (options?: {
1140 additionalAttributes: {
bbe0f064
C
1141 state?: boolean,
1142 waitTranscoding?: boolean,
1143 scheduledUpdate?: boolean
2186386c
C
1144 }
1145 }): Video {
b64c950a 1146 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
0f320037 1147 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
14d3270f 1148
2186386c 1149 const videoObject: Video = {
3fd3ab2d
C
1150 id: this.id,
1151 uuid: this.uuid,
1152 name: this.name,
ae5a3dd6
C
1153 category: {
1154 id: this.category,
1155 label: VideoModel.getCategoryLabel(this.category)
1156 },
1157 licence: {
1158 id: this.licence,
1159 label: VideoModel.getLicenceLabel(this.licence)
1160 },
1161 language: {
1162 id: this.language,
1163 label: VideoModel.getLanguageLabel(this.language)
1164 },
2243730c
C
1165 privacy: {
1166 id: this.privacy,
1167 label: VideoModel.getPrivacyLabel(this.privacy)
1168 },
3fd3ab2d
C
1169 nsfw: this.nsfw,
1170 description: this.getTruncatedDescription(),
3fd3ab2d 1171 isLocal: this.isOwned(),
3fd3ab2d
C
1172 duration: this.duration,
1173 views: this.views,
1174 likes: this.likes,
1175 dislikes: this.dislikes,
40e87e9e
C
1176 thumbnailPath: this.getThumbnailStaticPath(),
1177 previewPath: this.getPreviewStaticPath(),
1178 embedPath: this.getEmbedStaticPath(),
3fd3ab2d 1179 createdAt: this.createdAt,
b64c950a 1180 updatedAt: this.updatedAt,
2922e048 1181 publishedAt: this.publishedAt,
b64c950a 1182 account: {
03e12d7c
C
1183 id: formattedAccount.id,
1184 uuid: formattedAccount.uuid,
b64c950a
C
1185 name: formattedAccount.name,
1186 displayName: formattedAccount.displayName,
1187 url: formattedAccount.url,
1188 host: formattedAccount.host,
1189 avatar: formattedAccount.avatar
0f320037
C
1190 },
1191 channel: {
1192 id: formattedVideoChannel.id,
1193 uuid: formattedVideoChannel.uuid,
1194 name: formattedVideoChannel.name,
1195 displayName: formattedVideoChannel.displayName,
1196 url: formattedVideoChannel.url,
1197 host: formattedVideoChannel.host,
1198 avatar: formattedVideoChannel.avatar
b64c950a 1199 }
2422c46b 1200 }
2186386c
C
1201
1202 if (options) {
bbe0f064 1203 if (options.additionalAttributes.state === true) {
2186386c
C
1204 videoObject.state = {
1205 id: this.state,
1206 label: VideoModel.getStateLabel(this.state)
1207 }
1208 }
1209
bbe0f064 1210 if (options.additionalAttributes.waitTranscoding === true) {
2baea0c7
C
1211 videoObject.waitTranscoding = this.waitTranscoding
1212 }
1213
bbe0f064 1214 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
2baea0c7
C
1215 videoObject.scheduledUpdate = {
1216 updateAt: this.ScheduleVideoUpdate.updateAt,
1217 privacy: this.ScheduleVideoUpdate.privacy || undefined
1218 }
1219 }
2186386c
C
1220 }
1221
1222 return videoObject
14d3270f 1223 }
14d3270f 1224
2422c46b 1225 toFormattedDetailsJSON (): VideoDetails {
bbe0f064
C
1226 const formattedJson = this.toFormattedJSON({
1227 additionalAttributes: {
1228 scheduledUpdate: true
1229 }
1230 })
e4f97bab 1231
3fd3ab2d 1232 const detailsJson = {
2422c46b 1233 support: this.support,
3fd3ab2d
C
1234 descriptionPath: this.getDescriptionPath(),
1235 channel: this.VideoChannel.toFormattedJSON(),
1236 account: this.VideoChannel.Account.toFormattedJSON(),
ee28cdf1 1237 tags: map(this.Tags, 'name'),
47564bbe 1238 commentsEnabled: this.commentsEnabled,
2186386c
C
1239 waitTranscoding: this.waitTranscoding,
1240 state: {
1241 id: this.state,
1242 label: VideoModel.getStateLabel(this.state)
1243 },
3fd3ab2d
C
1244 files: []
1245 }
e4f97bab 1246
3fd3ab2d 1247 // Format and sort video files
244e76a5
RK
1248 detailsJson.files = this.getFormattedVideoFilesJSON()
1249
1250 return Object.assign(formattedJson, detailsJson)
1251 }
1252
1253 getFormattedVideoFilesJSON (): VideoFile[] {
3fd3ab2d 1254 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
3fd3ab2d 1255
244e76a5
RK
1256 return this.VideoFiles
1257 .map(videoFile => {
1258 let resolutionLabel = videoFile.resolution + 'p'
3fd3ab2d 1259
244e76a5
RK
1260 return {
1261 resolution: {
1262 id: videoFile.resolution,
1263 label: resolutionLabel
1264 },
1265 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1266 size: videoFile.size,
3a6f351b 1267 fps: videoFile.fps,
244e76a5 1268 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
02756fbd
C
1269 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1270 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1271 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
244e76a5
RK
1272 } as VideoFile
1273 })
1274 .sort((a, b) => {
1275 if (a.resolution.id < b.resolution.id) return 1
1276 if (a.resolution.id === b.resolution.id) return 0
1277 return -1
1278 })
3fd3ab2d 1279 }
e4f97bab 1280
3fd3ab2d
C
1281 toActivityPubObject (): VideoTorrentObject {
1282 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1283 if (!this.Tags) this.Tags = []
e4f97bab 1284
3fd3ab2d
C
1285 const tag = this.Tags.map(t => ({
1286 type: 'Hashtag' as 'Hashtag',
1287 name: t.name
1288 }))
40298b02 1289
3fd3ab2d
C
1290 let language
1291 if (this.language) {
1292 language = {
9d3ef9fe 1293 identifier: this.language,
ae5a3dd6 1294 name: VideoModel.getLanguageLabel(this.language)
3fd3ab2d
C
1295 }
1296 }
40298b02 1297
3fd3ab2d
C
1298 let category
1299 if (this.category) {
1300 category = {
1301 identifier: this.category + '',
ae5a3dd6 1302 name: VideoModel.getCategoryLabel(this.category)
3fd3ab2d
C
1303 }
1304 }
40298b02 1305
3fd3ab2d
C
1306 let licence
1307 if (this.licence) {
1308 licence = {
1309 identifier: this.licence + '',
ae5a3dd6 1310 name: VideoModel.getLicenceLabel(this.licence)
3fd3ab2d
C
1311 }
1312 }
9567011b 1313
3fd3ab2d
C
1314 const url = []
1315 for (const file of this.VideoFiles) {
1316 url.push({
1317 type: 'Link',
28be8916 1318 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
9fb3abfd 1319 href: this.getVideoFileUrl(file, baseUrlHttp),
3fd3ab2d
C
1320 width: file.resolution,
1321 size: file.size
1322 })
1323
1324 url.push({
1325 type: 'Link',
1326 mimeType: 'application/x-bittorrent',
9fb3abfd 1327 href: this.getTorrentUrl(file, baseUrlHttp),
3fd3ab2d
C
1328 width: file.resolution
1329 })
1330
1331 url.push({
1332 type: 'Link',
1333 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
9fb3abfd 1334 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
3fd3ab2d
C
1335 width: file.resolution
1336 })
1337 }
93e1258c 1338
3fd3ab2d
C
1339 // Add video url too
1340 url.push({
1341 type: 'Link',
1342 mimeType: 'text/html',
9fb3abfd 1343 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
3fd3ab2d 1344 })
93e1258c 1345
40e87e9e
C
1346 const subtitleLanguage = []
1347 for (const caption of this.VideoCaptions) {
1348 subtitleLanguage.push({
1349 identifier: caption.language,
1350 name: VideoCaptionModel.getLanguageLabel(caption.language)
1351 })
1352 }
1353
3fd3ab2d
C
1354 return {
1355 type: 'Video' as 'Video',
1356 id: this.url,
1357 name: this.name,
093237cf 1358 duration: this.getActivityStreamDuration(),
3fd3ab2d
C
1359 uuid: this.uuid,
1360 tag,
1361 category,
1362 licence,
1363 language,
1364 views: this.views,
0a67e28b 1365 sensitive: this.nsfw,
2186386c
C
1366 waitTranscoding: this.waitTranscoding,
1367 state: this.state,
47564bbe 1368 commentsEnabled: this.commentsEnabled,
2922e048 1369 published: this.publishedAt.toISOString(),
3fd3ab2d
C
1370 updated: this.updatedAt.toISOString(),
1371 mediaType: 'text/markdown',
1372 content: this.getTruncatedDescription(),
2422c46b 1373 support: this.support,
40e87e9e 1374 subtitleLanguage,
3fd3ab2d
C
1375 icon: {
1376 type: 'Image',
1377 url: this.getThumbnailUrl(baseUrlHttp),
1378 mediaType: 'image/jpeg',
1379 width: THUMBNAILS_SIZE.width,
1380 height: THUMBNAILS_SIZE.height
1381 },
1382 url,
8fffe21a
C
1383 likes: getVideoLikesActivityPubUrl(this),
1384 dislikes: getVideoDislikesActivityPubUrl(this),
1385 shares: getVideoSharesActivityPubUrl(this),
1386 comments: getVideoCommentsActivityPubUrl(this),
50d6de9c 1387 attributedTo: [
2ccaeeb3
C
1388 {
1389 type: 'Person',
1390 id: this.VideoChannel.Account.Actor.url
fc27b17c
C
1391 },
1392 {
1393 type: 'Group',
1394 id: this.VideoChannel.Actor.url
50d6de9c
C
1395 }
1396 ]
3fd3ab2d
C
1397 }
1398 }
1399
1400 getTruncatedDescription () {
1401 if (!this.description) return null
93e1258c 1402
bffbebbe 1403 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
c73e83da 1404 return peertubeTruncate(this.description, maxLength)
93e1258c
C
1405 }
1406
81e504b3 1407 async optimizeOriginalVideofile () {
3fd3ab2d
C
1408 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1409 const newExtname = '.mp4'
1410 const inputVideoFile = this.getOriginalFile()
1411 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
3a6f351b 1412 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
b769007f 1413
3fd3ab2d
C
1414 const transcodeOptions = {
1415 inputPath: videoInputPath,
3a6f351b 1416 outputPath: videoTranscodedPath
3fd3ab2d 1417 }
c46edbc2 1418
b0ef1782
C
1419 // Could be very long!
1420 await transcode(transcodeOptions)
c46edbc2 1421
b0ef1782 1422 try {
3fd3ab2d 1423 await unlinkPromise(videoInputPath)
c46edbc2 1424
3fd3ab2d
C
1425 // Important to do this before getVideoFilename() to take in account the new file extension
1426 inputVideoFile.set('extname', newExtname)
e71bcc0f 1427
3a6f351b
C
1428 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1429 await renamePromise(videoTranscodedPath, videoOutputPath)
1430 const stats = await statPromise(videoOutputPath)
1431 const fps = await getVideoFileFPS(videoOutputPath)
e71bcc0f 1432
3fd3ab2d 1433 inputVideoFile.set('size', stats.size)
3a6f351b 1434 inputVideoFile.set('fps', fps)
e71bcc0f 1435
3fd3ab2d
C
1436 await this.createTorrentAndSetInfoHash(inputVideoFile)
1437 await inputVideoFile.save()
fd45e8f4 1438
3fd3ab2d
C
1439 } catch (err) {
1440 // Auto destruction...
d5b7d911 1441 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
fd45e8f4 1442
3fd3ab2d
C
1443 throw err
1444 }
feb4bdfd
C
1445 }
1446
81e504b3 1447 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
3fd3ab2d
C
1448 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1449 const extname = '.mp4'
aaf61f38 1450
3fd3ab2d
C
1451 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1452 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
feb4bdfd 1453
3fd3ab2d
C
1454 const newVideoFile = new VideoFileModel({
1455 resolution,
1456 extname,
1457 size: 0,
1458 videoId: this.id
1459 })
1460 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
a041b171 1461
3fd3ab2d
C
1462 const transcodeOptions = {
1463 inputPath: videoInputPath,
1464 outputPath: videoOutputPath,
056aa7f2
C
1465 resolution,
1466 isPortraitMode
3fd3ab2d 1467 }
a041b171 1468
3fd3ab2d 1469 await transcode(transcodeOptions)
a041b171 1470
3fd3ab2d 1471 const stats = await statPromise(videoOutputPath)
3a6f351b 1472 const fps = await getVideoFileFPS(videoOutputPath)
d7d5611c 1473
3fd3ab2d 1474 newVideoFile.set('size', stats.size)
3a6f351b 1475 newVideoFile.set('fps', fps)
d7d5611c 1476
3fd3ab2d 1477 await this.createTorrentAndSetInfoHash(newVideoFile)
d7d5611c 1478
3fd3ab2d
C
1479 await newVideoFile.save()
1480
1481 this.VideoFiles.push(newVideoFile)
0d0e8dd0
C
1482 }
1483
0138af92 1484 async importVideoFile (inputFilePath: string) {
3a6f351b
C
1485 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1486 const { size } = await statPromise(inputFilePath)
1487 const fps = await getVideoFileFPS(inputFilePath)
1488
0138af92 1489 let updatedVideoFile = new VideoFileModel({
3a6f351b 1490 resolution: videoFileResolution,
0138af92 1491 extname: extname(inputFilePath),
3a6f351b
C
1492 size,
1493 fps,
0138af92
FF
1494 videoId: this.id
1495 })
1496
0138af92 1497 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
0138af92 1498
28be8916
C
1499 if (currentVideoFile) {
1500 // Remove old file and old torrent
1501 await this.removeFile(currentVideoFile)
1502 await this.removeTorrent(currentVideoFile)
1503 // Remove the old video file from the array
1504 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1505
1506 // Update the database
1507 currentVideoFile.set('extname', updatedVideoFile.extname)
0138af92 1508 currentVideoFile.set('size', updatedVideoFile.size)
3a6f351b 1509 currentVideoFile.set('fps', updatedVideoFile.fps)
28be8916 1510
0138af92
FF
1511 updatedVideoFile = currentVideoFile
1512 }
1513
6ccdf3a2
C
1514 const outputPath = this.getVideoFilePath(updatedVideoFile)
1515 await copyFilePromise(inputFilePath, outputPath)
1516
0138af92
FF
1517 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1518
1519 await updatedVideoFile.save()
1520
28be8916 1521 this.VideoFiles.push(updatedVideoFile)
0138af92
FF
1522 }
1523
056aa7f2 1524 getOriginalFileResolution () {
3fd3ab2d 1525 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
0d0e8dd0 1526
056aa7f2 1527 return getVideoFileResolution(originalFilePath)
3fd3ab2d 1528 }
0d0e8dd0 1529
3fd3ab2d
C
1530 getDescriptionPath () {
1531 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1532 }
1533
3fd3ab2d
C
1534 removeThumbnail () {
1535 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1536 return unlinkPromise(thumbnailPath)
feb4bdfd
C
1537 }
1538
3fd3ab2d
C
1539 removePreview () {
1540 // Same name than video thumbnail
1541 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
7920c273
C
1542 }
1543
3fd3ab2d
C
1544 removeFile (videoFile: VideoFileModel) {
1545 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1546 return unlinkPromise(filePath)
feb4bdfd
C
1547 }
1548
3fd3ab2d
C
1549 removeTorrent (videoFile: VideoFileModel) {
1550 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1551 return unlinkPromise(torrentPath)
aaf61f38
C
1552 }
1553
093237cf
C
1554 getActivityStreamDuration () {
1555 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1556 return 'PT' + this.duration + 'S'
1557 }
1558
3fd3ab2d
C
1559 private getBaseUrls () {
1560 let baseUrlHttp
1561 let baseUrlWs
7920c273 1562
3fd3ab2d
C
1563 if (this.isOwned()) {
1564 baseUrlHttp = CONFIG.WEBSERVER.URL
1565 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1566 } else {
50d6de9c
C
1567 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1568 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
6fcd19ba 1569 }
aaf61f38 1570
3fd3ab2d 1571 return { baseUrlHttp, baseUrlWs }
15d4ee04 1572 }
a96aed15 1573
3fd3ab2d
C
1574 private getThumbnailUrl (baseUrlHttp: string) {
1575 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
a96aed15
C
1576 }
1577
3fd3ab2d
C
1578 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1579 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1580 }
e4f97bab 1581
02756fbd
C
1582 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1583 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1584 }
1585
3fd3ab2d
C
1586 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1587 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1588 }
a96aed15 1589
02756fbd
C
1590 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1591 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1592 }
1593
3fd3ab2d
C
1594 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1595 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1596 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1597 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1598
1599 const magnetHash = {
1600 xs,
1601 announce,
1602 urlList,
1603 infoHash: videoFile.infoHash,
1604 name: this.name
1605 }
a96aed15 1606
3fd3ab2d 1607 return magnetUtil.encode(magnetHash)
a96aed15 1608 }
a96aed15 1609}