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