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