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