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