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