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