1 import * as Bluebird from 'bluebird'
2 import { map, 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'
28 } from 'sequelize-typescript'
29 import { VideoPrivacy, VideoResolution } from '../../../shared'
30 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
31 import { Video, VideoDetails } from '../../../shared/models/videos'
32 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
33 import { activityPubCollection } from '../../helpers/activitypub'
35 createTorrentPromise, peertubeTruncate, renamePromise, statPromise, unlinkPromise,
37 } from '../../helpers/core-utils'
38 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
39 import { isBooleanValid } from '../../helpers/custom-validators/misc'
42 isVideoDescriptionValid,
49 } from '../../helpers/custom-validators/videos'
50 import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
51 import { logger } from '../../helpers/logger'
52 import { getServerActor } from '../../helpers/utils'
65 } from '../../initializers'
67 getVideoCommentsActivityPubUrl,
68 getVideoDislikesActivityPubUrl,
69 getVideoLikesActivityPubUrl,
70 getVideoSharesActivityPubUrl
71 } from '../../lib/activitypub'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
73 import { AccountModel } from '../account/account'
74 import { AccountVideoRateModel } from '../account/account-video-rate'
75 import { ActorModel } from '../activitypub/actor'
76 import { AvatarModel } from '../avatar/avatar'
77 import { ServerModel } from '../server/server'
78 import { getSort, throwIfNotValid } from '../utils'
79 import { TagModel } from './tag'
80 import { VideoAbuseModel } from './video-abuse'
81 import { VideoChannelModel } from './video-channel'
82 import { VideoCommentModel } from './video-comment'
83 import { VideoFileModel } from './video-file'
84 import { VideoShareModel } from './video-share'
85 import { VideoTagModel } from './video-tag'
88 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
89 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
90 WITH_TAGS = 'WITH_TAGS',
91 WITH_FILES = 'WITH_FILES',
92 WITH_SHARES = 'WITH_SHARES',
93 WITH_RATES = 'WITH_RATES',
94 WITH_COMMENTS = 'WITH_COMMENTS'
98 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number, filter?: VideoFilter) => ({
101 [Sequelize.Op.notIn]: Sequelize.literal(
102 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
104 [ Sequelize.Op.in ]: Sequelize.literal(
106 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
107 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
108 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
110 'SELECT "video"."id" AS "id" FROM "video" ' +
111 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
112 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
113 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
114 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
115 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
119 privacy: VideoPrivacy.PUBLIC
123 attributes: [ 'name', 'description' ],
124 model: VideoChannelModel.unscoped(),
128 attributes: [ 'name' ],
129 model: AccountModel.unscoped(),
133 attributes: [ 'preferredUsername', 'url', 'serverId' ],
134 model: ActorModel.unscoped(),
136 where: VideoModel.buildActorWhereWithFilter(filter),
139 attributes: [ 'host' ],
140 model: ServerModel.unscoped(),
144 model: AvatarModel.unscoped(),
155 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
158 model: () => VideoChannelModel.unscoped(),
163 exclude: [ 'privateKey', 'publicKey' ]
165 model: () => ActorModel.unscoped(),
169 attributes: [ 'host' ],
170 model: () => ServerModel.unscoped(),
176 model: () => AccountModel.unscoped(),
180 model: () => ActorModel.unscoped(),
182 exclude: [ 'privateKey', 'publicKey' ]
187 attributes: [ 'host' ],
188 model: () => ServerModel.unscoped(),
192 model: () => AvatarModel.unscoped(),
203 [ScopeNames.WITH_TAGS]: {
204 include: [ () => TagModel ]
206 [ScopeNames.WITH_FILES]: {
209 model: () => VideoFileModel.unscoped(),
214 [ScopeNames.WITH_SHARES]: {
217 model: () => VideoShareModel.unscoped()
221 [ScopeNames.WITH_RATES]: {
224 model: () => AccountVideoRateModel,
227 model: () => AccountModel.unscoped(),
231 attributes: [ 'url' ],
232 model: () => ActorModel.unscoped()
240 [ScopeNames.WITH_COMMENTS]: {
243 model: () => VideoCommentModel.unscoped()
255 fields: [ 'createdAt' ]
258 fields: [ 'duration' ]
270 fields: [ 'channelId' ]
273 fields: [ 'id', 'privacy' ]
281 export class VideoModel extends Model<VideoModel> {
284 @Default(DataType.UUIDV4)
286 @Column(DataType.UUID)
290 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
296 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
302 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
308 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
313 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
318 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
324 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
325 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
330 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
331 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
335 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
365 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
366 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
371 commentsEnabled: boolean
380 @Default(Sequelize.NOW)
384 @ForeignKey(() => VideoChannelModel)
388 @BelongsTo(() => VideoChannelModel, {
394 VideoChannel: VideoChannelModel
396 @BelongsToMany(() => TagModel, {
397 foreignKey: 'videoId',
398 through: () => VideoTagModel,
403 @HasMany(() => VideoAbuseModel, {
410 VideoAbuses: VideoAbuseModel[]
412 @HasMany(() => VideoFileModel, {
419 VideoFiles: VideoFileModel[]
421 @HasMany(() => VideoShareModel, {
428 VideoShares: VideoShareModel[]
430 @HasMany(() => AccountVideoRateModel, {
437 AccountVideoRates: AccountVideoRateModel[]
439 @HasMany(() => VideoCommentModel, {
447 VideoComments: VideoCommentModel[]
450 static async sendDelete (instance: VideoModel, options) {
451 if (instance.isOwned()) {
452 if (!instance.VideoChannel) {
453 instance.VideoChannel = await instance.$get('VideoChannel', {
457 include: [ ActorModel ]
460 transaction: options.transaction
461 }) as VideoChannelModel
464 logger.debug('Sending delete of video %s.', instance.url)
466 return sendDeleteVideo(instance, options.transaction)
473 static async removeFilesAndSendDelete (instance: VideoModel) {
474 const tasks: Promise<any>[] = []
476 tasks.push(instance.removeThumbnail())
478 if (instance.isOwned()) {
479 if (!Array.isArray(instance.VideoFiles)) {
480 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
483 tasks.push(instance.removePreview())
485 // Remove physical files and torrents
486 instance.VideoFiles.forEach(file => {
487 tasks.push(instance.removeFile(file))
488 tasks.push(instance.removeTorrent(file))
492 return Promise.all(tasks)
494 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
499 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
502 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
503 function getRawQuery (select: string) {
504 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
505 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
506 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
507 'WHERE "Account"."actorId" = ' + actorId
508 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
509 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
510 'WHERE "VideoShare"."actorId" = ' + actorId
512 return `(${queryVideo}) UNION (${queryVideoShare})`
515 const rawQuery = getRawQuery('"Video"."id"')
516 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
522 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
525 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
528 { privacy: VideoPrivacy.PUBLIC },
529 { privacy: VideoPrivacy.UNLISTED }
534 attributes: [ 'id', 'url' ],
535 model: VideoShareModel.unscoped(),
538 [Sequelize.Op.and]: [
541 [Sequelize.Op.not]: null
551 attributes: [ 'id', 'url' ],
552 model: ActorModel.unscoped()
557 model: VideoChannelModel.unscoped(),
561 attributes: [ 'name' ],
562 model: AccountModel.unscoped(),
566 attributes: [ 'id', 'url' ],
567 model: ActorModel.unscoped(),
573 attributes: [ 'id', 'url' ],
574 model: ActorModel.unscoped(),
580 attributes: [ 'type' ],
581 model: AccountVideoRateModel,
585 attributes: [ 'id' ],
586 model: AccountModel.unscoped(),
589 attributes: [ 'url' ],
590 model: ActorModel.unscoped(),
593 attributes: [ 'host' ],
604 attributes: [ 'url' ],
605 model: VideoCommentModel,
613 return Bluebird.all([
614 // FIXME: typing issue
615 VideoModel.findAll(query as any),
616 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
617 ]).then(([ rows, totals ]) => {
618 // totals: totalVideos + totalVideoShares
620 let totalVideoShares = 0
621 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
622 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
624 const total = totalVideos + totalVideoShares
632 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
636 order: getSort(sort),
639 model: VideoChannelModel,
654 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
662 static async listForApi (start: number, count: number, sort: string, filter?: VideoFilter) {
669 const serverActor = await getServerActor()
671 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id, filter ] })
672 .findAndCountAll(query)
673 .then(({ rows, count }) => {
681 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
682 const query: IFindOptions<VideoModel> = {
685 order: getSort(sort),
690 [ Sequelize.Op.iLike ]: '%' + value + '%'
694 preferredUsername: Sequelize.where(Sequelize.col('preferredUsername'), {
695 [ Sequelize.Op.iLike ]: '%' + value + '%'
699 host: Sequelize.where(Sequelize.col('host'), {
700 [ Sequelize.Op.iLike ]: '%' + value + '%'
707 const serverActor = await getServerActor()
709 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
710 .findAndCountAll(query).then(({ rows, count }) => {
718 static load (id: number) {
719 return VideoModel.findById(id)
722 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
723 const query: IFindOptions<VideoModel> = {
729 if (t !== undefined) query.transaction = t
731 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
734 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
735 const query: IFindOptions<VideoModel> = {
744 if (t !== undefined) query.transaction = t
746 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
749 static loadAndPopulateAccountAndServerAndTags (id: number) {
751 order: [ [ 'Tags', 'name', 'ASC' ] ]
755 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
756 .findById(id, options)
759 static loadByUUID (uuid: string) {
767 .scope([ ScopeNames.WITH_FILES ])
771 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
773 order: [ [ 'Tags', 'name', 'ASC' ] ],
780 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
784 static loadAndPopulateAll (id: number) {
786 order: [ [ 'Tags', 'name', 'ASC' ] ],
794 ScopeNames.WITH_RATES,
795 ScopeNames.WITH_SHARES,
796 ScopeNames.WITH_TAGS,
797 ScopeNames.WITH_FILES,
798 ScopeNames.WITH_ACCOUNT_DETAILS,
799 ScopeNames.WITH_COMMENTS
804 static async getStats () {
805 const totalLocalVideos = await VideoModel.count({
810 const totalVideos = await VideoModel.count()
812 let totalLocalVideoViews = await VideoModel.sum('views', {
817 // Sequelize could return null...
818 if (!totalLocalVideoViews) totalLocalVideoViews = 0
822 totalLocalVideoViews,
827 private static buildActorWhereWithFilter (filter?: VideoFilter) {
828 if (filter && filter === 'local') {
837 private static getCategoryLabel (id: number) {
838 let categoryLabel = VIDEO_CATEGORIES[id]
839 if (!categoryLabel) categoryLabel = 'Misc'
844 private static getLicenceLabel (id: number) {
845 let licenceLabel = VIDEO_LICENCES[id]
846 if (!licenceLabel) licenceLabel = 'Unknown'
851 private static getLanguageLabel (id: number) {
852 let languageLabel = VIDEO_LANGUAGES[id]
853 if (!languageLabel) languageLabel = 'Unknown'
859 if (Array.isArray(this.VideoFiles) === false) return undefined
861 // The original file is the file that have the higher resolution
862 return maxBy(this.VideoFiles, file => file.resolution)
865 getVideoFilename (videoFile: VideoFileModel) {
866 return this.uuid + '-' + videoFile.resolution + videoFile.extname
869 getThumbnailName () {
870 // We always have a copy of the thumbnail
871 const extension = '.jpg'
872 return this.uuid + extension
876 const extension = '.jpg'
877 return this.uuid + extension
880 getTorrentFileName (videoFile: VideoFileModel) {
881 const extension = '.torrent'
882 return this.uuid + '-' + videoFile.resolution + extension
886 return this.remote === false
889 createPreview (videoFile: VideoFileModel) {
890 return generateImageFromVideoFile(
891 this.getVideoFilePath(videoFile),
892 CONFIG.STORAGE.PREVIEWS_DIR,
893 this.getPreviewName(),
898 createThumbnail (videoFile: VideoFileModel) {
899 return generateImageFromVideoFile(
900 this.getVideoFilePath(videoFile),
901 CONFIG.STORAGE.THUMBNAILS_DIR,
902 this.getThumbnailName(),
907 getVideoFilePath (videoFile: VideoFileModel) {
908 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
911 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
914 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
915 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
918 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
922 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
924 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
925 logger.info('Creating torrent %s.', filePath)
927 await writeFilePromise(filePath, torrent)
929 const parsedTorrent = parseTorrent(torrent)
930 videoFile.infoHash = parsedTorrent.infoHash
934 return '/videos/embed/' + this.uuid
937 getThumbnailPath () {
938 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
942 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
945 toFormattedJSON (): Video {
946 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
954 label: VideoModel.getCategoryLabel(this.category)
958 label: VideoModel.getLicenceLabel(this.licence)
962 label: VideoModel.getLanguageLabel(this.language)
965 description: this.getTruncatedDescription(),
966 isLocal: this.isOwned(),
967 duration: this.duration,
970 dislikes: this.dislikes,
971 thumbnailPath: this.getThumbnailPath(),
972 previewPath: this.getPreviewPath(),
973 embedPath: this.getEmbedPath(),
974 createdAt: this.createdAt,
975 updatedAt: this.updatedAt,
976 publishedAt: this.publishedAt,
978 name: formattedAccount.name,
979 displayName: formattedAccount.displayName,
980 url: formattedAccount.url,
981 host: formattedAccount.host,
982 avatar: formattedAccount.avatar
987 toFormattedDetailsJSON (): VideoDetails {
988 const formattedJson = this.toFormattedJSON()
990 // Maybe our server is not up to date and there are new privacy settings since our version
991 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
992 if (!privacyLabel) privacyLabel = 'Unknown'
994 const detailsJson = {
999 support: this.support,
1000 descriptionPath: this.getDescriptionPath(),
1001 channel: this.VideoChannel.toFormattedJSON(),
1002 account: this.VideoChannel.Account.toFormattedJSON(),
1003 tags: map<TagModel, string>(this.Tags, 'name'),
1004 commentsEnabled: this.commentsEnabled,
1008 // Format and sort video files
1009 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1010 detailsJson.files = this.VideoFiles
1012 let resolutionLabel = videoFile.resolution + 'p'
1016 id: videoFile.resolution,
1017 label: resolutionLabel
1019 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1020 size: videoFile.size,
1021 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1022 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1026 if (a.resolution.id < b.resolution.id) return 1
1027 if (a.resolution.id === b.resolution.id) return 0
1031 return Object.assign(formattedJson, detailsJson)
1034 toActivityPubObject (): VideoTorrentObject {
1035 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1036 if (!this.Tags) this.Tags = []
1038 const tag = this.Tags.map(t => ({
1039 type: 'Hashtag' as 'Hashtag',
1044 if (this.language) {
1046 identifier: this.language + '',
1047 name: VideoModel.getLanguageLabel(this.language)
1052 if (this.category) {
1054 identifier: this.category + '',
1055 name: VideoModel.getCategoryLabel(this.category)
1062 identifier: this.licence + '',
1063 name: VideoModel.getLicenceLabel(this.licence)
1070 if (Array.isArray(this.AccountVideoRates)) {
1071 const res = this.toRatesActivityPubObjects()
1072 likesObject = res.likesObject
1073 dislikesObject = res.dislikesObject
1077 if (Array.isArray(this.VideoShares)) {
1078 sharesObject = this.toAnnouncesActivityPubObject()
1082 if (Array.isArray(this.VideoComments)) {
1083 commentsObject = this.toCommentsActivityPubObject()
1087 for (const file of this.VideoFiles) {
1090 mimeType: 'video/' + file.extname.replace('.', ''),
1091 href: this.getVideoFileUrl(file, baseUrlHttp),
1092 width: file.resolution,
1098 mimeType: 'application/x-bittorrent',
1099 href: this.getTorrentUrl(file, baseUrlHttp),
1100 width: file.resolution
1105 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1106 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1107 width: file.resolution
1111 // Add video url too
1114 mimeType: 'text/html',
1115 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1119 type: 'Video' as 'Video',
1122 duration: this.getActivityStreamDuration(),
1129 sensitive: this.nsfw,
1130 commentsEnabled: this.commentsEnabled,
1131 published: this.publishedAt.toISOString(),
1132 updated: this.updatedAt.toISOString(),
1133 mediaType: 'text/markdown',
1134 content: this.getTruncatedDescription(),
1135 support: this.support,
1138 url: this.getThumbnailUrl(baseUrlHttp),
1139 mediaType: 'image/jpeg',
1140 width: THUMBNAILS_SIZE.width,
1141 height: THUMBNAILS_SIZE.height
1145 dislikes: dislikesObject,
1146 shares: sharesObject,
1147 comments: commentsObject,
1151 id: this.VideoChannel.Account.Actor.url
1155 id: this.VideoChannel.Actor.url
1161 toAnnouncesActivityPubObject () {
1162 const shares: string[] = []
1164 for (const videoShare of this.VideoShares) {
1165 shares.push(videoShare.url)
1168 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1171 toCommentsActivityPubObject () {
1172 const comments: string[] = []
1174 for (const videoComment of this.VideoComments) {
1175 comments.push(videoComment.url)
1178 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1181 toRatesActivityPubObjects () {
1182 const likes: string[] = []
1183 const dislikes: string[] = []
1185 for (const rate of this.AccountVideoRates) {
1186 if (rate.type === 'like') {
1187 likes.push(rate.Account.Actor.url)
1188 } else if (rate.type === 'dislike') {
1189 dislikes.push(rate.Account.Actor.url)
1193 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1194 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1196 return { likesObject, dislikesObject }
1199 getTruncatedDescription () {
1200 if (!this.description) return null
1202 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1203 return peertubeTruncate(this.description, maxLength)
1206 optimizeOriginalVideofile = async function () {
1207 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1208 const newExtname = '.mp4'
1209 const inputVideoFile = this.getOriginalFile()
1210 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1211 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1213 const transcodeOptions = {
1214 inputPath: videoInputPath,
1215 outputPath: videoOutputPath
1218 // Could be very long!
1219 await transcode(transcodeOptions)
1222 await unlinkPromise(videoInputPath)
1224 // Important to do this before getVideoFilename() to take in account the new file extension
1225 inputVideoFile.set('extname', newExtname)
1227 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1228 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1230 inputVideoFile.set('size', stats.size)
1232 await this.createTorrentAndSetInfoHash(inputVideoFile)
1233 await inputVideoFile.save()
1236 // Auto destruction...
1237 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1243 transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
1244 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1245 const extname = '.mp4'
1247 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1248 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1250 const newVideoFile = new VideoFileModel({
1256 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1258 const transcodeOptions = {
1259 inputPath: videoInputPath,
1260 outputPath: videoOutputPath,
1265 await transcode(transcodeOptions)
1267 const stats = await statPromise(videoOutputPath)
1269 newVideoFile.set('size', stats.size)
1271 await this.createTorrentAndSetInfoHash(newVideoFile)
1273 await newVideoFile.save()
1275 this.VideoFiles.push(newVideoFile)
1278 getOriginalFileResolution () {
1279 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1281 return getVideoFileResolution(originalFilePath)
1284 getDescriptionPath () {
1285 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1288 removeThumbnail () {
1289 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1290 return unlinkPromise(thumbnailPath)
1294 // Same name than video thumbnail
1295 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1298 removeFile (videoFile: VideoFileModel) {
1299 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1300 return unlinkPromise(filePath)
1303 removeTorrent (videoFile: VideoFileModel) {
1304 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1305 return unlinkPromise(torrentPath)
1308 getActivityStreamDuration () {
1309 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1310 return 'PT' + this.duration + 'S'
1313 private getBaseUrls () {
1317 if (this.isOwned()) {
1318 baseUrlHttp = CONFIG.WEBSERVER.URL
1319 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1321 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1322 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1325 return { baseUrlHttp, baseUrlWs }
1328 private getThumbnailUrl (baseUrlHttp: string) {
1329 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1332 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1333 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1336 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1337 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1340 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1341 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1342 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1343 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1345 const magnetHash = {
1349 infoHash: videoFile.infoHash,
1353 return magnetUtil.encode(magnetHash)