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