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