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