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