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