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