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