]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Update changelog
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
CommitLineData
39445ead 1import * as Bluebird from 'bluebird'
92e0f42e 2import { maxBy, minBy } from 'lodash'
098eb377 3import { join } from 'path'
1735c825
C
4import {
5 CountOptions,
6 FindOptions,
7 IncludeOptions,
8 ModelIndexesOptions,
9 Op,
10 QueryTypes,
11 ScopeOptions,
12 Sequelize,
13 Transaction,
14 WhereOptions
15} from 'sequelize'
3fd3ab2d 16import {
4ba3b8ea
C
17 AllowNull,
18 BeforeDestroy,
19 BelongsTo,
20 BelongsToMany,
21 Column,
22 CreatedAt,
23 DataType,
24 Default,
25 ForeignKey,
26 HasMany,
2baea0c7 27 HasOne,
4ba3b8ea
C
28 Is,
29 IsInt,
30 IsUUID,
31 Min,
32 Model,
33 Scopes,
34 Table,
9a629c6e 35 UpdatedAt
3fd3ab2d 36} from 'sequelize-typescript'
453e83ea 37import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
3fd3ab2d 38import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
d7a25329 39import { Video, VideoDetails } from '../../../shared/models/videos'
066e94c5 40import { VideoFilter } from '../../../shared/models/videos/video-query.type'
30ff39e7 41import { peertubeTruncate } from '../../helpers/core-utils'
da854ddd 42import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
d7a25329 43import { isBooleanValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 44import {
4ba3b8ea
C
45 isVideoCategoryValid,
46 isVideoDescriptionValid,
47 isVideoDurationValid,
48 isVideoLanguageValid,
49 isVideoLicenceValid,
418d092a 50 isVideoNameValid,
2baea0c7
C
51 isVideoPrivacyValid,
52 isVideoStateValid,
b64c950a 53 isVideoSupportValid
3fd3ab2d 54} from '../../helpers/custom-validators/videos'
1735c825 55import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
da854ddd 56import { logger } from '../../helpers/logger'
f05a1c30 57import { getServerActor } from '../../helpers/utils'
65fcc311 58import {
1297eb5d 59 ACTIVITY_PUB,
4ba3b8ea 60 API_VERSION,
418d092a 61 CONSTRAINTS_FIELDS,
557b13ae 62 LAZY_STATIC_PATHS,
4ba3b8ea 63 REMOTE_SCHEME,
02756fbd 64 STATIC_DOWNLOAD_PATHS,
4ba3b8ea 65 STATIC_PATHS,
4ba3b8ea
C
66 VIDEO_CATEGORIES,
67 VIDEO_LANGUAGES,
68 VIDEO_LICENCES,
2baea0c7 69 VIDEO_PRIVACIES,
6dd9de95
C
70 VIDEO_STATES,
71 WEBSERVER
74dc3bca 72} from '../../initializers/constants'
50d6de9c 73import { sendDeleteVideo } from '../../lib/activitypub/send'
3fd3ab2d
C
74import { AccountModel } from '../account/account'
75import { AccountVideoRateModel } from '../account/account-video-rate'
50d6de9c 76import { ActorModel } from '../activitypub/actor'
b6a4fd6b 77import { AvatarModel } from '../avatar/avatar'
3fd3ab2d 78import { ServerModel } from '../server/server'
418d092a
C
79import {
80 buildBlockedAccountSQL,
81 buildTrigramSearchIndex,
82 buildWhereIdOrUUID,
3caf77d3 83 createSafeIn,
418d092a 84 createSimilarityAttribute,
6dd9de95
C
85 getVideoSort,
86 isOutdated,
418d092a
C
87 throwIfNotValid
88} from '../utils'
3fd3ab2d
C
89import { TagModel } from './tag'
90import { VideoAbuseModel } from './video-abuse'
bfbd9128 91import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
da854ddd 92import { VideoCommentModel } from './video-comment'
3fd3ab2d
C
93import { VideoFileModel } from './video-file'
94import { VideoShareModel } from './video-share'
95import { VideoTagModel } from './video-tag'
2baea0c7 96import { ScheduleVideoUpdateModel } from './schedule-video-update'
40e87e9e 97import { VideoCaptionModel } from './video-caption'
26b7305a 98import { VideoBlacklistModel } from './video-blacklist'
d7a25329 99import { remove } from 'fs-extra'
9a629c6e 100import { VideoViewModel } from './video-views'
c48e82b5 101import { VideoRedundancyModel } from '../redundancy/video-redundancy'
098eb377
C
102import {
103 videoFilesModelToFormattedJSON,
104 VideoFormattingJSONOptions,
105 videoModelToActivityPubObject,
106 videoModelToFormattedDetailsJSON,
107 videoModelToFormattedJSON
108} from './video-format-utils'
6e46de09 109import { UserVideoHistoryModel } from '../account/user-video-history'
dc133480 110import { VideoImportModel } from './video-import'
09209296 111import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
418d092a 112import { VideoPlaylistElementModel } from './video-playlist-element'
6dd9de95 113import { CONFIG } from '../../initializers/config'
e8bafea3
C
114import { ThumbnailModel } from './thumbnail'
115import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
e2600d8b 116import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
453e83ea
C
117import {
118 MChannel,
0283eaac 119 MChannelAccountDefault,
453e83ea 120 MChannelId,
d7a25329
C
121 MStreamingPlaylist,
122 MStreamingPlaylistFilesVideo,
453e83ea
C
123 MUserAccountId,
124 MUserId,
453e83ea 125 MVideoAccountLight,
0283eaac 126 MVideoAccountLightBlacklistAllFiles,
b5fecbf4 127 MVideoAP,
453e83ea 128 MVideoDetails,
d7a25329 129 MVideoFileVideo,
b5fecbf4
C
130 MVideoFormattable,
131 MVideoFormattableDetails,
0283eaac 132 MVideoForUser,
453e83ea
C
133 MVideoFullLight,
134 MVideoIdThumbnail,
135 MVideoThumbnail,
d636ab58 136 MVideoThumbnailBlacklist,
b5fecbf4
C
137 MVideoWithAllFiles,
138 MVideoWithFile,
139 MVideoWithRights
453e83ea 140} from '../../typings/models'
d7a25329 141import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../typings/models/video/video-file'
453e83ea 142import { MThumbnail } from '../../typings/models/video/thumbnail'
d7a25329 143import { VideoFile } from '@shared/models/videos/video-file.model'
3cf53828 144import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
7cde3b9c 145import validator from 'validator'
6e46de09 146
57c36b27 147// FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
1735c825 148const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
57c36b27
C
149 buildTrigramSearchIndex('video_name_trigram', 'name'),
150
8cd72bd3 151 { fields: [ 'createdAt' ] },
611a72ae
C
152 {
153 fields: [
154 { name: 'publishedAt', order: 'DESC' },
155 { name: 'id', order: 'ASC' }
156 ]
157 },
8cd72bd3 158 { fields: [ 'duration' ] },
8cd72bd3 159 { fields: [ 'views' ] },
8cd72bd3 160 { fields: [ 'channelId' ] },
7519127b
C
161 {
162 fields: [ 'originallyPublishedAt' ],
163 where: {
164 originallyPublishedAt: {
1735c825 165 [Op.ne]: null
7519127b
C
166 }
167 }
168 },
439b1744
C
169 {
170 fields: [ 'category' ], // We don't care videos with an unknown category
171 where: {
172 category: {
1735c825 173 [Op.ne]: null
439b1744
C
174 }
175 }
176 },
177 {
178 fields: [ 'licence' ], // We don't care videos with an unknown licence
179 where: {
180 licence: {
1735c825 181 [Op.ne]: null
439b1744
C
182 }
183 }
184 },
185 {
186 fields: [ 'language' ], // We don't care videos with an unknown language
187 where: {
188 language: {
1735c825 189 [Op.ne]: null
439b1744
C
190 }
191 }
192 },
193 {
194 fields: [ 'nsfw' ], // Most of the videos are not NSFW
195 where: {
196 nsfw: true
197 }
198 },
199 {
200 fields: [ 'remote' ], // Only index local videos
201 where: {
202 remote: false
203 }
204 },
57c36b27 205 {
8cd72bd3
C
206 fields: [ 'uuid' ],
207 unique: true
57c36b27
C
208 },
209 {
8ea6f49a 210 fields: [ 'url' ],
57c36b27
C
211 unique: true
212 }
213]
214
2baea0c7 215export enum ScopeNames {
afd2cba5
C
216 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
217 FOR_API = 'FOR_API',
4cb6d457 218 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d 219 WITH_TAGS = 'WITH_TAGS',
d7a25329 220 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
191764f3 221 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
6e46de09 222 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
09209296
C
223 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
224 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
e8bafea3
C
225 WITH_USER_ID = 'WITH_USER_ID',
226 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
d48ff09d
C
227}
228
bfbd9128
C
229export type ForAPIOptions = {
230 ids?: number[]
418d092a
C
231
232 videoPlaylistId?: number
233
afd2cba5 234 withFiles?: boolean
bfbd9128
C
235
236 withAccountBlockerIds?: number[]
afd2cba5
C
237}
238
bfbd9128 239export type AvailableForListIDsOptions = {
7ad9b984 240 serverAccountId: number
4e74e803 241 followerActorId: number
afd2cba5 242 includeLocalVideos: boolean
418d092a 243
bfbd9128 244 attributesType?: 'none' | 'id' | 'all'
8519cc92 245
afd2cba5
C
246 filter?: VideoFilter
247 categoryOneOf?: number[]
248 nsfw?: boolean
249 licenceOneOf?: number[]
250 languageOneOf?: string[]
251 tagsOneOf?: string[]
252 tagsAllOf?: string[]
418d092a 253
afd2cba5 254 withFiles?: boolean
418d092a 255
afd2cba5 256 accountId?: number
d525fc39 257 videoChannelId?: number
418d092a
C
258
259 videoPlaylistId?: number
260
9a629c6e 261 trendingDays?: number
453e83ea
C
262 user?: MUserAccountId
263 historyOfUser?: MUserId
3caf77d3
C
264
265 baseWhere?: WhereOptions[]
d525fc39
C
266}
267
3acc5084 268@Scopes(() => ({
8ea6f49a 269 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
1735c825 270 const query: FindOptions = {
418d092a
C
271 include: [
272 {
bfbd9128
C
273 model: VideoChannelModel.scope({
274 method: [
275 VideoChannelScopeNames.SUMMARY, {
276 withAccount: true,
277 withAccountBlockerIds: options.withAccountBlockerIds
278 } as SummaryOptions
279 ]
280 }),
76564702 281 required: true
2fb5b3a5
C
282 },
283 {
284 attributes: [ 'type', 'filename' ],
285 model: ThumbnailModel,
286 required: false
418d092a
C
287 }
288 ]
afd2cba5
C
289 }
290
bfbd9128
C
291 if (options.ids) {
292 query.where = {
293 id: {
294 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
295 }
296 }
297 }
298
afd2cba5
C
299 if (options.withFiles === true) {
300 query.include.push({
301 model: VideoFileModel.unscoped(),
302 required: true
303 })
304 }
305
418d092a
C
306 if (options.videoPlaylistId) {
307 query.include.push({
308 model: VideoPlaylistElementModel.unscoped(),
15e9d5ca
C
309 required: true,
310 where: {
311 videoPlaylistId: options.videoPlaylistId
312 }
418d092a
C
313 })
314 }
315
afd2cba5
C
316 return query
317 },
8ea6f49a 318 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
def2a70b 319 const whereAnd = options.baseWhere ? [].concat(options.baseWhere) : []
8519cc92 320
1735c825 321 const query: FindOptions = {
2b62cccd 322 raw: true,
1cd3facc
C
323 include: []
324 }
325
bfbd9128
C
326 const attributesType = options.attributesType || 'id'
327
328 if (attributesType === 'id') query.attributes = [ 'id' ]
329 else if (attributesType === 'none') query.attributes = [ ]
330
3caf77d3
C
331 whereAnd.push({
332 id: {
333 [ Op.notIn ]: Sequelize.literal(
334 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
335 )
336 }
337 })
338
bfbd9128
C
339 if (options.serverAccountId) {
340 whereAnd.push({
341 channelId: {
342 [ Op.notIn ]: Sequelize.literal(
343 '(' +
344 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
345 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
346 ')' +
347 ')'
348 )
349 }
350 })
351 }
3caf77d3 352
1cd3facc
C
353 // Only list public/published videos
354 if (!options.filter || options.filter !== 'all-local') {
22a73cb8
C
355
356 const publishWhere = {
2186386c 357 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
1735c825 358 [ Op.or ]: [
2186386c
C
359 {
360 state: VideoState.PUBLISHED
361 },
362 {
1735c825 363 [ Op.and ]: {
2186386c
C
364 state: VideoState.TO_TRANSCODE,
365 waitTranscoding: false
366 }
367 }
368 ]
1cd3facc 369 }
22a73cb8 370 whereAnd.push(publishWhere)
1cd3facc 371
22a73cb8
C
372 // List internal videos if the user is logged in
373 if (options.user) {
374 const privacyWhere = {
375 [Op.or]: [
376 {
377 privacy: VideoPrivacy.INTERNAL
378 },
379 {
380 privacy: VideoPrivacy.PUBLIC
381 }
382 ]
383 }
384
385 whereAnd.push(privacyWhere)
386 } else { // Or only public videos
387 const privacyWhere = { privacy: VideoPrivacy.PUBLIC }
388 whereAnd.push(privacyWhere)
389 }
afd2cba5
C
390 }
391
418d092a
C
392 if (options.videoPlaylistId) {
393 query.include.push({
394 attributes: [],
395 model: VideoPlaylistElementModel.unscoped(),
396 required: true,
397 where: {
398 videoPlaylistId: options.videoPlaylistId
399 }
400 })
15e9d5ca
C
401
402 query.subQuery = false
418d092a
C
403 }
404
0dfee3a3
C
405 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
406 whereAnd.push({
407 remote: false
408 })
409 }
410
411 if (options.accountId || options.videoChannelId) {
1735c825 412 const videoChannelInclude: IncludeOptions = {
afd2cba5
C
413 attributes: [],
414 model: VideoChannelModel.unscoped(),
415 required: true
416 }
417
418 if (options.videoChannelId) {
419 videoChannelInclude.where = {
420 id: options.videoChannelId
421 }
422 }
423
0dfee3a3 424 if (options.accountId) {
1735c825 425 const accountInclude: IncludeOptions = {
afd2cba5
C
426 attributes: [],
427 model: AccountModel.unscoped(),
428 required: true
429 }
430
0dfee3a3 431 accountInclude.where = { id: options.accountId }
afd2cba5
C
432 videoChannelInclude.include = [ accountInclude ]
433 }
434
435 query.include.push(videoChannelInclude)
244e76a5
RK
436 }
437
4e74e803 438 if (options.followerActorId) {
1c5fed88 439 let localVideosReq: WhereOptions = {}
687d638c 440 if (options.includeLocalVideos === true) {
1c5fed88 441 localVideosReq = { remote: false }
687d638c
C
442 }
443
444 // Force actorId to be a number to avoid SQL injections
4e74e803 445 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
3caf77d3 446 whereAnd.push({
1c5fed88
C
447 [Op.or]: [
448 {
449 id: {
450 [ Op.in ]: Sequelize.literal(
451 '(' +
452 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
453 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
454 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
8ee988c3
C
455 ')'
456 )
457 }
458 },
459 {
460 id: {
461 [ Op.in ]: Sequelize.literal(
462 '(' +
1c5fed88
C
463 'SELECT "video"."id" AS "id" FROM "video" ' +
464 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
465 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
466 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
467 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
468 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
469 ')'
470 )
471 }
472 },
473 localVideosReq
474 ]
b6314e3c 475 })
687d638c
C
476 }
477
48dce1c9 478 if (options.withFiles === true) {
3caf77d3
C
479 whereAnd.push({
480 id: {
481 [ Op.in ]: Sequelize.literal(
482 '(SELECT "videoId" FROM "videoFile")'
483 )
484 }
244e76a5
RK
485 })
486 }
487
d525fc39
C
488 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
489 if (options.tagsAllOf || options.tagsOneOf) {
d525fc39 490 if (options.tagsOneOf) {
4b1f1b81
C
491 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
492
3caf77d3
C
493 whereAnd.push({
494 id: {
495 [ Op.in ]: Sequelize.literal(
496 '(' +
497 'SELECT "videoId" FROM "videoTag" ' +
498 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
4b1f1b81 499 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
3caf77d3
C
500 ')'
501 )
502 }
b6314e3c 503 })
d525fc39
C
504 }
505
506 if (options.tagsAllOf) {
4b1f1b81
C
507 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
508
3caf77d3
C
509 whereAnd.push({
510 id: {
511 [ Op.in ]: Sequelize.literal(
512 '(' +
513 'SELECT "videoId" FROM "videoTag" ' +
514 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
4b1f1b81
C
515 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
516 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
3caf77d3
C
517 ')'
518 )
519 }
b6314e3c 520 })
d525fc39
C
521 }
522 }
523
524 if (options.nsfw === true || options.nsfw === false) {
3caf77d3 525 whereAnd.push({ nsfw: options.nsfw })
d525fc39
C
526 }
527
528 if (options.categoryOneOf) {
3caf77d3
C
529 whereAnd.push({
530 category: {
531 [ Op.or ]: options.categoryOneOf
532 }
533 })
d525fc39
C
534 }
535
536 if (options.licenceOneOf) {
3caf77d3
C
537 whereAnd.push({
538 licence: {
539 [ Op.or ]: options.licenceOneOf
540 }
541 })
0883b324
C
542 }
543
d525fc39 544 if (options.languageOneOf) {
3caf77d3
C
545 let videoLanguages = options.languageOneOf
546 if (options.languageOneOf.find(l => l === '_unknown')) {
547 videoLanguages = videoLanguages.concat([ null ])
d525fc39 548 }
3caf77d3
C
549
550 whereAnd.push({
551 [Op.or]: [
552 {
553 language: {
554 [ Op.or ]: videoLanguages
555 }
556 },
557 {
558 id: {
559 [ Op.in ]: Sequelize.literal(
560 '(' +
561 'SELECT "videoId" FROM "videoCaption" ' +
562 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
563 ')'
564 )
565 }
566 }
567 ]
568 })
61b909b9
P
569 }
570
9a629c6e 571 if (options.trendingDays) {
b36f41ca 572 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
9a629c6e
C
573
574 query.subQuery = false
575 }
576
8b9a525a
C
577 if (options.historyOfUser) {
578 query.include.push({
579 model: UserVideoHistoryModel,
580 required: true,
581 where: {
582 userId: options.historyOfUser.id
583 }
584 })
80bfd33c
C
585
586 // Even if the relation is n:m, we know that a user only have 0..1 video history
587 // So we won't have multiple rows for the same video
588 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
589 query.subQuery = false
8b9a525a
C
590 }
591
3caf77d3
C
592 query.where = {
593 [ Op.and ]: whereAnd
594 }
595
244e76a5
RK
596 return query
597 },
e8bafea3
C
598 [ ScopeNames.WITH_THUMBNAILS ]: {
599 include: [
600 {
3acc5084 601 model: ThumbnailModel,
e8bafea3
C
602 required: false
603 }
604 ]
605 },
09209296
C
606 [ ScopeNames.WITH_USER_ID ]: {
607 include: [
608 {
609 attributes: [ 'accountId' ],
3acc5084 610 model: VideoChannelModel.unscoped(),
09209296
C
611 required: true,
612 include: [
613 {
614 attributes: [ 'userId' ],
3acc5084 615 model: AccountModel.unscoped(),
09209296
C
616 required: true
617 }
618 ]
619 }
3acc5084 620 ]
09209296 621 },
8ea6f49a 622 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
d48ff09d
C
623 include: [
624 {
3acc5084 625 model: VideoChannelModel.unscoped(),
d48ff09d
C
626 required: true,
627 include: [
6120941f
C
628 {
629 attributes: {
630 exclude: [ 'privateKey', 'publicKey' ]
631 },
3acc5084 632 model: ActorModel.unscoped(),
3e500247
C
633 required: true,
634 include: [
635 {
636 attributes: [ 'host' ],
3acc5084 637 model: ServerModel.unscoped(),
3e500247 638 required: false
52d9f792
C
639 },
640 {
3acc5084 641 model: AvatarModel.unscoped(),
52d9f792 642 required: false
3e500247
C
643 }
644 ]
6120941f 645 },
d48ff09d 646 {
3acc5084 647 model: AccountModel.unscoped(),
d48ff09d
C
648 required: true,
649 include: [
650 {
3acc5084 651 model: ActorModel.unscoped(),
6120941f
C
652 attributes: {
653 exclude: [ 'privateKey', 'publicKey' ]
654 },
50d6de9c
C
655 required: true,
656 include: [
657 {
3e500247 658 attributes: [ 'host' ],
3acc5084 659 model: ServerModel.unscoped(),
50d6de9c 660 required: false
b6a4fd6b
C
661 },
662 {
3acc5084 663 model: AvatarModel.unscoped(),
b6a4fd6b 664 required: false
50d6de9c
C
665 }
666 ]
d48ff09d
C
667 }
668 ]
669 }
670 ]
671 }
3acc5084 672 ]
d48ff09d 673 },
8ea6f49a 674 [ ScopeNames.WITH_TAGS ]: {
3acc5084 675 include: [ TagModel ]
d48ff09d 676 },
8ea6f49a 677 [ ScopeNames.WITH_BLACKLISTED ]: {
191764f3
C
678 include: [
679 {
453e83ea 680 attributes: [ 'id', 'reason', 'unfederated' ],
3acc5084 681 model: VideoBlacklistModel,
191764f3
C
682 required: false
683 }
684 ]
685 },
d7a25329 686 [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => {
09209296
C
687 let subInclude: any[] = []
688
689 if (withRedundancies === true) {
690 subInclude = [
691 {
692 attributes: [ 'fileUrl' ],
693 model: VideoRedundancyModel.unscoped(),
694 required: false
695 }
696 ]
697 }
698
699 return {
700 include: [
701 {
702 model: VideoFileModel.unscoped(),
3acc5084 703 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
09209296
C
704 required: false,
705 include: subInclude
706 }
707 ]
708 }
709 },
710 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
d7a25329
C
711 const subInclude: IncludeOptions[] = [
712 {
713 model: VideoFileModel.unscoped(),
714 required: false
715 }
716 ]
09209296
C
717
718 if (withRedundancies === true) {
d7a25329
C
719 subInclude.push({
720 attributes: [ 'fileUrl' ],
721 model: VideoRedundancyModel.unscoped(),
722 required: false
723 })
09209296
C
724 }
725
726 return {
727 include: [
728 {
729 model: VideoStreamingPlaylistModel.unscoped(),
3acc5084 730 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
09209296
C
731 required: false,
732 include: subInclude
733 }
734 ]
735 }
bbe0f064 736 },
8ea6f49a 737 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
bbe0f064
C
738 include: [
739 {
3acc5084 740 model: ScheduleVideoUpdateModel.unscoped(),
bbe0f064
C
741 required: false
742 }
743 ]
6e46de09
C
744 },
745 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
746 return {
747 include: [
748 {
749 attributes: [ 'currentTime' ],
750 model: UserVideoHistoryModel.unscoped(),
751 required: false,
752 where: {
753 userId
754 }
755 }
756 ]
757 }
d48ff09d 758 }
3acc5084 759}))
3fd3ab2d
C
760@Table({
761 tableName: 'video',
57c36b27 762 indexes
3fd3ab2d
C
763})
764export class VideoModel extends Model<VideoModel> {
765
766 @AllowNull(false)
767 @Default(DataType.UUIDV4)
768 @IsUUID(4)
769 @Column(DataType.UUID)
770 uuid: string
771
772 @AllowNull(false)
773 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
774 @Column
775 name: string
776
777 @AllowNull(true)
778 @Default(null)
1735c825 779 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
3fd3ab2d
C
780 @Column
781 category: number
782
783 @AllowNull(true)
784 @Default(null)
1735c825 785 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
3fd3ab2d
C
786 @Column
787 licence: number
788
789 @AllowNull(true)
790 @Default(null)
1735c825 791 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
9d3ef9fe
C
792 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
793 language: string
3fd3ab2d
C
794
795 @AllowNull(false)
796 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
797 @Column
798 privacy: number
799
800 @AllowNull(false)
47564bbe 801 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
802 @Column
803 nsfw: boolean
804
805 @AllowNull(true)
806 @Default(null)
1735c825 807 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
3fd3ab2d
C
808 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
809 description: string
810
2422c46b
C
811 @AllowNull(true)
812 @Default(null)
1735c825 813 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
2422c46b
C
814 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
815 support: string
816
3fd3ab2d
C
817 @AllowNull(false)
818 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
819 @Column
820 duration: number
821
822 @AllowNull(false)
823 @Default(0)
824 @IsInt
825 @Min(0)
826 @Column
827 views: number
828
829 @AllowNull(false)
830 @Default(0)
831 @IsInt
832 @Min(0)
833 @Column
834 likes: number
835
836 @AllowNull(false)
837 @Default(0)
838 @IsInt
839 @Min(0)
840 @Column
841 dislikes: number
842
843 @AllowNull(false)
844 @Column
845 remote: boolean
846
847 @AllowNull(false)
848 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
849 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
850 url: string
851
47564bbe
C
852 @AllowNull(false)
853 @Column
854 commentsEnabled: boolean
855
156c50af
LD
856 @AllowNull(false)
857 @Column
7f2cfe3a 858 downloadEnabled: boolean
156c50af 859
2186386c
C
860 @AllowNull(false)
861 @Column
862 waitTranscoding: boolean
863
864 @AllowNull(false)
865 @Default(null)
866 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
867 @Column
868 state: VideoState
869
3fd3ab2d
C
870 @CreatedAt
871 createdAt: Date
872
873 @UpdatedAt
874 updatedAt: Date
875
2922e048 876 @AllowNull(false)
1735c825 877 @Default(DataType.NOW)
2922e048
JLB
878 @Column
879 publishedAt: Date
880
7519127b
C
881 @AllowNull(true)
882 @Default(null)
c8034165 883 @Column
884 originallyPublishedAt: Date
885
3fd3ab2d
C
886 @ForeignKey(() => VideoChannelModel)
887 @Column
888 channelId: number
889
890 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 891 foreignKey: {
50d6de9c 892 allowNull: true
feb4bdfd 893 },
6b738c7a 894 hooks: true
feb4bdfd 895 })
3fd3ab2d 896 VideoChannel: VideoChannelModel
7920c273 897
3fd3ab2d 898 @BelongsToMany(() => TagModel, {
7920c273 899 foreignKey: 'videoId',
3fd3ab2d
C
900 through: () => VideoTagModel,
901 onDelete: 'CASCADE'
7920c273 902 })
3fd3ab2d 903 Tags: TagModel[]
55fa55a9 904
e8bafea3
C
905 @HasMany(() => ThumbnailModel, {
906 foreignKey: {
907 name: 'videoId',
908 allowNull: true
909 },
910 hooks: true,
911 onDelete: 'cascade'
912 })
913 Thumbnails: ThumbnailModel[]
914
418d092a
C
915 @HasMany(() => VideoPlaylistElementModel, {
916 foreignKey: {
917 name: 'videoId',
bfbd9128 918 allowNull: true
418d092a 919 },
bfbd9128 920 onDelete: 'set null'
418d092a
C
921 })
922 VideoPlaylistElements: VideoPlaylistElementModel[]
923
3fd3ab2d 924 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
925 foreignKey: {
926 name: 'videoId',
927 allowNull: false
928 },
929 onDelete: 'cascade'
930 })
3fd3ab2d 931 VideoAbuses: VideoAbuseModel[]
93e1258c 932
3fd3ab2d 933 @HasMany(() => VideoFileModel, {
93e1258c
C
934 foreignKey: {
935 name: 'videoId',
d7a25329 936 allowNull: true
93e1258c 937 },
c48e82b5 938 hooks: true,
93e1258c
C
939 onDelete: 'cascade'
940 })
3fd3ab2d 941 VideoFiles: VideoFileModel[]
e71bcc0f 942
09209296
C
943 @HasMany(() => VideoStreamingPlaylistModel, {
944 foreignKey: {
945 name: 'videoId',
946 allowNull: false
947 },
948 hooks: true,
949 onDelete: 'cascade'
950 })
951 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
952
3fd3ab2d 953 @HasMany(() => VideoShareModel, {
e71bcc0f
C
954 foreignKey: {
955 name: 'videoId',
956 allowNull: false
957 },
958 onDelete: 'cascade'
959 })
3fd3ab2d 960 VideoShares: VideoShareModel[]
16b90975 961
3fd3ab2d 962 @HasMany(() => AccountVideoRateModel, {
16b90975
C
963 foreignKey: {
964 name: 'videoId',
965 allowNull: false
966 },
967 onDelete: 'cascade'
968 })
3fd3ab2d 969 AccountVideoRates: AccountVideoRateModel[]
f285faa0 970
da854ddd
C
971 @HasMany(() => VideoCommentModel, {
972 foreignKey: {
973 name: 'videoId',
974 allowNull: false
975 },
f05a1c30
C
976 onDelete: 'cascade',
977 hooks: true
da854ddd
C
978 })
979 VideoComments: VideoCommentModel[]
980
9a629c6e
C
981 @HasMany(() => VideoViewModel, {
982 foreignKey: {
983 name: 'videoId',
984 allowNull: false
985 },
6e46de09 986 onDelete: 'cascade'
9a629c6e
C
987 })
988 VideoViews: VideoViewModel[]
989
6e46de09
C
990 @HasMany(() => UserVideoHistoryModel, {
991 foreignKey: {
992 name: 'videoId',
993 allowNull: false
994 },
995 onDelete: 'cascade'
996 })
997 UserVideoHistories: UserVideoHistoryModel[]
998
2baea0c7
C
999 @HasOne(() => ScheduleVideoUpdateModel, {
1000 foreignKey: {
1001 name: 'videoId',
1002 allowNull: false
1003 },
1004 onDelete: 'cascade'
1005 })
1006 ScheduleVideoUpdate: ScheduleVideoUpdateModel
1007
26b7305a
C
1008 @HasOne(() => VideoBlacklistModel, {
1009 foreignKey: {
1010 name: 'videoId',
1011 allowNull: false
1012 },
1013 onDelete: 'cascade'
1014 })
1015 VideoBlacklist: VideoBlacklistModel
1016
dc133480
C
1017 @HasOne(() => VideoImportModel, {
1018 foreignKey: {
1019 name: 'videoId',
1020 allowNull: true
1021 },
1022 onDelete: 'set null'
1023 })
1024 VideoImport: VideoImportModel
1025
40e87e9e
C
1026 @HasMany(() => VideoCaptionModel, {
1027 foreignKey: {
1028 name: 'videoId',
1029 allowNull: false
1030 },
1031 onDelete: 'cascade',
1032 hooks: true,
8ea6f49a 1033 [ 'separate' as any ]: true
40e87e9e
C
1034 })
1035 VideoCaptions: VideoCaptionModel[]
1036
f05a1c30 1037 @BeforeDestroy
453e83ea 1038 static async sendDelete (instance: MVideoAccountLight, options) {
f05a1c30
C
1039 if (instance.isOwned()) {
1040 if (!instance.VideoChannel) {
1041 instance.VideoChannel = await instance.$get('VideoChannel', {
1042 include: [
453e83ea
C
1043 ActorModel,
1044 AccountModel
f05a1c30
C
1045 ],
1046 transaction: options.transaction
0283eaac 1047 }) as MChannelAccountDefault
f05a1c30
C
1048 }
1049
f05a1c30
C
1050 return sendDeleteVideo(instance, options.transaction)
1051 }
1052
1053 return undefined
1054 }
1055
6b738c7a 1056 @BeforeDestroy
40e87e9e 1057 static async removeFiles (instance: VideoModel) {
f05a1c30 1058 const tasks: Promise<any>[] = []
f285faa0 1059
8e0fd45e 1060 logger.info('Removing files of video %s.', instance.url)
6b738c7a 1061
3fd3ab2d 1062 if (instance.isOwned()) {
f05a1c30 1063 if (!Array.isArray(instance.VideoFiles)) {
e6122097 1064 instance.VideoFiles = await instance.$get('VideoFiles')
f05a1c30
C
1065 }
1066
3fd3ab2d
C
1067 // Remove physical files and torrents
1068 instance.VideoFiles.forEach(file => {
1069 tasks.push(instance.removeFile(file))
1070 tasks.push(instance.removeTorrent(file))
1071 })
09209296
C
1072
1073 // Remove playlists file
1074 tasks.push(instance.removeStreamingPlaylist())
3fd3ab2d 1075 }
40298b02 1076
6b738c7a
C
1077 // Do not wait video deletion because we could be in a transaction
1078 Promise.all(tasks)
8ea6f49a
C
1079 .catch(err => {
1080 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1081 })
6b738c7a
C
1082
1083 return undefined
3fd3ab2d 1084 }
f285faa0 1085
453e83ea 1086 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
9f1ddd24
C
1087 const query = {
1088 where: {
1089 remote: false
1090 }
1091 }
1092
e8bafea3 1093 return VideoModel.scope([
d7a25329 1094 ScopeNames.WITH_WEBTORRENT_FILES,
e8bafea3
C
1095 ScopeNames.WITH_STREAMING_PLAYLISTS,
1096 ScopeNames.WITH_THUMBNAILS
1097 ]).findAll(query)
9f1ddd24
C
1098 }
1099
50d6de9c 1100 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
1101 function getRawQuery (select: string) {
1102 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1103 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
1104 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1105 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
1106 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1107 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 1108 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 1109
3fd3ab2d
C
1110 return `(${queryVideo}) UNION (${queryVideoShare})`
1111 }
aaf61f38 1112
3fd3ab2d
C
1113 const rawQuery = getRawQuery('"Video"."id"')
1114 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1115
1116 const query = {
1117 distinct: true,
1118 offset: start,
1119 limit: count,
1735c825 1120 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
3fd3ab2d
C
1121 where: {
1122 id: {
1735c825 1123 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
3c75ce12 1124 },
1735c825 1125 [ Op.or ]: [
3c75ce12
C
1126 { privacy: VideoPrivacy.PUBLIC },
1127 { privacy: VideoPrivacy.UNLISTED }
1128 ]
3fd3ab2d
C
1129 },
1130 include: [
40e87e9e
C
1131 {
1132 attributes: [ 'language' ],
1133 model: VideoCaptionModel.unscoped(),
1134 required: false
1135 },
3fd3ab2d 1136 {
1d230c44 1137 attributes: [ 'id', 'url' ],
2c897999 1138 model: VideoShareModel.unscoped(),
3fd3ab2d 1139 required: false,
e3d5ea4f
C
1140 // We only want videos shared by this actor
1141 where: {
1735c825 1142 [ Op.and ]: [
e3d5ea4f
C
1143 {
1144 id: {
1735c825 1145 [ Op.not ]: null
e3d5ea4f
C
1146 }
1147 },
1148 {
1149 actorId
1150 }
1151 ]
1152 },
50d6de9c
C
1153 include: [
1154 {
2c897999
C
1155 attributes: [ 'id', 'url' ],
1156 model: ActorModel.unscoped()
50d6de9c
C
1157 }
1158 ]
3fd3ab2d
C
1159 },
1160 {
2c897999 1161 model: VideoChannelModel.unscoped(),
3fd3ab2d
C
1162 required: true,
1163 include: [
1164 {
2c897999
C
1165 attributes: [ 'name' ],
1166 model: AccountModel.unscoped(),
1167 required: true,
1168 include: [
1169 {
e3d5ea4f 1170 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999
C
1171 model: ActorModel.unscoped(),
1172 required: true
1173 }
1174 ]
1175 },
1176 {
e3d5ea4f 1177 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999 1178 model: ActorModel.unscoped(),
3fd3ab2d
C
1179 required: true
1180 }
1181 ]
1182 },
3fd3ab2d 1183 VideoFileModel,
2c897999 1184 TagModel
3fd3ab2d
C
1185 ]
1186 }
164174a6 1187
3fd3ab2d 1188 return Bluebird.all([
3acc5084
C
1189 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1190 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
3fd3ab2d
C
1191 ]).then(([ rows, totals ]) => {
1192 // totals: totalVideos + totalVideoShares
1193 let totalVideos = 0
1194 let totalVideoShares = 0
3acc5084
C
1195 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1196 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
3fd3ab2d
C
1197
1198 const total = totalVideos + totalVideoShares
1199 return {
1200 data: rows,
1201 total: total
1202 }
1203 })
1204 }
93e1258c 1205
bf64ed41
RK
1206 static listUserVideosForApi (
1207 accountId: number,
1208 start: number,
1209 count: number,
1210 sort: string,
1211 search?: string
1212 ) {
3acc5084 1213 function buildBaseQuery (): FindOptions {
bf64ed41 1214 let baseQuery = {
3acc5084
C
1215 offset: start,
1216 limit: count,
1217 order: getVideoSort(sort),
1218 include: [
1219 {
1220 model: VideoChannelModel,
1221 required: true,
1222 include: [
1223 {
1224 model: AccountModel,
1225 where: {
1226 id: accountId
1227 },
1228 required: true
1229 }
1230 ]
1231 }
1232 ]
1233 }
bf64ed41
RK
1234
1235 if (search) {
1236 baseQuery = Object.assign(baseQuery, {
1237 where: {
1238 name: {
1239 [ Op.iLike ]: '%' + search + '%'
1240 }
1241 }
1242 })
1243 }
1244
1245 return baseQuery
3fd3ab2d 1246 }
d8755eed 1247
3acc5084
C
1248 const countQuery = buildBaseQuery()
1249 const findQuery = buildBaseQuery()
1250
bf64ed41 1251 const findScopes: (string | ScopeOptions)[] = [
a18f275d
C
1252 ScopeNames.WITH_SCHEDULED_UPDATE,
1253 ScopeNames.WITH_BLACKLISTED,
1254 ScopeNames.WITH_THUMBNAILS
1255 ]
3acc5084 1256
3acc5084
C
1257 return Promise.all([
1258 VideoModel.count(countQuery),
0283eaac 1259 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
3acc5084
C
1260 ]).then(([ count, rows ]) => {
1261 return {
0283eaac 1262 data: rows,
3acc5084
C
1263 total: count
1264 }
1265 })
3fd3ab2d 1266 }
93e1258c 1267
48dce1c9 1268 static async listForApi (options: {
0626e7af
C
1269 start: number,
1270 count: number,
1271 sort: string,
d525fc39 1272 nsfw: boolean,
06a05d5f 1273 includeLocalVideos: boolean,
48dce1c9 1274 withFiles: boolean,
d525fc39
C
1275 categoryOneOf?: number[],
1276 licenceOneOf?: number[],
1277 languageOneOf?: string[],
1278 tagsOneOf?: string[],
1279 tagsAllOf?: string[],
0626e7af 1280 filter?: VideoFilter,
48dce1c9 1281 accountId?: number,
06a05d5f 1282 videoChannelId?: number,
4e74e803 1283 followerActorId?: number
418d092a 1284 videoPlaylistId?: number,
6e46de09 1285 trendingDays?: number,
453e83ea 1286 user?: MUserAccountId,
fe987656
C
1287 historyOfUser?: MUserId,
1288 countVideos?: boolean
1289 }) {
7ad9b984
C
1290 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1291 throw new Error('Try to filter all-local but no user has not the see all videos right')
1cd3facc
C
1292 }
1293
3caf77d3 1294 const query: FindOptions & { where?: null } = {
48dce1c9
C
1295 offset: options.start,
1296 limit: options.count,
9a629c6e
C
1297 order: getVideoSort(options.sort)
1298 }
1299
1300 let trendingDays: number
1301 if (options.sort.endsWith('trending')) {
1302 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1303
1304 query.group = 'VideoModel.id'
3fd3ab2d 1305 }
93e1258c 1306
7ad9b984
C
1307 const serverActor = await getServerActor()
1308
4e74e803
C
1309 // followerActorId === null has a meaning, so just check undefined
1310 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
06a05d5f 1311
afd2cba5 1312 const queryOptions = {
4e74e803 1313 followerActorId,
7ad9b984 1314 serverAccountId: serverActor.Account.id,
afd2cba5
C
1315 nsfw: options.nsfw,
1316 categoryOneOf: options.categoryOneOf,
1317 licenceOneOf: options.licenceOneOf,
1318 languageOneOf: options.languageOneOf,
1319 tagsOneOf: options.tagsOneOf,
1320 tagsAllOf: options.tagsAllOf,
1321 filter: options.filter,
1322 withFiles: options.withFiles,
1323 accountId: options.accountId,
1324 videoChannelId: options.videoChannelId,
418d092a 1325 videoPlaylistId: options.videoPlaylistId,
9a629c6e 1326 includeLocalVideos: options.includeLocalVideos,
7ad9b984 1327 user: options.user,
8b9a525a 1328 historyOfUser: options.historyOfUser,
9a629c6e 1329 trendingDays
48dce1c9
C
1330 }
1331
fe987656 1332 return VideoModel.getAvailableForApi(query, queryOptions, options.countVideos)
93e1258c
C
1333 }
1334
0b18f4aa 1335 static async searchAndPopulateAccountAndServer (options: {
06a05d5f 1336 includeLocalVideos: boolean
d4112450 1337 search?: string
0b18f4aa
C
1338 start?: number
1339 count?: number
1340 sort?: string
1341 startDate?: string // ISO 8601
1342 endDate?: string // ISO 8601
31d065cc
AM
1343 originallyPublishedStartDate?: string
1344 originallyPublishedEndDate?: string
0b18f4aa
C
1345 nsfw?: boolean
1346 categoryOneOf?: number[]
1347 licenceOneOf?: number[]
1348 languageOneOf?: string[]
1349 tagsOneOf?: string[]
1350 tagsAllOf?: string[]
1351 durationMin?: number // seconds
1352 durationMax?: number // seconds
453e83ea 1353 user?: MUserAccountId,
1cd3facc 1354 filter?: VideoFilter
0b18f4aa 1355 }) {
8ea6f49a 1356 const whereAnd = []
d525fc39
C
1357
1358 if (options.startDate || options.endDate) {
8ea6f49a 1359 const publishedAtRange = {}
d525fc39 1360
1735c825
C
1361 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1362 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
d525fc39
C
1363
1364 whereAnd.push({ publishedAt: publishedAtRange })
1365 }
1366
31d065cc
AM
1367 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1368 const originallyPublishedAtRange = {}
1369
1735c825
C
1370 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1371 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
31d065cc
AM
1372
1373 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1374 }
1375
d525fc39 1376 if (options.durationMin || options.durationMax) {
8ea6f49a 1377 const durationRange = {}
d525fc39 1378
1735c825
C
1379 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1380 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
d525fc39
C
1381
1382 whereAnd.push({ duration: durationRange })
1383 }
1384
d4112450 1385 const attributesInclude = []
dbfd3e9b
C
1386 const escapedSearch = VideoModel.sequelize.escape(options.search)
1387 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
d4112450 1388 if (options.search) {
3cf53828
C
1389 const trigramSearch = {
1390 id: {
1391 [ Op.in ]: Sequelize.literal(
1392 '(' +
1393 'SELECT "video"."id" FROM "video" ' +
1394 'WHERE ' +
1395 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1396 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1397 'UNION ALL ' +
1398 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1399 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
227eb02f 1400 'WHERE lower("tag"."name") = lower(' + escapedSearch + ')' +
3cf53828
C
1401 ')'
1402 )
d4112450 1403 }
3cf53828
C
1404 }
1405
1406 if (validator.isUUID(options.search)) {
1407 whereAnd.push({
1408 [Op.or]: [
1409 trigramSearch,
1410 {
1411 uuid: options.search
1412 }
1413 ]
1414 })
1415 } else {
1416 whereAnd.push(trigramSearch)
1417 }
d4112450
C
1418
1419 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1420 }
1421
1422 // Cannot search on similarity if we don't have a search
1423 if (!options.search) {
1424 attributesInclude.push(
1425 Sequelize.literal('0 as similarity')
1426 )
1427 }
d525fc39 1428
3caf77d3 1429 const query = {
57c36b27 1430 attributes: {
d4112450 1431 include: attributesInclude
57c36b27 1432 },
d525fc39
C
1433 offset: options.start,
1434 limit: options.count,
3caf77d3 1435 order: getVideoSort(options.sort)
f05a1c30
C
1436 }
1437
1438 const serverActor = await getServerActor()
afd2cba5 1439 const queryOptions = {
4e74e803 1440 followerActorId: serverActor.id,
7ad9b984 1441 serverAccountId: serverActor.Account.id,
afd2cba5
C
1442 includeLocalVideos: options.includeLocalVideos,
1443 nsfw: options.nsfw,
1444 categoryOneOf: options.categoryOneOf,
1445 licenceOneOf: options.licenceOneOf,
1446 languageOneOf: options.languageOneOf,
1447 tagsOneOf: options.tagsOneOf,
6e46de09 1448 tagsAllOf: options.tagsAllOf,
7ad9b984 1449 user: options.user,
3caf77d3
C
1450 filter: options.filter,
1451 baseWhere: whereAnd
48dce1c9 1452 }
f05a1c30 1453
afd2cba5 1454 return VideoModel.getAvailableForApi(query, queryOptions)
f05a1c30
C
1455 }
1456
453e83ea 1457 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
418d092a 1458 const where = buildWhereIdOrUUID(id)
627621c1
C
1459 const options = {
1460 where,
1461 transaction: t
3fd3ab2d 1462 }
d8755eed 1463
e8bafea3 1464 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
3fd3ab2d 1465 }
d8755eed 1466
d636ab58
C
1467 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1468 const where = buildWhereIdOrUUID(id)
1469 const options = {
1470 where,
1471 transaction: t
1472 }
1473
1474 return VideoModel.scope([
1475 ScopeNames.WITH_THUMBNAILS,
1476 ScopeNames.WITH_BLACKLISTED
1477 ]).findOne(options)
1478 }
1479
453e83ea 1480 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
418d092a 1481 const where = buildWhereIdOrUUID(id)
09209296
C
1482 const options = {
1483 where,
1484 transaction: t
1485 }
1486
e8bafea3
C
1487 return VideoModel.scope([
1488 ScopeNames.WITH_BLACKLISTED,
1489 ScopeNames.WITH_USER_ID,
1490 ScopeNames.WITH_THUMBNAILS
1491 ]).findOne(options)
09209296
C
1492 }
1493
453e83ea 1494 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
418d092a 1495 const where = buildWhereIdOrUUID(id)
627621c1 1496
3fd3ab2d 1497 const options = {
627621c1
C
1498 attributes: [ 'id' ],
1499 where,
1500 transaction: t
3fd3ab2d 1501 }
72c7248b 1502
e8bafea3 1503 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
627621c1
C
1504 }
1505
453e83ea 1506 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
e2600d8b
C
1507 const where = buildWhereIdOrUUID(id)
1508
1509 const query = {
1510 where,
1511 transaction: t,
1512 logging
1513 }
1514
e8bafea3 1515 return VideoModel.scope([
d7a25329 1516 ScopeNames.WITH_WEBTORRENT_FILES,
e8bafea3
C
1517 ScopeNames.WITH_STREAMING_PLAYLISTS,
1518 ScopeNames.WITH_THUMBNAILS
e2600d8b 1519 ]).findOne(query)
3fd3ab2d 1520 }
72c7248b 1521
453e83ea 1522 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
8fa5653a
C
1523 const options = {
1524 where: {
1525 uuid
1526 }
1527 }
1528
e8bafea3 1529 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
8fa5653a
C
1530 }
1531
453e83ea 1532 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1735c825 1533 const query: FindOptions = {
627621c1
C
1534 where: {
1535 url
4157cdb1
C
1536 },
1537 transaction
627621c1
C
1538 }
1539
e8bafea3 1540 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
4157cdb1
C
1541 }
1542
0283eaac 1543 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1735c825 1544 const query: FindOptions = {
4157cdb1
C
1545 where: {
1546 url
1547 },
1548 transaction
1549 }
627621c1 1550
09209296
C
1551 return VideoModel.scope([
1552 ScopeNames.WITH_ACCOUNT_DETAILS,
d7a25329 1553 ScopeNames.WITH_WEBTORRENT_FILES,
e8bafea3 1554 ScopeNames.WITH_STREAMING_PLAYLISTS,
453e83ea
C
1555 ScopeNames.WITH_THUMBNAILS,
1556 ScopeNames.WITH_BLACKLISTED
09209296 1557 ]).findOne(query)
627621c1
C
1558 }
1559
453e83ea 1560 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
418d092a 1561 const where = buildWhereIdOrUUID(id)
627621c1 1562
3fd3ab2d 1563 const options = {
3acc5084 1564 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
627621c1 1565 where,
2186386c 1566 transaction: t
3fd3ab2d 1567 }
fd45e8f4 1568
3acc5084 1569 const scopes: (string | ScopeOptions)[] = [
6e46de09
C
1570 ScopeNames.WITH_TAGS,
1571 ScopeNames.WITH_BLACKLISTED,
09209296
C
1572 ScopeNames.WITH_ACCOUNT_DETAILS,
1573 ScopeNames.WITH_SCHEDULED_UPDATE,
d7a25329 1574 ScopeNames.WITH_WEBTORRENT_FILES,
e8bafea3
C
1575 ScopeNames.WITH_STREAMING_PLAYLISTS,
1576 ScopeNames.WITH_THUMBNAILS
09209296
C
1577 ]
1578
1579 if (userId) {
3acc5084 1580 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
09209296
C
1581 }
1582
1583 return VideoModel
1584 .scope(scopes)
1585 .findOne(options)
1586 }
1587
89cd1275
C
1588 static loadForGetAPI (parameters: {
1589 id: number | string,
1590 t?: Transaction,
1591 userId?: number
453e83ea 1592 }): Bluebird<MVideoDetails> {
89cd1275 1593 const { id, t, userId } = parameters
418d092a 1594 const where = buildWhereIdOrUUID(id)
09209296
C
1595
1596 const options = {
1735c825 1597 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
09209296
C
1598 where,
1599 transaction: t
1600 }
1601
3acc5084 1602 const scopes: (string | ScopeOptions)[] = [
09209296
C
1603 ScopeNames.WITH_TAGS,
1604 ScopeNames.WITH_BLACKLISTED,
6e46de09 1605 ScopeNames.WITH_ACCOUNT_DETAILS,
09209296 1606 ScopeNames.WITH_SCHEDULED_UPDATE,
e8bafea3 1607 ScopeNames.WITH_THUMBNAILS,
d7a25329 1608 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
3acc5084 1609 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
6e46de09
C
1610 ]
1611
1612 if (userId) {
3acc5084 1613 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
6e46de09
C
1614 }
1615
d48ff09d 1616 return VideoModel
6e46de09 1617 .scope(scopes)
da854ddd
C
1618 .findOne(options)
1619 }
1620
09cababd
C
1621 static async getStats () {
1622 const totalLocalVideos = await VideoModel.count({
1623 where: {
1624 remote: false
1625 }
1626 })
1627 const totalVideos = await VideoModel.count()
1628
1629 let totalLocalVideoViews = await VideoModel.sum('views', {
1630 where: {
1631 remote: false
1632 }
1633 })
1634 // Sequelize could return null...
1635 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1636
1637 return {
1638 totalLocalVideos,
1639 totalLocalVideoViews,
1640 totalVideos
1641 }
1642 }
1643
6b616860
C
1644 static incrementViews (id: number, views: number) {
1645 return VideoModel.increment('views', {
1646 by: views,
1647 where: {
1648 id
1649 }
1650 })
1651 }
1652
8d427346
C
1653 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1654 // Instances only share videos
1655 const query = 'SELECT 1 FROM "videoShare" ' +
1656 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1657 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1658 'LIMIT 1'
1659
1660 const options = {
d5d9b6d7 1661 type: QueryTypes.SELECT as QueryTypes.SELECT,
8d427346
C
1662 bind: { followerActorId, videoId },
1663 raw: true
1664 }
1665
1666 return VideoModel.sequelize.query(query, options)
1667 .then(results => results.length === 1)
1668 }
1669
453e83ea 1670 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
7d14d4d2
C
1671 const options = {
1672 where: {
1673 channelId: videoChannel.id
1674 },
1675 transaction: t
1676 }
1677
1678 return VideoModel.update({ support: videoChannel.support }, options)
1679 }
1680
453e83ea 1681 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
7d14d4d2
C
1682 const query = {
1683 attributes: [ 'id' ],
1684 where: {
1685 channelId: videoChannel.id
1686 }
1687 }
1688
1689 return VideoModel.findAll(query)
1690 .then(videos => videos.map(v => v.id))
1691 }
1692
2d3741d6 1693 // threshold corresponds to how many video the field should have to be returned
7348b1fd 1694 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
65b21c96 1695 const serverActor = await getServerActor()
4e74e803 1696 const followerActorId = serverActor.id
7348b1fd 1697
65b21c96
C
1698 const scopeOptions: AvailableForListIDsOptions = {
1699 serverAccountId: serverActor.Account.id,
4e74e803 1700 followerActorId,
8519cc92 1701 includeLocalVideos: true,
bfbd9128 1702 attributesType: 'none' // Don't break aggregation
7348b1fd
C
1703 }
1704
1735c825 1705 const query: FindOptions = {
2d3741d6
C
1706 attributes: [ field ],
1707 limit: count,
1708 group: field,
3acc5084
C
1709 having: Sequelize.where(
1710 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1711 ),
1735c825 1712 order: [ (this.sequelize as any).random() ]
2d3741d6
C
1713 }
1714
7348b1fd
C
1715 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1716 .findAll(query)
8ea6f49a 1717 .then(rows => rows.map(r => r[ field ]))
2d3741d6
C
1718 }
1719
b36f41ca
C
1720 static buildTrendingQuery (trendingDays: number) {
1721 return {
1722 attributes: [],
1723 subQuery: false,
1724 model: VideoViewModel,
1725 required: false,
1726 where: {
1727 startDate: {
1735c825 1728 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
b36f41ca
C
1729 }
1730 }
1731 }
1732 }
1733
6e46de09 1734 private static async getAvailableForApi (
3caf77d3 1735 query: FindOptions & { where?: null }, // Forbid where field in query
7ad9b984 1736 options: AvailableForListIDsOptions,
6e46de09
C
1737 countVideos = true
1738 ) {
1735c825 1739 const idsScope: ScopeOptions = {
afd2cba5
C
1740 method: [
1741 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1742 ]
1743 }
1744
8ea6f49a
C
1745 // Remove trending sort on count, because it uses a group by
1746 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1735c825
C
1747 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1748 const countScope: ScopeOptions = {
8ea6f49a
C
1749 method: [
1750 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1751 ]
1752 }
1753
ddc07312 1754 const [ count, rows ] = await Promise.all([
3caf77d3
C
1755 countVideos
1756 ? VideoModel.scope(countScope).count(countQuery)
1757 : Promise.resolve<number>(undefined),
1758
1759 VideoModel.scope(idsScope)
ddc07312 1760 .findAll(Object.assign({}, query, { raw: true }))
3caf77d3 1761 .then(rows => rows.map(r => r.id))
ddc07312 1762 .then(ids => VideoModel.loadCompleteVideosForApi(ids, query, options))
8ea6f49a 1763 ])
afd2cba5 1764
ddc07312
C
1765 return {
1766 data: rows,
1767 total: count
1768 }
1769 }
1770
1771 private static loadCompleteVideosForApi (ids: number[], query: FindOptions, options: AvailableForListIDsOptions) {
1772 if (ids.length === 0) return []
afd2cba5 1773
1735c825 1774 const secondQuery: FindOptions = {
b6314e3c
C
1775 offset: 0,
1776 limit: query.limit,
9a629c6e
C
1777 attributes: query.attributes,
1778 order: [ // Keep original order
1779 Sequelize.literal(
2ba92871 1780 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
9a629c6e
C
1781 )
1782 ]
b6314e3c 1783 }
df0b219d 1784
2fb5b3a5 1785 const apiScope: (string | ScopeOptions)[] = []
df0b219d
C
1786
1787 if (options.user) {
1788 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
df0b219d
C
1789 }
1790
1791 apiScope.push({
1792 method: [
1793 ScopeNames.FOR_API, {
76564702
C
1794 ids,
1795 withFiles: options.withFiles,
df0b219d
C
1796 videoPlaylistId: options.videoPlaylistId
1797 } as ForAPIOptions
1798 ]
1799 })
1800
ddc07312 1801 return VideoModel.scope(apiScope).findAll(secondQuery)
afd2cba5 1802 }
066e94c5 1803
22a73cb8 1804 private static isPrivacyForFederation (privacy: VideoPrivacy) {
dce659fa
C
1805 const castedPrivacy = parseInt(privacy + '', 10)
1806
1807 return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
22a73cb8
C
1808 }
1809
098eb377 1810 static getCategoryLabel (id: number) {
8ea6f49a 1811 return VIDEO_CATEGORIES[ id ] || 'Misc'
ae5a3dd6
C
1812 }
1813
098eb377 1814 static getLicenceLabel (id: number) {
8ea6f49a 1815 return VIDEO_LICENCES[ id ] || 'Unknown'
ae5a3dd6
C
1816 }
1817
098eb377 1818 static getLanguageLabel (id: string) {
8ea6f49a 1819 return VIDEO_LANGUAGES[ id ] || 'Unknown'
ae5a3dd6
C
1820 }
1821
098eb377 1822 static getPrivacyLabel (id: number) {
8ea6f49a 1823 return VIDEO_PRIVACIES[ id ] || 'Unknown'
2186386c 1824 }
2243730c 1825
098eb377 1826 static getStateLabel (id: number) {
8ea6f49a 1827 return VIDEO_STATES[ id ] || 'Unknown'
2243730c
C
1828 }
1829
5b77537c
C
1830 isBlacklisted () {
1831 return !!this.VideoBlacklist
1832 }
1833
bfbd9128
C
1834 isBlocked () {
1835 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1836 this.VideoChannel.Account.isBlocked()
1837 }
1838
92e0f42e 1839 getQualityFileBy <T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
d7a25329 1840 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
92e0f42e 1841 const file = fun(this.VideoFiles, file => file.resolution)
d7a25329
C
1842
1843 return Object.assign(file, { Video: this })
1844 }
1845
1846 // No webtorrent files, try with streaming playlist files
1847 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1848 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1849
92e0f42e 1850 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
d7a25329
C
1851 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1852 }
aaf61f38 1853
d7a25329 1854 return undefined
e4f97bab 1855 }
aaf61f38 1856
92e0f42e
C
1857 getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1858 return this.getQualityFileBy(maxBy)
1859 }
1860
1861 getMinQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1862 return this.getQualityFileBy(minBy)
1863 }
1864
d7a25329 1865 getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
29d4e137
C
1866 if (Array.isArray(this.VideoFiles) === false) return undefined
1867
d7a25329
C
1868 const file = this.VideoFiles.find(f => f.resolution === resolution)
1869 if (!file) return undefined
1870
1871 return Object.assign(file, { Video: this })
29d4e137
C
1872 }
1873
453e83ea 1874 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
3acc5084
C
1875 thumbnail.videoId = this.id
1876
1877 const savedThumbnail = await thumbnail.save({ transaction })
1878
e8bafea3
C
1879 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1880
1881 // Already have this thumbnail, skip
3acc5084 1882 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
e8bafea3 1883
3acc5084 1884 this.Thumbnails.push(savedThumbnail)
e8bafea3
C
1885 }
1886
e8bafea3
C
1887 generateThumbnailName () {
1888 return this.uuid + '.jpg'
7b1f49de
C
1889 }
1890
3acc5084 1891 getMiniature () {
e8bafea3
C
1892 if (Array.isArray(this.Thumbnails) === false) return undefined
1893
3acc5084 1894 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
e8bafea3
C
1895 }
1896
1897 generatePreviewName () {
1898 return this.uuid + '.jpg'
1899 }
1900
1901 getPreview () {
1902 if (Array.isArray(this.Thumbnails) === false) return undefined
1903
1904 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
3fd3ab2d 1905 }
7b1f49de 1906
3fd3ab2d
C
1907 isOwned () {
1908 return this.remote === false
9567011b
C
1909 }
1910
cef534ed
C
1911 getWatchStaticPath () {
1912 return '/videos/watch/' + this.uuid
1913 }
1914
40e87e9e 1915 getEmbedStaticPath () {
3fd3ab2d
C
1916 return '/videos/embed/' + this.uuid
1917 }
e4f97bab 1918
3acc5084
C
1919 getMiniatureStaticPath () {
1920 const thumbnail = this.getMiniature()
e8bafea3
C
1921 if (!thumbnail) return null
1922
1923 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
e4f97bab 1924 }
227d02fe 1925
40e87e9e 1926 getPreviewStaticPath () {
e8bafea3
C
1927 const preview = this.getPreview()
1928 if (!preview) return null
1929
1930 // We use a local cache, so specify our cache endpoint instead of potential remote URL
557b13ae 1931 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
3fd3ab2d 1932 }
40298b02 1933
b5fecbf4 1934 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
098eb377 1935 return videoModelToFormattedJSON(this, options)
14d3270f 1936 }
14d3270f 1937
b5fecbf4 1938 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
098eb377 1939 return videoModelToFormattedDetailsJSON(this)
244e76a5
RK
1940 }
1941
1942 getFormattedVideoFilesJSON (): VideoFile[] {
d7a25329
C
1943 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1944 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
3fd3ab2d 1945 }
e4f97bab 1946
b5fecbf4 1947 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
098eb377 1948 return videoModelToActivityPubObject(this)
3fd3ab2d
C
1949 }
1950
1951 getTruncatedDescription () {
1952 if (!this.description) return null
93e1258c 1953
bffbebbe 1954 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
687c6180 1955 return peertubeTruncate(this.description, { length: maxLength })
93e1258c
C
1956 }
1957
d7a25329
C
1958 getMaxQualityResolution () {
1959 const file = this.getMaxQualityFile()
1960 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1961 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
0d0e8dd0 1962
056aa7f2 1963 return getVideoFileResolution(originalFilePath)
3fd3ab2d 1964 }
0d0e8dd0 1965
96f29c0f 1966 getDescriptionAPIPath () {
3fd3ab2d 1967 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1968 }
1969
d7a25329 1970 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
e2600d8b
C
1971 if (!this.VideoStreamingPlaylists) return undefined
1972
d7a25329
C
1973 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1974 playlist.Video = this
1975
1976 return playlist
e2600d8b
C
1977 }
1978
d7a25329
C
1979 setHLSPlaylist (playlist: MStreamingPlaylist) {
1980 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
b9fffa29 1981
d7a25329
C
1982 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1983 this.VideoStreamingPlaylists = toAdd
1984 return
1985 }
1986
1987 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1988 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1989 .concat(toAdd)
1990 }
1991
1992 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1993 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
62689b94 1994 return remove(filePath)
ed31c059 1995 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
feb4bdfd
C
1996 }
1997
453e83ea 1998 removeTorrent (videoFile: MVideoFile) {
d7a25329 1999 const torrentPath = getTorrentFilePath(this, videoFile)
62689b94 2000 return remove(torrentPath)
ed31c059 2001 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
aaf61f38
C
2002 }
2003
09209296 2004 removeStreamingPlaylist (isRedundancy = false) {
66fb2aa3 2005 const directoryPath = getHLSDirectory(this, isRedundancy)
09209296 2006
66fb2aa3
C
2007 return remove(directoryPath)
2008 .catch(err => logger.warn('Cannot delete playlist directory %s.', directoryPath, { err }))
09209296
C
2009 }
2010
1297eb5d
C
2011 isOutdated () {
2012 if (this.isOwned()) return false
2013
9f79ade6 2014 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1297eb5d
C
2015 }
2016
22a73cb8
C
2017 hasPrivacyForFederation () {
2018 return VideoModel.isPrivacyForFederation(this.privacy)
2019 }
2020
2021 isNewVideo (newPrivacy: VideoPrivacy) {
2022 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
2023 }
2024
04b8c3fb
C
2025 setAsRefreshed () {
2026 this.changed('updatedAt', true)
2027
2028 return this.save()
2029 }
2030
22a73cb8
C
2031 requiresAuth () {
2032 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2033 }
2034
2035 setPrivacy (newPrivacy: VideoPrivacy) {
2036 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2037 this.publishedAt = new Date()
2038 }
2039
2040 this.privacy = newPrivacy
2041 }
2042
2043 isConfidential () {
2044 return this.privacy === VideoPrivacy.PRIVATE ||
2045 this.privacy === VideoPrivacy.UNLISTED ||
2046 this.privacy === VideoPrivacy.INTERNAL
2047 }
2048
d7a25329
C
2049 async publishIfNeededAndSave (t: Transaction) {
2050 if (this.state !== VideoState.PUBLISHED) {
2051 this.state = VideoState.PUBLISHED
2052 this.publishedAt = new Date()
2053 await this.save({ transaction: t })
7920c273 2054
d7a25329 2055 return true
6fcd19ba 2056 }
aaf61f38 2057
d7a25329 2058 return false
15d4ee04 2059 }
a96aed15 2060
d7a25329
C
2061 getBaseUrls () {
2062 if (this.isOwned()) {
2063 return {
2064 baseUrlHttp: WEBSERVER.URL,
2065 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2066 }
c48e82b5
C
2067 }
2068
d7a25329
C
2069 return {
2070 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2071 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2072 }
c48e82b5
C
2073 }
2074
09209296
C
2075 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2076 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2077 }
2078
453e83ea 2079 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
d7a25329 2080 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
3fd3ab2d 2081 }
e4f97bab 2082
453e83ea 2083 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
d7a25329 2084 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
02756fbd
C
2085 }
2086
453e83ea 2087 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
d7a25329 2088 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
3fd3ab2d 2089 }
a96aed15 2090
453e83ea 2091 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
d7a25329 2092 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
b9fffa29
C
2093 }
2094
453e83ea 2095 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
d7a25329 2096 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
02756fbd 2097 }
09209296 2098
453e83ea 2099 getBandwidthBits (videoFile: MVideoFile) {
09209296
C
2100 return Math.ceil((videoFile.size * 8) / this.duration)
2101 }
a96aed15 2102}