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