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, VideoFile } 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, withFiles?: boolean) => {
99 const query: IFindOptions<VideoModel> = {
102 [Sequelize.Op.notIn]: Sequelize.literal(
103 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
105 [ Sequelize.Op.in ]: Sequelize.literal(
107 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
108 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
109 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
111 'SELECT "video"."id" AS "id" FROM "video" ' +
112 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
113 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
114 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
115 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
116 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
120 privacy: VideoPrivacy.PUBLIC
124 attributes: [ 'name', 'description' ],
125 model: VideoChannelModel.unscoped(),
129 attributes: [ 'name' ],
130 model: AccountModel.unscoped(),
134 attributes: [ 'preferredUsername', 'url', 'serverId', 'avatarId' ],
135 model: ActorModel.unscoped(),
137 where: VideoModel.buildActorWhereWithFilter(filter),
140 attributes: [ 'host' ],
141 model: ServerModel.unscoped(),
145 model: AvatarModel.unscoped(),
157 if (withFiles === true) {
159 model: VideoFileModel.unscoped(),
166 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
169 model: () => VideoChannelModel.unscoped(),
174 exclude: [ 'privateKey', 'publicKey' ]
176 model: () => ActorModel.unscoped(),
180 attributes: [ 'host' ],
181 model: () => ServerModel.unscoped(),
187 model: () => AccountModel.unscoped(),
191 model: () => ActorModel.unscoped(),
193 exclude: [ 'privateKey', 'publicKey' ]
198 attributes: [ 'host' ],
199 model: () => ServerModel.unscoped(),
203 model: () => AvatarModel.unscoped(),
214 [ScopeNames.WITH_TAGS]: {
215 include: [ () => TagModel ]
217 [ScopeNames.WITH_FILES]: {
220 model: () => VideoFileModel.unscoped(),
225 [ScopeNames.WITH_SHARES]: {
228 model: () => VideoShareModel.unscoped()
232 [ScopeNames.WITH_RATES]: {
235 model: () => AccountVideoRateModel,
238 model: () => AccountModel.unscoped(),
242 attributes: [ 'url' ],
243 model: () => ActorModel.unscoped()
251 [ScopeNames.WITH_COMMENTS]: {
254 model: () => VideoCommentModel.unscoped()
266 fields: [ 'createdAt' ]
269 fields: [ 'duration' ]
281 fields: [ 'channelId' ]
284 fields: [ 'id', 'privacy' ]
292 export class VideoModel extends Model<VideoModel> {
295 @Default(DataType.UUIDV4)
297 @Column(DataType.UUID)
301 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
307 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
313 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
319 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
324 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
329 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
335 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
336 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
341 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
342 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
346 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
376 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
377 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
382 commentsEnabled: boolean
391 @Default(Sequelize.NOW)
395 @ForeignKey(() => VideoChannelModel)
399 @BelongsTo(() => VideoChannelModel, {
405 VideoChannel: VideoChannelModel
407 @BelongsToMany(() => TagModel, {
408 foreignKey: 'videoId',
409 through: () => VideoTagModel,
414 @HasMany(() => VideoAbuseModel, {
421 VideoAbuses: VideoAbuseModel[]
423 @HasMany(() => VideoFileModel, {
430 VideoFiles: VideoFileModel[]
432 @HasMany(() => VideoShareModel, {
439 VideoShares: VideoShareModel[]
441 @HasMany(() => AccountVideoRateModel, {
448 AccountVideoRates: AccountVideoRateModel[]
450 @HasMany(() => VideoCommentModel, {
458 VideoComments: VideoCommentModel[]
461 static async sendDelete (instance: VideoModel, options) {
462 if (instance.isOwned()) {
463 if (!instance.VideoChannel) {
464 instance.VideoChannel = await instance.$get('VideoChannel', {
468 include: [ ActorModel ]
471 transaction: options.transaction
472 }) as VideoChannelModel
475 logger.debug('Sending delete of video %s.', instance.url)
477 return sendDeleteVideo(instance, options.transaction)
484 static async removeFilesAndSendDelete (instance: VideoModel) {
485 const tasks: Promise<any>[] = []
487 tasks.push(instance.removeThumbnail())
489 if (instance.isOwned()) {
490 if (!Array.isArray(instance.VideoFiles)) {
491 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
494 tasks.push(instance.removePreview())
496 // Remove physical files and torrents
497 instance.VideoFiles.forEach(file => {
498 tasks.push(instance.removeFile(file))
499 tasks.push(instance.removeTorrent(file))
503 return Promise.all(tasks)
505 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
510 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
513 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
514 function getRawQuery (select: string) {
515 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
516 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
517 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
518 'WHERE "Account"."actorId" = ' + actorId
519 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
520 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
521 'WHERE "VideoShare"."actorId" = ' + actorId
523 return `(${queryVideo}) UNION (${queryVideoShare})`
526 const rawQuery = getRawQuery('"Video"."id"')
527 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
533 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
536 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
539 { privacy: VideoPrivacy.PUBLIC },
540 { privacy: VideoPrivacy.UNLISTED }
545 attributes: [ 'id', 'url' ],
546 model: VideoShareModel.unscoped(),
549 [Sequelize.Op.and]: [
552 [Sequelize.Op.not]: null
562 attributes: [ 'id', 'url' ],
563 model: ActorModel.unscoped()
568 model: VideoChannelModel.unscoped(),
572 attributes: [ 'name' ],
573 model: AccountModel.unscoped(),
577 attributes: [ 'id', 'url' ],
578 model: ActorModel.unscoped(),
584 attributes: [ 'id', 'url' ],
585 model: ActorModel.unscoped(),
591 attributes: [ 'type' ],
592 model: AccountVideoRateModel,
596 attributes: [ 'id' ],
597 model: AccountModel.unscoped(),
600 attributes: [ 'url' ],
601 model: ActorModel.unscoped(),
604 attributes: [ 'host' ],
615 attributes: [ 'url' ],
616 model: VideoCommentModel,
624 return Bluebird.all([
625 // FIXME: typing issue
626 VideoModel.findAll(query as any),
627 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
628 ]).then(([ rows, totals ]) => {
629 // totals: totalVideos + totalVideoShares
631 let totalVideoShares = 0
632 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
633 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
635 const total = totalVideos + totalVideoShares
643 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
644 const query: IFindOptions<VideoModel> = {
647 order: getSort(sort),
650 model: VideoChannelModel,
665 if (withFiles === true) {
667 model: VideoFileModel.unscoped(),
672 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
680 static async listForApi (start: number, count: number, sort: string, filter?: VideoFilter, withFiles = false) {
687 const serverActor = await getServerActor()
689 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id, filter, withFiles ] })
690 .findAndCountAll(query)
691 .then(({ rows, count }) => {
699 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
700 const query: IFindOptions<VideoModel> = {
703 order: getSort(sort),
708 [ Sequelize.Op.iLike ]: '%' + value + '%'
712 preferredUsername: Sequelize.where(Sequelize.col('preferredUsername'), {
713 [ Sequelize.Op.iLike ]: '%' + value + '%'
717 host: Sequelize.where(Sequelize.col('host'), {
718 [ Sequelize.Op.iLike ]: '%' + value + '%'
725 const serverActor = await getServerActor()
727 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
728 .findAndCountAll(query)
729 .then(({ rows, count }) => {
737 static load (id: number) {
738 return VideoModel.findById(id)
741 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
742 const query: IFindOptions<VideoModel> = {
748 if (t !== undefined) query.transaction = t
750 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
753 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
754 const query: IFindOptions<VideoModel> = {
763 if (t !== undefined) query.transaction = t
765 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
768 static loadAndPopulateAccountAndServerAndTags (id: number) {
770 order: [ [ 'Tags', 'name', 'ASC' ] ]
774 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
775 .findById(id, options)
778 static loadByUUID (uuid: string) {
786 .scope([ ScopeNames.WITH_FILES ])
790 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
792 order: [ [ 'Tags', 'name', 'ASC' ] ],
799 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
803 static loadAndPopulateAll (id: number) {
805 order: [ [ 'Tags', 'name', 'ASC' ] ],
813 ScopeNames.WITH_RATES,
814 ScopeNames.WITH_SHARES,
815 ScopeNames.WITH_TAGS,
816 ScopeNames.WITH_FILES,
817 ScopeNames.WITH_ACCOUNT_DETAILS,
818 ScopeNames.WITH_COMMENTS
823 static async getStats () {
824 const totalLocalVideos = await VideoModel.count({
829 const totalVideos = await VideoModel.count()
831 let totalLocalVideoViews = await VideoModel.sum('views', {
836 // Sequelize could return null...
837 if (!totalLocalVideoViews) totalLocalVideoViews = 0
841 totalLocalVideoViews,
846 private static buildActorWhereWithFilter (filter?: VideoFilter) {
847 if (filter && filter === 'local') {
856 private static getCategoryLabel (id: number) {
857 let categoryLabel = VIDEO_CATEGORIES[id]
858 if (!categoryLabel) categoryLabel = 'Misc'
863 private static getLicenceLabel (id: number) {
864 let licenceLabel = VIDEO_LICENCES[id]
865 if (!licenceLabel) licenceLabel = 'Unknown'
870 private static getLanguageLabel (id: number) {
871 let languageLabel = VIDEO_LANGUAGES[id]
872 if (!languageLabel) languageLabel = 'Unknown'
878 if (Array.isArray(this.VideoFiles) === false) return undefined
880 // The original file is the file that have the higher resolution
881 return maxBy(this.VideoFiles, file => file.resolution)
884 getVideoFilename (videoFile: VideoFileModel) {
885 return this.uuid + '-' + videoFile.resolution + videoFile.extname
888 getThumbnailName () {
889 // We always have a copy of the thumbnail
890 const extension = '.jpg'
891 return this.uuid + extension
895 const extension = '.jpg'
896 return this.uuid + extension
899 getTorrentFileName (videoFile: VideoFileModel) {
900 const extension = '.torrent'
901 return this.uuid + '-' + videoFile.resolution + extension
905 return this.remote === false
908 createPreview (videoFile: VideoFileModel) {
909 return generateImageFromVideoFile(
910 this.getVideoFilePath(videoFile),
911 CONFIG.STORAGE.PREVIEWS_DIR,
912 this.getPreviewName(),
917 createThumbnail (videoFile: VideoFileModel) {
918 return generateImageFromVideoFile(
919 this.getVideoFilePath(videoFile),
920 CONFIG.STORAGE.THUMBNAILS_DIR,
921 this.getThumbnailName(),
926 getVideoFilePath (videoFile: VideoFileModel) {
927 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
930 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
933 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
934 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
937 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
941 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
943 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
944 logger.info('Creating torrent %s.', filePath)
946 await writeFilePromise(filePath, torrent)
948 const parsedTorrent = parseTorrent(torrent)
949 videoFile.infoHash = parsedTorrent.infoHash
953 return '/videos/embed/' + this.uuid
956 getThumbnailPath () {
957 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
961 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
964 toFormattedJSON (): Video {
965 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
973 label: VideoModel.getCategoryLabel(this.category)
977 label: VideoModel.getLicenceLabel(this.licence)
981 label: VideoModel.getLanguageLabel(this.language)
984 description: this.getTruncatedDescription(),
985 isLocal: this.isOwned(),
986 duration: this.duration,
989 dislikes: this.dislikes,
990 thumbnailPath: this.getThumbnailPath(),
991 previewPath: this.getPreviewPath(),
992 embedPath: this.getEmbedPath(),
993 createdAt: this.createdAt,
994 updatedAt: this.updatedAt,
995 publishedAt: this.publishedAt,
997 name: formattedAccount.name,
998 displayName: formattedAccount.displayName,
999 url: formattedAccount.url,
1000 host: formattedAccount.host,
1001 avatar: formattedAccount.avatar
1006 toFormattedDetailsJSON (): VideoDetails {
1007 const formattedJson = this.toFormattedJSON()
1009 // Maybe our server is not up to date and there are new privacy settings since our version
1010 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
1011 if (!privacyLabel) privacyLabel = 'Unknown'
1013 const detailsJson = {
1018 support: this.support,
1019 descriptionPath: this.getDescriptionPath(),
1020 channel: this.VideoChannel.toFormattedJSON(),
1021 account: this.VideoChannel.Account.toFormattedJSON(),
1022 tags: map(this.Tags, 'name'),
1023 commentsEnabled: this.commentsEnabled,
1027 // Format and sort video files
1028 detailsJson.files = this.getFormattedVideoFilesJSON()
1030 return Object.assign(formattedJson, detailsJson)
1033 getFormattedVideoFilesJSON (): VideoFile[] {
1034 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1036 return this.VideoFiles
1038 let resolutionLabel = videoFile.resolution + 'p'
1042 id: videoFile.resolution,
1043 label: resolutionLabel
1045 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1046 size: videoFile.size,
1047 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1048 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1052 if (a.resolution.id < b.resolution.id) return 1
1053 if (a.resolution.id === b.resolution.id) return 0
1058 toActivityPubObject (): VideoTorrentObject {
1059 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1060 if (!this.Tags) this.Tags = []
1062 const tag = this.Tags.map(t => ({
1063 type: 'Hashtag' as 'Hashtag',
1068 if (this.language) {
1070 identifier: this.language + '',
1071 name: VideoModel.getLanguageLabel(this.language)
1076 if (this.category) {
1078 identifier: this.category + '',
1079 name: VideoModel.getCategoryLabel(this.category)
1086 identifier: this.licence + '',
1087 name: VideoModel.getLicenceLabel(this.licence)
1094 if (Array.isArray(this.AccountVideoRates)) {
1095 const res = this.toRatesActivityPubObjects()
1096 likesObject = res.likesObject
1097 dislikesObject = res.dislikesObject
1101 if (Array.isArray(this.VideoShares)) {
1102 sharesObject = this.toAnnouncesActivityPubObject()
1106 if (Array.isArray(this.VideoComments)) {
1107 commentsObject = this.toCommentsActivityPubObject()
1111 for (const file of this.VideoFiles) {
1114 mimeType: 'video/' + file.extname.replace('.', ''),
1115 href: this.getVideoFileUrl(file, baseUrlHttp),
1116 width: file.resolution,
1122 mimeType: 'application/x-bittorrent',
1123 href: this.getTorrentUrl(file, baseUrlHttp),
1124 width: file.resolution
1129 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1130 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1131 width: file.resolution
1135 // Add video url too
1138 mimeType: 'text/html',
1139 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1143 type: 'Video' as 'Video',
1146 duration: this.getActivityStreamDuration(),
1153 sensitive: this.nsfw,
1154 commentsEnabled: this.commentsEnabled,
1155 published: this.publishedAt.toISOString(),
1156 updated: this.updatedAt.toISOString(),
1157 mediaType: 'text/markdown',
1158 content: this.getTruncatedDescription(),
1159 support: this.support,
1162 url: this.getThumbnailUrl(baseUrlHttp),
1163 mediaType: 'image/jpeg',
1164 width: THUMBNAILS_SIZE.width,
1165 height: THUMBNAILS_SIZE.height
1169 dislikes: dislikesObject,
1170 shares: sharesObject,
1171 comments: commentsObject,
1175 id: this.VideoChannel.Account.Actor.url
1179 id: this.VideoChannel.Actor.url
1185 toAnnouncesActivityPubObject () {
1186 const shares: string[] = []
1188 for (const videoShare of this.VideoShares) {
1189 shares.push(videoShare.url)
1192 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1195 toCommentsActivityPubObject () {
1196 const comments: string[] = []
1198 for (const videoComment of this.VideoComments) {
1199 comments.push(videoComment.url)
1202 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1205 toRatesActivityPubObjects () {
1206 const likes: string[] = []
1207 const dislikes: string[] = []
1209 for (const rate of this.AccountVideoRates) {
1210 if (rate.type === 'like') {
1211 likes.push(rate.Account.Actor.url)
1212 } else if (rate.type === 'dislike') {
1213 dislikes.push(rate.Account.Actor.url)
1217 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1218 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1220 return { likesObject, dislikesObject }
1223 getTruncatedDescription () {
1224 if (!this.description) return null
1226 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1227 return peertubeTruncate(this.description, maxLength)
1230 optimizeOriginalVideofile = async function () {
1231 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1232 const newExtname = '.mp4'
1233 const inputVideoFile = this.getOriginalFile()
1234 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1235 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1237 const transcodeOptions = {
1238 inputPath: videoInputPath,
1239 outputPath: videoOutputPath
1242 // Could be very long!
1243 await transcode(transcodeOptions)
1246 await unlinkPromise(videoInputPath)
1248 // Important to do this before getVideoFilename() to take in account the new file extension
1249 inputVideoFile.set('extname', newExtname)
1251 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1252 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1254 inputVideoFile.set('size', stats.size)
1256 await this.createTorrentAndSetInfoHash(inputVideoFile)
1257 await inputVideoFile.save()
1260 // Auto destruction...
1261 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1267 transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
1268 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1269 const extname = '.mp4'
1271 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1272 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1274 const newVideoFile = new VideoFileModel({
1280 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1282 const transcodeOptions = {
1283 inputPath: videoInputPath,
1284 outputPath: videoOutputPath,
1289 await transcode(transcodeOptions)
1291 const stats = await statPromise(videoOutputPath)
1293 newVideoFile.set('size', stats.size)
1295 await this.createTorrentAndSetInfoHash(newVideoFile)
1297 await newVideoFile.save()
1299 this.VideoFiles.push(newVideoFile)
1302 getOriginalFileResolution () {
1303 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1305 return getVideoFileResolution(originalFilePath)
1308 getDescriptionPath () {
1309 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1312 removeThumbnail () {
1313 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1314 return unlinkPromise(thumbnailPath)
1318 // Same name than video thumbnail
1319 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1322 removeFile (videoFile: VideoFileModel) {
1323 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1324 return unlinkPromise(filePath)
1327 removeTorrent (videoFile: VideoFileModel) {
1328 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1329 return unlinkPromise(torrentPath)
1332 getActivityStreamDuration () {
1333 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1334 return 'PT' + this.duration + 'S'
1337 private getBaseUrls () {
1341 if (this.isOwned()) {
1342 baseUrlHttp = CONFIG.WEBSERVER.URL
1343 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1345 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1346 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1349 return { baseUrlHttp, baseUrlWs }
1352 private getThumbnailUrl (baseUrlHttp: string) {
1353 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1356 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1357 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1360 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1361 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1364 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1365 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1366 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1367 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1369 const magnetHash = {
1373 infoHash: videoFile.infoHash,
1377 return magnetUtil.encode(magnetHash)