]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/video.ts
Add history page on client
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
1 import * as Bluebird from 'bluebird'
2 import { maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
6 import * as Sequelize from 'sequelize'
7 import {
8 AllowNull,
9 BeforeDestroy,
10 BelongsTo,
11 BelongsToMany,
12 Column,
13 CreatedAt,
14 DataType,
15 Default,
16 ForeignKey,
17 HasMany,
18 HasOne,
19 IFindOptions,
20 IIncludeOptions,
21 Is,
22 IsInt,
23 IsUUID,
24 Min,
25 Model,
26 Scopes,
27 Table,
28 UpdatedAt
29 } from 'sequelize-typescript'
30 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
31 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
32 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
33 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
34 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
35 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
36 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
37 import {
38 isVideoCategoryValid,
39 isVideoDescriptionValid,
40 isVideoDurationValid,
41 isVideoLanguageValid,
42 isVideoLicenceValid,
43 isVideoNameValid,
44 isVideoPrivacyValid,
45 isVideoStateValid,
46 isVideoSupportValid
47 } from '../../helpers/custom-validators/videos'
48 import { generateImageFromVideoFile, getVideoFileResolution } from '../../helpers/ffmpeg-utils'
49 import { logger } from '../../helpers/logger'
50 import { getServerActor } from '../../helpers/utils'
51 import {
52 ACTIVITY_PUB,
53 API_VERSION,
54 CONFIG,
55 CONSTRAINTS_FIELDS,
56 PREVIEWS_SIZE,
57 REMOTE_SCHEME,
58 STATIC_DOWNLOAD_PATHS,
59 STATIC_PATHS,
60 THUMBNAILS_SIZE,
61 VIDEO_CATEGORIES,
62 VIDEO_LANGUAGES,
63 VIDEO_LICENCES,
64 VIDEO_PRIVACIES,
65 VIDEO_STATES
66 } from '../../initializers'
67 import { sendDeleteVideo } from '../../lib/activitypub/send'
68 import { AccountModel } from '../account/account'
69 import { AccountVideoRateModel } from '../account/account-video-rate'
70 import { ActorModel } from '../activitypub/actor'
71 import { AvatarModel } from '../avatar/avatar'
72 import { ServerModel } from '../server/server'
73 import { buildBlockedAccountSQL, buildTrigramSearchIndex, createSimilarityAttribute, getVideoSort, throwIfNotValid } from '../utils'
74 import { TagModel } from './tag'
75 import { VideoAbuseModel } from './video-abuse'
76 import { VideoChannelModel } from './video-channel'
77 import { VideoCommentModel } from './video-comment'
78 import { VideoFileModel } from './video-file'
79 import { VideoShareModel } from './video-share'
80 import { VideoTagModel } from './video-tag'
81 import { ScheduleVideoUpdateModel } from './schedule-video-update'
82 import { VideoCaptionModel } from './video-caption'
83 import { VideoBlacklistModel } from './video-blacklist'
84 import { remove, writeFile } from 'fs-extra'
85 import { VideoViewModel } from './video-views'
86 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
87 import {
88 videoFilesModelToFormattedJSON,
89 VideoFormattingJSONOptions,
90 videoModelToActivityPubObject,
91 videoModelToFormattedDetailsJSON,
92 videoModelToFormattedJSON
93 } from './video-format-utils'
94 import * as validator from 'validator'
95 import { UserVideoHistoryModel } from '../account/user-video-history'
96 import { UserModel } from '../account/user'
97
98 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
99 const indexes: Sequelize.DefineIndexesOptions[] = [
100 buildTrigramSearchIndex('video_name_trigram', 'name'),
101
102 { fields: [ 'createdAt' ] },
103 { fields: [ 'publishedAt' ] },
104 { fields: [ 'duration' ] },
105 { fields: [ 'category' ] },
106 { fields: [ 'licence' ] },
107 { fields: [ 'nsfw' ] },
108 { fields: [ 'language' ] },
109 { fields: [ 'waitTranscoding' ] },
110 { fields: [ 'state' ] },
111 { fields: [ 'remote' ] },
112 { fields: [ 'views' ] },
113 { fields: [ 'likes' ] },
114 { fields: [ 'channelId' ] },
115 {
116 fields: [ 'uuid' ],
117 unique: true
118 },
119 {
120 fields: [ 'url' ],
121 unique: true
122 }
123 ]
124
125 export enum ScopeNames {
126 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
127 FOR_API = 'FOR_API',
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_FILES = 'WITH_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
133 WITH_USER_HISTORY = 'WITH_USER_HISTORY'
134 }
135
136 type ForAPIOptions = {
137 ids: number[]
138 withFiles?: boolean
139 }
140
141 type AvailableForListIDsOptions = {
142 serverAccountId: number
143 followerActorId: number
144 includeLocalVideos: boolean
145 filter?: VideoFilter
146 categoryOneOf?: number[]
147 nsfw?: boolean
148 licenceOneOf?: number[]
149 languageOneOf?: string[]
150 tagsOneOf?: string[]
151 tagsAllOf?: string[]
152 withFiles?: boolean
153 accountId?: number
154 videoChannelId?: number
155 trendingDays?: number
156 user?: UserModel,
157 historyOfUser?: UserModel
158 }
159
160 @Scopes({
161 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
162 const accountInclude = {
163 attributes: [ 'id', 'name' ],
164 model: AccountModel.unscoped(),
165 required: true,
166 include: [
167 {
168 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
169 model: ActorModel.unscoped(),
170 required: true,
171 include: [
172 {
173 attributes: [ 'host' ],
174 model: ServerModel.unscoped(),
175 required: false
176 },
177 {
178 model: AvatarModel.unscoped(),
179 required: false
180 }
181 ]
182 }
183 ]
184 }
185
186 const videoChannelInclude = {
187 attributes: [ 'name', 'description', 'id' ],
188 model: VideoChannelModel.unscoped(),
189 required: true,
190 include: [
191 {
192 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
193 model: ActorModel.unscoped(),
194 required: true,
195 include: [
196 {
197 attributes: [ 'host' ],
198 model: ServerModel.unscoped(),
199 required: false
200 },
201 {
202 model: AvatarModel.unscoped(),
203 required: false
204 }
205 ]
206 },
207 accountInclude
208 ]
209 }
210
211 const query: IFindOptions<VideoModel> = {
212 where: {
213 id: {
214 [ Sequelize.Op.any ]: options.ids
215 }
216 },
217 include: [ videoChannelInclude ]
218 }
219
220 if (options.withFiles === true) {
221 query.include.push({
222 model: VideoFileModel.unscoped(),
223 required: true
224 })
225 }
226
227 return query
228 },
229 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
230 const query: IFindOptions<VideoModel> = {
231 raw: true,
232 attributes: [ 'id' ],
233 where: {
234 id: {
235 [ Sequelize.Op.and ]: [
236 {
237 [ Sequelize.Op.notIn ]: Sequelize.literal(
238 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
239 )
240 }
241 ]
242 },
243 channelId: {
244 [ Sequelize.Op.notIn ]: Sequelize.literal(
245 '(' +
246 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
247 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
248 ')' +
249 ')'
250 )
251 }
252 },
253 include: []
254 }
255
256 // Only list public/published videos
257 if (!options.filter || options.filter !== 'all-local') {
258 const privacyWhere = {
259 // Always list public videos
260 privacy: VideoPrivacy.PUBLIC,
261 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
262 [ Sequelize.Op.or ]: [
263 {
264 state: VideoState.PUBLISHED
265 },
266 {
267 [ Sequelize.Op.and ]: {
268 state: VideoState.TO_TRANSCODE,
269 waitTranscoding: false
270 }
271 }
272 ]
273 }
274
275 Object.assign(query.where, privacyWhere)
276 }
277
278 if (options.filter || options.accountId || options.videoChannelId) {
279 const videoChannelInclude: IIncludeOptions = {
280 attributes: [],
281 model: VideoChannelModel.unscoped(),
282 required: true
283 }
284
285 if (options.videoChannelId) {
286 videoChannelInclude.where = {
287 id: options.videoChannelId
288 }
289 }
290
291 if (options.filter || options.accountId) {
292 const accountInclude: IIncludeOptions = {
293 attributes: [],
294 model: AccountModel.unscoped(),
295 required: true
296 }
297
298 if (options.filter) {
299 accountInclude.include = [
300 {
301 attributes: [],
302 model: ActorModel.unscoped(),
303 required: true,
304 where: VideoModel.buildActorWhereWithFilter(options.filter)
305 }
306 ]
307 }
308
309 if (options.accountId) {
310 accountInclude.where = { id: options.accountId }
311 }
312
313 videoChannelInclude.include = [ accountInclude ]
314 }
315
316 query.include.push(videoChannelInclude)
317 }
318
319 if (options.followerActorId) {
320 let localVideosReq = ''
321 if (options.includeLocalVideos === true) {
322 localVideosReq = ' UNION ALL ' +
323 'SELECT "video"."id" AS "id" FROM "video" ' +
324 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
325 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
326 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
327 'WHERE "actor"."serverId" IS NULL'
328 }
329
330 // Force actorId to be a number to avoid SQL injections
331 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
332 query.where[ 'id' ][ Sequelize.Op.and ].push({
333 [ Sequelize.Op.in ]: Sequelize.literal(
334 '(' +
335 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
336 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
337 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
338 ' UNION ALL ' +
339 'SELECT "video"."id" AS "id" FROM "video" ' +
340 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
341 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
342 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
343 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
344 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
345 localVideosReq +
346 ')'
347 )
348 })
349 }
350
351 if (options.withFiles === true) {
352 query.where[ 'id' ][ Sequelize.Op.and ].push({
353 [ Sequelize.Op.in ]: Sequelize.literal(
354 '(SELECT "videoId" FROM "videoFile")'
355 )
356 })
357 }
358
359 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
360 if (options.tagsAllOf || options.tagsOneOf) {
361 const createTagsIn = (tags: string[]) => {
362 return tags.map(t => VideoModel.sequelize.escape(t))
363 .join(', ')
364 }
365
366 if (options.tagsOneOf) {
367 query.where[ 'id' ][ Sequelize.Op.and ].push({
368 [ Sequelize.Op.in ]: Sequelize.literal(
369 '(' +
370 'SELECT "videoId" FROM "videoTag" ' +
371 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
372 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
373 ')'
374 )
375 })
376 }
377
378 if (options.tagsAllOf) {
379 query.where[ 'id' ][ Sequelize.Op.and ].push({
380 [ Sequelize.Op.in ]: Sequelize.literal(
381 '(' +
382 'SELECT "videoId" FROM "videoTag" ' +
383 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
384 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
385 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
386 ')'
387 )
388 })
389 }
390 }
391
392 if (options.nsfw === true || options.nsfw === false) {
393 query.where[ 'nsfw' ] = options.nsfw
394 }
395
396 if (options.categoryOneOf) {
397 query.where[ 'category' ] = {
398 [ Sequelize.Op.or ]: options.categoryOneOf
399 }
400 }
401
402 if (options.licenceOneOf) {
403 query.where[ 'licence' ] = {
404 [ Sequelize.Op.or ]: options.licenceOneOf
405 }
406 }
407
408 if (options.languageOneOf) {
409 query.where[ 'language' ] = {
410 [ Sequelize.Op.or ]: options.languageOneOf
411 }
412 }
413
414 if (options.trendingDays) {
415 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
416
417 query.subQuery = false
418 }
419
420 if (options.historyOfUser) {
421 query.include.push({
422 model: UserVideoHistoryModel,
423 required: true,
424 where: {
425 userId: options.historyOfUser.id
426 }
427 })
428
429 // Even if the relation is n:m, we know that a user only have 0..1 video history
430 // So we won't have multiple rows for the same video
431 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
432 query.subQuery = false
433 }
434
435 return query
436 },
437 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
438 include: [
439 {
440 model: () => VideoChannelModel.unscoped(),
441 required: true,
442 include: [
443 {
444 attributes: {
445 exclude: [ 'privateKey', 'publicKey' ]
446 },
447 model: () => ActorModel.unscoped(),
448 required: true,
449 include: [
450 {
451 attributes: [ 'host' ],
452 model: () => ServerModel.unscoped(),
453 required: false
454 },
455 {
456 model: () => AvatarModel.unscoped(),
457 required: false
458 }
459 ]
460 },
461 {
462 model: () => AccountModel.unscoped(),
463 required: true,
464 include: [
465 {
466 model: () => ActorModel.unscoped(),
467 attributes: {
468 exclude: [ 'privateKey', 'publicKey' ]
469 },
470 required: true,
471 include: [
472 {
473 attributes: [ 'host' ],
474 model: () => ServerModel.unscoped(),
475 required: false
476 },
477 {
478 model: () => AvatarModel.unscoped(),
479 required: false
480 }
481 ]
482 }
483 ]
484 }
485 ]
486 }
487 ]
488 },
489 [ ScopeNames.WITH_TAGS ]: {
490 include: [ () => TagModel ]
491 },
492 [ ScopeNames.WITH_BLACKLISTED ]: {
493 include: [
494 {
495 attributes: [ 'id', 'reason' ],
496 model: () => VideoBlacklistModel,
497 required: false
498 }
499 ]
500 },
501 [ ScopeNames.WITH_FILES ]: {
502 include: [
503 {
504 model: () => VideoFileModel.unscoped(),
505 // FIXME: typings
506 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
507 required: false,
508 include: [
509 {
510 attributes: [ 'fileUrl' ],
511 model: () => VideoRedundancyModel.unscoped(),
512 required: false
513 }
514 ]
515 }
516 ]
517 },
518 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
519 include: [
520 {
521 model: () => ScheduleVideoUpdateModel.unscoped(),
522 required: false
523 }
524 ]
525 },
526 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
527 return {
528 include: [
529 {
530 attributes: [ 'currentTime' ],
531 model: UserVideoHistoryModel.unscoped(),
532 required: false,
533 where: {
534 userId
535 }
536 }
537 ]
538 }
539 }
540 })
541 @Table({
542 tableName: 'video',
543 indexes
544 })
545 export class VideoModel extends Model<VideoModel> {
546
547 @AllowNull(false)
548 @Default(DataType.UUIDV4)
549 @IsUUID(4)
550 @Column(DataType.UUID)
551 uuid: string
552
553 @AllowNull(false)
554 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
555 @Column
556 name: string
557
558 @AllowNull(true)
559 @Default(null)
560 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
561 @Column
562 category: number
563
564 @AllowNull(true)
565 @Default(null)
566 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
567 @Column
568 licence: number
569
570 @AllowNull(true)
571 @Default(null)
572 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
573 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
574 language: string
575
576 @AllowNull(false)
577 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
578 @Column
579 privacy: number
580
581 @AllowNull(false)
582 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
583 @Column
584 nsfw: boolean
585
586 @AllowNull(true)
587 @Default(null)
588 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
589 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
590 description: string
591
592 @AllowNull(true)
593 @Default(null)
594 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
595 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
596 support: string
597
598 @AllowNull(false)
599 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
600 @Column
601 duration: number
602
603 @AllowNull(false)
604 @Default(0)
605 @IsInt
606 @Min(0)
607 @Column
608 views: number
609
610 @AllowNull(false)
611 @Default(0)
612 @IsInt
613 @Min(0)
614 @Column
615 likes: number
616
617 @AllowNull(false)
618 @Default(0)
619 @IsInt
620 @Min(0)
621 @Column
622 dislikes: number
623
624 @AllowNull(false)
625 @Column
626 remote: boolean
627
628 @AllowNull(false)
629 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
630 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
631 url: string
632
633 @AllowNull(false)
634 @Column
635 commentsEnabled: boolean
636
637 @AllowNull(false)
638 @Column
639 waitTranscoding: boolean
640
641 @AllowNull(false)
642 @Default(null)
643 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
644 @Column
645 state: VideoState
646
647 @CreatedAt
648 createdAt: Date
649
650 @UpdatedAt
651 updatedAt: Date
652
653 @AllowNull(false)
654 @Default(Sequelize.NOW)
655 @Column
656 publishedAt: Date
657
658 @ForeignKey(() => VideoChannelModel)
659 @Column
660 channelId: number
661
662 @BelongsTo(() => VideoChannelModel, {
663 foreignKey: {
664 allowNull: true
665 },
666 hooks: true
667 })
668 VideoChannel: VideoChannelModel
669
670 @BelongsToMany(() => TagModel, {
671 foreignKey: 'videoId',
672 through: () => VideoTagModel,
673 onDelete: 'CASCADE'
674 })
675 Tags: TagModel[]
676
677 @HasMany(() => VideoAbuseModel, {
678 foreignKey: {
679 name: 'videoId',
680 allowNull: false
681 },
682 onDelete: 'cascade'
683 })
684 VideoAbuses: VideoAbuseModel[]
685
686 @HasMany(() => VideoFileModel, {
687 foreignKey: {
688 name: 'videoId',
689 allowNull: false
690 },
691 hooks: true,
692 onDelete: 'cascade'
693 })
694 VideoFiles: VideoFileModel[]
695
696 @HasMany(() => VideoShareModel, {
697 foreignKey: {
698 name: 'videoId',
699 allowNull: false
700 },
701 onDelete: 'cascade'
702 })
703 VideoShares: VideoShareModel[]
704
705 @HasMany(() => AccountVideoRateModel, {
706 foreignKey: {
707 name: 'videoId',
708 allowNull: false
709 },
710 onDelete: 'cascade'
711 })
712 AccountVideoRates: AccountVideoRateModel[]
713
714 @HasMany(() => VideoCommentModel, {
715 foreignKey: {
716 name: 'videoId',
717 allowNull: false
718 },
719 onDelete: 'cascade',
720 hooks: true
721 })
722 VideoComments: VideoCommentModel[]
723
724 @HasMany(() => VideoViewModel, {
725 foreignKey: {
726 name: 'videoId',
727 allowNull: false
728 },
729 onDelete: 'cascade'
730 })
731 VideoViews: VideoViewModel[]
732
733 @HasMany(() => UserVideoHistoryModel, {
734 foreignKey: {
735 name: 'videoId',
736 allowNull: false
737 },
738 onDelete: 'cascade'
739 })
740 UserVideoHistories: UserVideoHistoryModel[]
741
742 @HasOne(() => ScheduleVideoUpdateModel, {
743 foreignKey: {
744 name: 'videoId',
745 allowNull: false
746 },
747 onDelete: 'cascade'
748 })
749 ScheduleVideoUpdate: ScheduleVideoUpdateModel
750
751 @HasOne(() => VideoBlacklistModel, {
752 foreignKey: {
753 name: 'videoId',
754 allowNull: false
755 },
756 onDelete: 'cascade'
757 })
758 VideoBlacklist: VideoBlacklistModel
759
760 @HasMany(() => VideoCaptionModel, {
761 foreignKey: {
762 name: 'videoId',
763 allowNull: false
764 },
765 onDelete: 'cascade',
766 hooks: true,
767 [ 'separate' as any ]: true
768 })
769 VideoCaptions: VideoCaptionModel[]
770
771 @BeforeDestroy
772 static async sendDelete (instance: VideoModel, options) {
773 if (instance.isOwned()) {
774 if (!instance.VideoChannel) {
775 instance.VideoChannel = await instance.$get('VideoChannel', {
776 include: [
777 {
778 model: AccountModel,
779 include: [ ActorModel ]
780 }
781 ],
782 transaction: options.transaction
783 }) as VideoChannelModel
784 }
785
786 return sendDeleteVideo(instance, options.transaction)
787 }
788
789 return undefined
790 }
791
792 @BeforeDestroy
793 static async removeFiles (instance: VideoModel) {
794 const tasks: Promise<any>[] = []
795
796 logger.info('Removing files of video %s.', instance.url)
797
798 tasks.push(instance.removeThumbnail())
799
800 if (instance.isOwned()) {
801 if (!Array.isArray(instance.VideoFiles)) {
802 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
803 }
804
805 tasks.push(instance.removePreview())
806
807 // Remove physical files and torrents
808 instance.VideoFiles.forEach(file => {
809 tasks.push(instance.removeFile(file))
810 tasks.push(instance.removeTorrent(file))
811 })
812 }
813
814 // Do not wait video deletion because we could be in a transaction
815 Promise.all(tasks)
816 .catch(err => {
817 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
818 })
819
820 return undefined
821 }
822
823 static list () {
824 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
825 }
826
827 static listLocal () {
828 const query = {
829 where: {
830 remote: false
831 }
832 }
833
834 return VideoModel.scope(ScopeNames.WITH_FILES).findAll(query)
835 }
836
837 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
838 function getRawQuery (select: string) {
839 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
840 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
841 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
842 'WHERE "Account"."actorId" = ' + actorId
843 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
844 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
845 'WHERE "VideoShare"."actorId" = ' + actorId
846
847 return `(${queryVideo}) UNION (${queryVideoShare})`
848 }
849
850 const rawQuery = getRawQuery('"Video"."id"')
851 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
852
853 const query = {
854 distinct: true,
855 offset: start,
856 limit: count,
857 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
858 where: {
859 id: {
860 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
861 },
862 [ Sequelize.Op.or ]: [
863 { privacy: VideoPrivacy.PUBLIC },
864 { privacy: VideoPrivacy.UNLISTED }
865 ]
866 },
867 include: [
868 {
869 attributes: [ 'language' ],
870 model: VideoCaptionModel.unscoped(),
871 required: false
872 },
873 {
874 attributes: [ 'id', 'url' ],
875 model: VideoShareModel.unscoped(),
876 required: false,
877 // We only want videos shared by this actor
878 where: {
879 [ Sequelize.Op.and ]: [
880 {
881 id: {
882 [ Sequelize.Op.not ]: null
883 }
884 },
885 {
886 actorId
887 }
888 ]
889 },
890 include: [
891 {
892 attributes: [ 'id', 'url' ],
893 model: ActorModel.unscoped()
894 }
895 ]
896 },
897 {
898 model: VideoChannelModel.unscoped(),
899 required: true,
900 include: [
901 {
902 attributes: [ 'name' ],
903 model: AccountModel.unscoped(),
904 required: true,
905 include: [
906 {
907 attributes: [ 'id', 'url', 'followersUrl' ],
908 model: ActorModel.unscoped(),
909 required: true
910 }
911 ]
912 },
913 {
914 attributes: [ 'id', 'url', 'followersUrl' ],
915 model: ActorModel.unscoped(),
916 required: true
917 }
918 ]
919 },
920 VideoFileModel,
921 TagModel
922 ]
923 }
924
925 return Bluebird.all([
926 // FIXME: typing issue
927 VideoModel.findAll(query as any),
928 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
929 ]).then(([ rows, totals ]) => {
930 // totals: totalVideos + totalVideoShares
931 let totalVideos = 0
932 let totalVideoShares = 0
933 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
934 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
935
936 const total = totalVideos + totalVideoShares
937 return {
938 data: rows,
939 total: total
940 }
941 })
942 }
943
944 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
945 const query: IFindOptions<VideoModel> = {
946 offset: start,
947 limit: count,
948 order: getVideoSort(sort),
949 include: [
950 {
951 model: VideoChannelModel,
952 required: true,
953 include: [
954 {
955 model: AccountModel,
956 where: {
957 id: accountId
958 },
959 required: true
960 }
961 ]
962 },
963 {
964 model: ScheduleVideoUpdateModel,
965 required: false
966 },
967 {
968 model: VideoBlacklistModel,
969 required: false
970 }
971 ]
972 }
973
974 if (withFiles === true) {
975 query.include.push({
976 model: VideoFileModel.unscoped(),
977 required: true
978 })
979 }
980
981 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
982 return {
983 data: rows,
984 total: count
985 }
986 })
987 }
988
989 static async listForApi (options: {
990 start: number,
991 count: number,
992 sort: string,
993 nsfw: boolean,
994 includeLocalVideos: boolean,
995 withFiles: boolean,
996 categoryOneOf?: number[],
997 licenceOneOf?: number[],
998 languageOneOf?: string[],
999 tagsOneOf?: string[],
1000 tagsAllOf?: string[],
1001 filter?: VideoFilter,
1002 accountId?: number,
1003 videoChannelId?: number,
1004 followerActorId?: number
1005 trendingDays?: number,
1006 user?: UserModel,
1007 historyOfUser?: UserModel
1008 }, countVideos = true) {
1009 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1010 throw new Error('Try to filter all-local but no user has not the see all videos right')
1011 }
1012
1013 const query: IFindOptions<VideoModel> = {
1014 offset: options.start,
1015 limit: options.count,
1016 order: getVideoSort(options.sort)
1017 }
1018
1019 let trendingDays: number
1020 if (options.sort.endsWith('trending')) {
1021 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1022
1023 query.group = 'VideoModel.id'
1024 }
1025
1026 const serverActor = await getServerActor()
1027
1028 // followerActorId === null has a meaning, so just check undefined
1029 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1030
1031 const queryOptions = {
1032 followerActorId,
1033 serverAccountId: serverActor.Account.id,
1034 nsfw: options.nsfw,
1035 categoryOneOf: options.categoryOneOf,
1036 licenceOneOf: options.licenceOneOf,
1037 languageOneOf: options.languageOneOf,
1038 tagsOneOf: options.tagsOneOf,
1039 tagsAllOf: options.tagsAllOf,
1040 filter: options.filter,
1041 withFiles: options.withFiles,
1042 accountId: options.accountId,
1043 videoChannelId: options.videoChannelId,
1044 includeLocalVideos: options.includeLocalVideos,
1045 user: options.user,
1046 historyOfUser: options.historyOfUser,
1047 trendingDays
1048 }
1049
1050 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1051 }
1052
1053 static async searchAndPopulateAccountAndServer (options: {
1054 includeLocalVideos: boolean
1055 search?: string
1056 start?: number
1057 count?: number
1058 sort?: string
1059 startDate?: string // ISO 8601
1060 endDate?: string // ISO 8601
1061 nsfw?: boolean
1062 categoryOneOf?: number[]
1063 licenceOneOf?: number[]
1064 languageOneOf?: string[]
1065 tagsOneOf?: string[]
1066 tagsAllOf?: string[]
1067 durationMin?: number // seconds
1068 durationMax?: number // seconds
1069 user?: UserModel,
1070 filter?: VideoFilter
1071 }) {
1072 const whereAnd = []
1073
1074 if (options.startDate || options.endDate) {
1075 const publishedAtRange = {}
1076
1077 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1078 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1079
1080 whereAnd.push({ publishedAt: publishedAtRange })
1081 }
1082
1083 if (options.durationMin || options.durationMax) {
1084 const durationRange = {}
1085
1086 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1087 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1088
1089 whereAnd.push({ duration: durationRange })
1090 }
1091
1092 const attributesInclude = []
1093 const escapedSearch = VideoModel.sequelize.escape(options.search)
1094 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1095 if (options.search) {
1096 whereAnd.push(
1097 {
1098 id: {
1099 [ Sequelize.Op.in ]: Sequelize.literal(
1100 '(' +
1101 'SELECT "video"."id" FROM "video" ' +
1102 'WHERE ' +
1103 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1104 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1105 'UNION ALL ' +
1106 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1107 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1108 'WHERE "tag"."name" = ' + escapedSearch +
1109 ')'
1110 )
1111 }
1112 }
1113 )
1114
1115 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1116 }
1117
1118 // Cannot search on similarity if we don't have a search
1119 if (!options.search) {
1120 attributesInclude.push(
1121 Sequelize.literal('0 as similarity')
1122 )
1123 }
1124
1125 const query: IFindOptions<VideoModel> = {
1126 attributes: {
1127 include: attributesInclude
1128 },
1129 offset: options.start,
1130 limit: options.count,
1131 order: getVideoSort(options.sort),
1132 where: {
1133 [ Sequelize.Op.and ]: whereAnd
1134 }
1135 }
1136
1137 const serverActor = await getServerActor()
1138 const queryOptions = {
1139 followerActorId: serverActor.id,
1140 serverAccountId: serverActor.Account.id,
1141 includeLocalVideos: options.includeLocalVideos,
1142 nsfw: options.nsfw,
1143 categoryOneOf: options.categoryOneOf,
1144 licenceOneOf: options.licenceOneOf,
1145 languageOneOf: options.languageOneOf,
1146 tagsOneOf: options.tagsOneOf,
1147 tagsAllOf: options.tagsAllOf,
1148 user: options.user,
1149 filter: options.filter
1150 }
1151
1152 return VideoModel.getAvailableForApi(query, queryOptions)
1153 }
1154
1155 static load (id: number | string, t?: Sequelize.Transaction) {
1156 const where = VideoModel.buildWhereIdOrUUID(id)
1157 const options = {
1158 where,
1159 transaction: t
1160 }
1161
1162 return VideoModel.findOne(options)
1163 }
1164
1165 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1166 const where = VideoModel.buildWhereIdOrUUID(id)
1167
1168 const options = {
1169 attributes: [ 'id' ],
1170 where,
1171 transaction: t
1172 }
1173
1174 return VideoModel.findOne(options)
1175 }
1176
1177 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1178 return VideoModel.scope(ScopeNames.WITH_FILES)
1179 .findById(id, { transaction: t, logging })
1180 }
1181
1182 static loadByUUIDWithFile (uuid: string) {
1183 const options = {
1184 where: {
1185 uuid
1186 }
1187 }
1188
1189 return VideoModel
1190 .scope([ ScopeNames.WITH_FILES ])
1191 .findOne(options)
1192 }
1193
1194 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1195 const query: IFindOptions<VideoModel> = {
1196 where: {
1197 url
1198 },
1199 transaction
1200 }
1201
1202 return VideoModel.findOne(query)
1203 }
1204
1205 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1206 const query: IFindOptions<VideoModel> = {
1207 where: {
1208 url
1209 },
1210 transaction
1211 }
1212
1213 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1214 }
1215
1216 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1217 const where = VideoModel.buildWhereIdOrUUID(id)
1218
1219 const options = {
1220 order: [ [ 'Tags', 'name', 'ASC' ] ],
1221 where,
1222 transaction: t
1223 }
1224
1225 const scopes = [
1226 ScopeNames.WITH_TAGS,
1227 ScopeNames.WITH_BLACKLISTED,
1228 ScopeNames.WITH_FILES,
1229 ScopeNames.WITH_ACCOUNT_DETAILS,
1230 ScopeNames.WITH_SCHEDULED_UPDATE
1231 ]
1232
1233 if (userId) {
1234 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1235 }
1236
1237 return VideoModel
1238 .scope(scopes)
1239 .findOne(options)
1240 }
1241
1242 static async getStats () {
1243 const totalLocalVideos = await VideoModel.count({
1244 where: {
1245 remote: false
1246 }
1247 })
1248 const totalVideos = await VideoModel.count()
1249
1250 let totalLocalVideoViews = await VideoModel.sum('views', {
1251 where: {
1252 remote: false
1253 }
1254 })
1255 // Sequelize could return null...
1256 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1257
1258 return {
1259 totalLocalVideos,
1260 totalLocalVideoViews,
1261 totalVideos
1262 }
1263 }
1264
1265 static incrementViews (id: number, views: number) {
1266 return VideoModel.increment('views', {
1267 by: views,
1268 where: {
1269 id
1270 }
1271 })
1272 }
1273
1274 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1275 // Instances only share videos
1276 const query = 'SELECT 1 FROM "videoShare" ' +
1277 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1278 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1279 'LIMIT 1'
1280
1281 const options = {
1282 type: Sequelize.QueryTypes.SELECT,
1283 bind: { followerActorId, videoId },
1284 raw: true
1285 }
1286
1287 return VideoModel.sequelize.query(query, options)
1288 .then(results => results.length === 1)
1289 }
1290
1291 // threshold corresponds to how many video the field should have to be returned
1292 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1293 const serverActor = await getServerActor()
1294 const followerActorId = serverActor.id
1295
1296 const scopeOptions: AvailableForListIDsOptions = {
1297 serverAccountId: serverActor.Account.id,
1298 followerActorId,
1299 includeLocalVideos: true
1300 }
1301
1302 const query: IFindOptions<VideoModel> = {
1303 attributes: [ field ],
1304 limit: count,
1305 group: field,
1306 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1307 [ Sequelize.Op.gte ]: threshold
1308 }) as any, // FIXME: typings
1309 order: [ this.sequelize.random() ]
1310 }
1311
1312 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1313 .findAll(query)
1314 .then(rows => rows.map(r => r[ field ]))
1315 }
1316
1317 static buildTrendingQuery (trendingDays: number) {
1318 return {
1319 attributes: [],
1320 subQuery: false,
1321 model: VideoViewModel,
1322 required: false,
1323 where: {
1324 startDate: {
1325 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1326 }
1327 }
1328 }
1329 }
1330
1331 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1332 if (filter && (filter === 'local' || filter === 'all-local')) {
1333 return {
1334 serverId: null
1335 }
1336 }
1337
1338 return {}
1339 }
1340
1341 private static async getAvailableForApi (
1342 query: IFindOptions<VideoModel>,
1343 options: AvailableForListIDsOptions,
1344 countVideos = true
1345 ) {
1346 const idsScope = {
1347 method: [
1348 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1349 ]
1350 }
1351
1352 // Remove trending sort on count, because it uses a group by
1353 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1354 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1355 const countScope = {
1356 method: [
1357 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1358 ]
1359 }
1360
1361 const [ count, rowsId ] = await Promise.all([
1362 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1363 VideoModel.scope(idsScope).findAll(query)
1364 ])
1365 const ids = rowsId.map(r => r.id)
1366
1367 if (ids.length === 0) return { data: [], total: count }
1368
1369 // FIXME: typings
1370 const apiScope: any[] = [
1371 {
1372 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1373 }
1374 ]
1375
1376 if (options.user) {
1377 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1378 }
1379
1380 const secondQuery = {
1381 offset: 0,
1382 limit: query.limit,
1383 attributes: query.attributes,
1384 order: [ // Keep original order
1385 Sequelize.literal(
1386 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1387 )
1388 ]
1389 }
1390 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1391
1392 return {
1393 data: rows,
1394 total: count
1395 }
1396 }
1397
1398 static getCategoryLabel (id: number) {
1399 return VIDEO_CATEGORIES[ id ] || 'Misc'
1400 }
1401
1402 static getLicenceLabel (id: number) {
1403 return VIDEO_LICENCES[ id ] || 'Unknown'
1404 }
1405
1406 static getLanguageLabel (id: string) {
1407 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1408 }
1409
1410 static getPrivacyLabel (id: number) {
1411 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1412 }
1413
1414 static getStateLabel (id: number) {
1415 return VIDEO_STATES[ id ] || 'Unknown'
1416 }
1417
1418 static buildWhereIdOrUUID (id: number | string) {
1419 return validator.isInt('' + id) ? { id } : { uuid: id }
1420 }
1421
1422 getOriginalFile () {
1423 if (Array.isArray(this.VideoFiles) === false) return undefined
1424
1425 // The original file is the file that have the higher resolution
1426 return maxBy(this.VideoFiles, file => file.resolution)
1427 }
1428
1429 getVideoFilename (videoFile: VideoFileModel) {
1430 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1431 }
1432
1433 getThumbnailName () {
1434 // We always have a copy of the thumbnail
1435 const extension = '.jpg'
1436 return this.uuid + extension
1437 }
1438
1439 getPreviewName () {
1440 const extension = '.jpg'
1441 return this.uuid + extension
1442 }
1443
1444 getTorrentFileName (videoFile: VideoFileModel) {
1445 const extension = '.torrent'
1446 return this.uuid + '-' + videoFile.resolution + extension
1447 }
1448
1449 isOwned () {
1450 return this.remote === false
1451 }
1452
1453 createPreview (videoFile: VideoFileModel) {
1454 return generateImageFromVideoFile(
1455 this.getVideoFilePath(videoFile),
1456 CONFIG.STORAGE.PREVIEWS_DIR,
1457 this.getPreviewName(),
1458 PREVIEWS_SIZE
1459 )
1460 }
1461
1462 createThumbnail (videoFile: VideoFileModel) {
1463 return generateImageFromVideoFile(
1464 this.getVideoFilePath(videoFile),
1465 CONFIG.STORAGE.THUMBNAILS_DIR,
1466 this.getThumbnailName(),
1467 THUMBNAILS_SIZE
1468 )
1469 }
1470
1471 getTorrentFilePath (videoFile: VideoFileModel) {
1472 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1473 }
1474
1475 getVideoFilePath (videoFile: VideoFileModel) {
1476 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1477 }
1478
1479 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1480 const options = {
1481 // Keep the extname, it's used by the client to stream the file inside a web browser
1482 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1483 createdBy: 'PeerTube',
1484 announceList: [
1485 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1486 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1487 ],
1488 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1489 }
1490
1491 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1492
1493 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1494 logger.info('Creating torrent %s.', filePath)
1495
1496 await writeFile(filePath, torrent)
1497
1498 const parsedTorrent = parseTorrent(torrent)
1499 videoFile.infoHash = parsedTorrent.infoHash
1500 }
1501
1502 getEmbedStaticPath () {
1503 return '/videos/embed/' + this.uuid
1504 }
1505
1506 getThumbnailStaticPath () {
1507 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1508 }
1509
1510 getPreviewStaticPath () {
1511 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1512 }
1513
1514 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1515 return videoModelToFormattedJSON(this, options)
1516 }
1517
1518 toFormattedDetailsJSON (): VideoDetails {
1519 return videoModelToFormattedDetailsJSON(this)
1520 }
1521
1522 getFormattedVideoFilesJSON (): VideoFile[] {
1523 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1524 }
1525
1526 toActivityPubObject (): VideoTorrentObject {
1527 return videoModelToActivityPubObject(this)
1528 }
1529
1530 getTruncatedDescription () {
1531 if (!this.description) return null
1532
1533 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1534 return peertubeTruncate(this.description, maxLength)
1535 }
1536
1537 getOriginalFileResolution () {
1538 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1539
1540 return getVideoFileResolution(originalFilePath)
1541 }
1542
1543 getDescriptionAPIPath () {
1544 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1545 }
1546
1547 removeThumbnail () {
1548 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1549 return remove(thumbnailPath)
1550 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1551 }
1552
1553 removePreview () {
1554 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1555 return remove(previewPath)
1556 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1557 }
1558
1559 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1560 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1561
1562 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1563 return remove(filePath)
1564 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1565 }
1566
1567 removeTorrent (videoFile: VideoFileModel) {
1568 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1569 return remove(torrentPath)
1570 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1571 }
1572
1573 isOutdated () {
1574 if (this.isOwned()) return false
1575
1576 const now = Date.now()
1577 const createdAtTime = this.createdAt.getTime()
1578 const updatedAtTime = this.updatedAt.getTime()
1579
1580 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1581 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1582 }
1583
1584 setAsRefreshed () {
1585 this.changed('updatedAt', true)
1586
1587 return this.save()
1588 }
1589
1590 getBaseUrls () {
1591 let baseUrlHttp
1592 let baseUrlWs
1593
1594 if (this.isOwned()) {
1595 baseUrlHttp = CONFIG.WEBSERVER.URL
1596 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1597 } else {
1598 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1599 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1600 }
1601
1602 return { baseUrlHttp, baseUrlWs }
1603 }
1604
1605 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1606 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1607 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1608 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1609
1610 const redundancies = videoFile.RedundancyVideos
1611 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1612
1613 const magnetHash = {
1614 xs,
1615 announce,
1616 urlList,
1617 infoHash: videoFile.infoHash,
1618 name: this.name
1619 }
1620
1621 return magnetUtil.encode(magnetHash)
1622 }
1623
1624 getThumbnailUrl (baseUrlHttp: string) {
1625 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1626 }
1627
1628 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1629 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1630 }
1631
1632 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1633 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1634 }
1635
1636 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1637 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1638 }
1639
1640 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1641 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1642 }
1643
1644 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1645 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1646 }
1647 }