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