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'
27 } from 'sequelize-typescript'
28 import { VideoPrivacy, VideoResolution } from '../../../shared'
29 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
30 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
31 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
32 import { activityPubCollection } from '../../helpers/activitypub'
40 } from '../../helpers/core-utils'
41 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
42 import { isBooleanValid } from '../../helpers/custom-validators/misc'
45 isVideoDescriptionValid,
52 } from '../../helpers/custom-validators/videos'
53 import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
54 import { logger } from '../../helpers/logger'
55 import { getServerActor } from '../../helpers/utils'
68 } from '../../initializers'
70 getVideoCommentsActivityPubUrl,
71 getVideoDislikesActivityPubUrl,
72 getVideoLikesActivityPubUrl,
73 getVideoSharesActivityPubUrl
74 } from '../../lib/activitypub'
75 import { sendDeleteVideo } from '../../lib/activitypub/send'
76 import { AccountModel } from '../account/account'
77 import { AccountVideoRateModel } from '../account/account-video-rate'
78 import { ActorModel } from '../activitypub/actor'
79 import { AvatarModel } from '../avatar/avatar'
80 import { ServerModel } from '../server/server'
81 import { getSort, throwIfNotValid } from '../utils'
82 import { TagModel } from './tag'
83 import { VideoAbuseModel } from './video-abuse'
84 import { VideoChannelModel } from './video-channel'
85 import { VideoCommentModel } from './video-comment'
86 import { VideoFileModel } from './video-file'
87 import { VideoShareModel } from './video-share'
88 import { VideoTagModel } from './video-tag'
91 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
92 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
93 WITH_TAGS = 'WITH_TAGS',
94 WITH_FILES = 'WITH_FILES',
95 WITH_SHARES = 'WITH_SHARES',
96 WITH_RATES = 'WITH_RATES',
97 WITH_COMMENTS = 'WITH_COMMENTS'
101 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
104 filter?: VideoFilter,
107 videoChannelId?: number
109 const accountInclude = {
110 attributes: [ 'id', 'name' ],
111 model: AccountModel.unscoped(),
116 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
117 model: ActorModel.unscoped(),
119 where: VideoModel.buildActorWhereWithFilter(options.filter),
122 attributes: [ 'host' ],
123 model: ServerModel.unscoped(),
127 model: AvatarModel.unscoped(),
135 const videoChannelInclude = {
136 attributes: [ 'name', 'description', 'id' ],
137 model: VideoChannelModel.unscoped(),
142 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
143 model: ActorModel.unscoped(),
147 attributes: [ 'host' ],
148 model: ServerModel.unscoped(),
152 model: AvatarModel.unscoped(),
161 // Force actorId to be a number to avoid SQL injections
162 const actorIdNumber = parseInt(options.actorId.toString(), 10)
163 const query: IFindOptions<VideoModel> = {
166 [Sequelize.Op.notIn]: Sequelize.literal(
167 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
169 [ Sequelize.Op.in ]: Sequelize.literal(
171 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
172 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
173 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
175 'SELECT "video"."id" AS "id" FROM "video" ' +
176 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
177 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
178 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
179 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
180 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
184 privacy: VideoPrivacy.PUBLIC
186 include: [ videoChannelInclude ]
189 if (options.withFiles === true) {
191 model: VideoFileModel.unscoped(),
197 if (options.hideNSFW === true) {
198 query.where['nsfw'] = false
201 if (options.accountId) {
202 accountInclude.where = {
203 id: options.accountId
207 if (options.videoChannelId) {
208 videoChannelInclude.where = {
209 id: options.videoChannelId
215 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
218 model: () => VideoChannelModel.unscoped(),
223 exclude: [ 'privateKey', 'publicKey' ]
225 model: () => ActorModel.unscoped(),
229 attributes: [ 'host' ],
230 model: () => ServerModel.unscoped(),
236 model: () => AccountModel.unscoped(),
240 model: () => ActorModel.unscoped(),
242 exclude: [ 'privateKey', 'publicKey' ]
247 attributes: [ 'host' ],
248 model: () => ServerModel.unscoped(),
252 model: () => AvatarModel.unscoped(),
263 [ScopeNames.WITH_TAGS]: {
264 include: [ () => TagModel ]
266 [ScopeNames.WITH_FILES]: {
269 model: () => VideoFileModel.unscoped(),
274 [ScopeNames.WITH_SHARES]: {
277 ['separate' as any]: true,
278 model: () => VideoShareModel.unscoped()
282 [ScopeNames.WITH_RATES]: {
285 ['separate' as any]: true,
286 model: () => AccountVideoRateModel,
289 model: () => AccountModel.unscoped(),
293 attributes: [ 'url' ],
294 model: () => ActorModel.unscoped()
302 [ScopeNames.WITH_COMMENTS]: {
305 ['separate' as any]: true,
306 model: () => VideoCommentModel.unscoped()
318 fields: [ 'createdAt' ]
321 fields: [ 'duration' ]
333 fields: [ 'channelId' ]
336 fields: [ 'id', 'privacy' ]
344 export class VideoModel extends Model<VideoModel> {
347 @Default(DataType.UUIDV4)
349 @Column(DataType.UUID)
353 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
359 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
365 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
371 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
372 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
376 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
381 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
387 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
388 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
393 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
394 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
398 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
428 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
429 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
434 commentsEnabled: boolean
443 @Default(Sequelize.NOW)
447 @ForeignKey(() => VideoChannelModel)
451 @BelongsTo(() => VideoChannelModel, {
457 VideoChannel: VideoChannelModel
459 @BelongsToMany(() => TagModel, {
460 foreignKey: 'videoId',
461 through: () => VideoTagModel,
466 @HasMany(() => VideoAbuseModel, {
473 VideoAbuses: VideoAbuseModel[]
475 @HasMany(() => VideoFileModel, {
482 VideoFiles: VideoFileModel[]
484 @HasMany(() => VideoShareModel, {
491 VideoShares: VideoShareModel[]
493 @HasMany(() => AccountVideoRateModel, {
500 AccountVideoRates: AccountVideoRateModel[]
502 @HasMany(() => VideoCommentModel, {
510 VideoComments: VideoCommentModel[]
513 static async sendDelete (instance: VideoModel, options) {
514 if (instance.isOwned()) {
515 if (!instance.VideoChannel) {
516 instance.VideoChannel = await instance.$get('VideoChannel', {
520 include: [ ActorModel ]
523 transaction: options.transaction
524 }) as VideoChannelModel
527 logger.debug('Sending delete of video %s.', instance.url)
529 return sendDeleteVideo(instance, options.transaction)
536 static async removeFilesAndSendDelete (instance: VideoModel) {
537 const tasks: Promise<any>[] = []
539 logger.debug('Removing files of video %s.', instance.url)
541 tasks.push(instance.removeThumbnail())
543 if (instance.isOwned()) {
544 if (!Array.isArray(instance.VideoFiles)) {
545 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
548 tasks.push(instance.removePreview())
550 // Remove physical files and torrents
551 instance.VideoFiles.forEach(file => {
552 tasks.push(instance.removeFile(file))
553 tasks.push(instance.removeTorrent(file))
557 // Do not wait video deletion because we could be in a transaction
560 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
567 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
570 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
571 function getRawQuery (select: string) {
572 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
573 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
574 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
575 'WHERE "Account"."actorId" = ' + actorId
576 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
577 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
578 'WHERE "VideoShare"."actorId" = ' + actorId
580 return `(${queryVideo}) UNION (${queryVideoShare})`
583 const rawQuery = getRawQuery('"Video"."id"')
584 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
590 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
593 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
596 { privacy: VideoPrivacy.PUBLIC },
597 { privacy: VideoPrivacy.UNLISTED }
602 attributes: [ 'id', 'url' ],
603 model: VideoShareModel.unscoped(),
606 [Sequelize.Op.and]: [
609 [Sequelize.Op.not]: null
619 attributes: [ 'id', 'url' ],
620 model: ActorModel.unscoped()
625 model: VideoChannelModel.unscoped(),
629 attributes: [ 'name' ],
630 model: AccountModel.unscoped(),
634 attributes: [ 'id', 'url' ],
635 model: ActorModel.unscoped(),
641 attributes: [ 'id', 'url' ],
642 model: ActorModel.unscoped(),
648 attributes: [ 'type' ],
649 model: AccountVideoRateModel,
653 attributes: [ 'id' ],
654 model: AccountModel.unscoped(),
657 attributes: [ 'url' ],
658 model: ActorModel.unscoped(),
661 attributes: [ 'host' ],
672 attributes: [ 'url' ],
673 model: VideoCommentModel,
681 return Bluebird.all([
682 // FIXME: typing issue
683 VideoModel.findAll(query as any),
684 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
685 ]).then(([ rows, totals ]) => {
686 // totals: totalVideos + totalVideoShares
688 let totalVideoShares = 0
689 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
690 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
692 const total = totalVideos + totalVideoShares
700 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
701 const query: IFindOptions<VideoModel> = {
704 order: getSort(sort),
707 model: VideoChannelModel,
722 if (withFiles === true) {
724 model: VideoFileModel.unscoped(),
729 if (hideNSFW === true) {
735 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
743 static async listForApi (options: {
749 filter?: VideoFilter,
751 videoChannelId?: number
754 offset: options.start,
755 limit: options.count,
756 order: getSort(options.sort)
759 const serverActor = await getServerActor()
762 ScopeNames.AVAILABLE_FOR_LIST, {
763 actorId: serverActor.id,
764 hideNSFW: options.hideNSFW,
765 filter: options.filter,
766 withFiles: options.withFiles,
767 accountId: options.accountId,
768 videoChannelId: options.videoChannelId
773 return VideoModel.scope(scopes)
774 .findAndCountAll(query)
775 .then(({ rows, count }) => {
783 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
784 const query: IFindOptions<VideoModel> = {
787 order: getSort(sort),
792 [ Sequelize.Op.iLike ]: '%' + value + '%'
796 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
797 [ Sequelize.Op.iLike ]: '%' + value + '%'
801 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
802 [ Sequelize.Op.iLike ]: '%' + value + '%'
806 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
807 [ Sequelize.Op.iLike ]: '%' + value + '%'
814 const serverActor = await getServerActor()
817 ScopeNames.AVAILABLE_FOR_LIST, {
818 actorId: serverActor.id,
824 return VideoModel.scope(scopes)
825 .findAndCountAll(query)
826 .then(({ rows, count }) => {
834 static load (id: number) {
835 return VideoModel.findById(id)
838 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
839 const query: IFindOptions<VideoModel> = {
845 if (t !== undefined) query.transaction = t
847 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
850 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
851 const query: IFindOptions<VideoModel> = {
860 if (t !== undefined) query.transaction = t
862 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
865 static loadAndPopulateAccountAndServerAndTags (id: number) {
867 order: [ [ 'Tags', 'name', 'ASC' ] ]
871 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
872 .findById(id, options)
875 static loadByUUID (uuid: string) {
883 .scope([ ScopeNames.WITH_FILES ])
887 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
889 order: [ [ 'Tags', 'name', 'ASC' ] ],
896 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
900 static loadAndPopulateAll (id: number) {
902 order: [ [ 'Tags', 'name', 'ASC' ] ],
910 ScopeNames.WITH_RATES,
911 ScopeNames.WITH_SHARES,
912 ScopeNames.WITH_TAGS,
913 ScopeNames.WITH_FILES,
914 ScopeNames.WITH_ACCOUNT_DETAILS,
915 ScopeNames.WITH_COMMENTS
920 static async getStats () {
921 const totalLocalVideos = await VideoModel.count({
926 const totalVideos = await VideoModel.count()
928 let totalLocalVideoViews = await VideoModel.sum('views', {
933 // Sequelize could return null...
934 if (!totalLocalVideoViews) totalLocalVideoViews = 0
938 totalLocalVideoViews,
943 private static buildActorWhereWithFilter (filter?: VideoFilter) {
944 if (filter && filter === 'local') {
953 private static getCategoryLabel (id: number) {
954 let categoryLabel = VIDEO_CATEGORIES[id]
955 if (!categoryLabel) categoryLabel = 'Misc'
960 private static getLicenceLabel (id: number) {
961 let licenceLabel = VIDEO_LICENCES[id]
962 if (!licenceLabel) licenceLabel = 'Unknown'
967 private static getLanguageLabel (id: string) {
968 let languageLabel = VIDEO_LANGUAGES[id]
969 if (!languageLabel) languageLabel = 'Unknown'
974 private static getPrivacyLabel (id: number) {
975 let privacyLabel = VIDEO_PRIVACIES[id]
976 if (!privacyLabel) privacyLabel = 'Unknown'
982 if (Array.isArray(this.VideoFiles) === false) return undefined
984 // The original file is the file that have the higher resolution
985 return maxBy(this.VideoFiles, file => file.resolution)
988 getVideoFilename (videoFile: VideoFileModel) {
989 return this.uuid + '-' + videoFile.resolution + videoFile.extname
992 getThumbnailName () {
993 // We always have a copy of the thumbnail
994 const extension = '.jpg'
995 return this.uuid + extension
999 const extension = '.jpg'
1000 return this.uuid + extension
1003 getTorrentFileName (videoFile: VideoFileModel) {
1004 const extension = '.torrent'
1005 return this.uuid + '-' + videoFile.resolution + extension
1009 return this.remote === false
1012 createPreview (videoFile: VideoFileModel) {
1013 return generateImageFromVideoFile(
1014 this.getVideoFilePath(videoFile),
1015 CONFIG.STORAGE.PREVIEWS_DIR,
1016 this.getPreviewName(),
1021 createThumbnail (videoFile: VideoFileModel) {
1022 return generateImageFromVideoFile(
1023 this.getVideoFilePath(videoFile),
1024 CONFIG.STORAGE.THUMBNAILS_DIR,
1025 this.getThumbnailName(),
1030 getVideoFilePath (videoFile: VideoFileModel) {
1031 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1034 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1036 // Keep the extname, it's used by the client to stream the file inside a web browser
1037 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1038 createdBy: 'PeerTube',
1040 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1041 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1044 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1048 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1050 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1051 logger.info('Creating torrent %s.', filePath)
1053 await writeFilePromise(filePath, torrent)
1055 const parsedTorrent = parseTorrent(torrent)
1056 videoFile.infoHash = parsedTorrent.infoHash
1060 return '/videos/embed/' + this.uuid
1063 getThumbnailPath () {
1064 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1068 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1071 toFormattedJSON (): Video {
1072 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1073 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1081 label: VideoModel.getCategoryLabel(this.category)
1085 label: VideoModel.getLicenceLabel(this.licence)
1089 label: VideoModel.getLanguageLabel(this.language)
1093 label: VideoModel.getPrivacyLabel(this.privacy)
1096 description: this.getTruncatedDescription(),
1097 isLocal: this.isOwned(),
1098 duration: this.duration,
1101 dislikes: this.dislikes,
1102 thumbnailPath: this.getThumbnailPath(),
1103 previewPath: this.getPreviewPath(),
1104 embedPath: this.getEmbedPath(),
1105 createdAt: this.createdAt,
1106 updatedAt: this.updatedAt,
1107 publishedAt: this.publishedAt,
1109 id: formattedAccount.id,
1110 uuid: formattedAccount.uuid,
1111 name: formattedAccount.name,
1112 displayName: formattedAccount.displayName,
1113 url: formattedAccount.url,
1114 host: formattedAccount.host,
1115 avatar: formattedAccount.avatar
1118 id: formattedVideoChannel.id,
1119 uuid: formattedVideoChannel.uuid,
1120 name: formattedVideoChannel.name,
1121 displayName: formattedVideoChannel.displayName,
1122 url: formattedVideoChannel.url,
1123 host: formattedVideoChannel.host,
1124 avatar: formattedVideoChannel.avatar
1129 toFormattedDetailsJSON (): VideoDetails {
1130 const formattedJson = this.toFormattedJSON()
1132 const detailsJson = {
1133 support: this.support,
1134 descriptionPath: this.getDescriptionPath(),
1135 channel: this.VideoChannel.toFormattedJSON(),
1136 account: this.VideoChannel.Account.toFormattedJSON(),
1137 tags: map(this.Tags, 'name'),
1138 commentsEnabled: this.commentsEnabled,
1142 // Format and sort video files
1143 detailsJson.files = this.getFormattedVideoFilesJSON()
1145 return Object.assign(formattedJson, detailsJson)
1148 getFormattedVideoFilesJSON (): VideoFile[] {
1149 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1151 return this.VideoFiles
1153 let resolutionLabel = videoFile.resolution + 'p'
1157 id: videoFile.resolution,
1158 label: resolutionLabel
1160 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1161 size: videoFile.size,
1162 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1163 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1167 if (a.resolution.id < b.resolution.id) return 1
1168 if (a.resolution.id === b.resolution.id) return 0
1173 toActivityPubObject (): VideoTorrentObject {
1174 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1175 if (!this.Tags) this.Tags = []
1177 const tag = this.Tags.map(t => ({
1178 type: 'Hashtag' as 'Hashtag',
1183 if (this.language) {
1185 identifier: this.language,
1186 name: VideoModel.getLanguageLabel(this.language)
1191 if (this.category) {
1193 identifier: this.category + '',
1194 name: VideoModel.getCategoryLabel(this.category)
1201 identifier: this.licence + '',
1202 name: VideoModel.getLicenceLabel(this.licence)
1209 if (Array.isArray(this.AccountVideoRates)) {
1210 const res = this.toRatesActivityPubObjects()
1211 likesObject = res.likesObject
1212 dislikesObject = res.dislikesObject
1216 if (Array.isArray(this.VideoShares)) {
1217 sharesObject = this.toAnnouncesActivityPubObject()
1221 if (Array.isArray(this.VideoComments)) {
1222 commentsObject = this.toCommentsActivityPubObject()
1226 for (const file of this.VideoFiles) {
1229 mimeType: 'video/' + file.extname.replace('.', ''),
1230 href: this.getVideoFileUrl(file, baseUrlHttp),
1231 width: file.resolution,
1237 mimeType: 'application/x-bittorrent',
1238 href: this.getTorrentUrl(file, baseUrlHttp),
1239 width: file.resolution
1244 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1245 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1246 width: file.resolution
1250 // Add video url too
1253 mimeType: 'text/html',
1254 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1258 type: 'Video' as 'Video',
1261 duration: this.getActivityStreamDuration(),
1268 sensitive: this.nsfw,
1269 commentsEnabled: this.commentsEnabled,
1270 published: this.publishedAt.toISOString(),
1271 updated: this.updatedAt.toISOString(),
1272 mediaType: 'text/markdown',
1273 content: this.getTruncatedDescription(),
1274 support: this.support,
1277 url: this.getThumbnailUrl(baseUrlHttp),
1278 mediaType: 'image/jpeg',
1279 width: THUMBNAILS_SIZE.width,
1280 height: THUMBNAILS_SIZE.height
1284 dislikes: dislikesObject,
1285 shares: sharesObject,
1286 comments: commentsObject,
1290 id: this.VideoChannel.Account.Actor.url
1294 id: this.VideoChannel.Actor.url
1300 toAnnouncesActivityPubObject () {
1301 const shares: string[] = []
1303 for (const videoShare of this.VideoShares) {
1304 shares.push(videoShare.url)
1307 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1310 toCommentsActivityPubObject () {
1311 const comments: string[] = []
1313 for (const videoComment of this.VideoComments) {
1314 comments.push(videoComment.url)
1317 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1320 toRatesActivityPubObjects () {
1321 const likes: string[] = []
1322 const dislikes: string[] = []
1324 for (const rate of this.AccountVideoRates) {
1325 if (rate.type === 'like') {
1326 likes.push(rate.Account.Actor.url)
1327 } else if (rate.type === 'dislike') {
1328 dislikes.push(rate.Account.Actor.url)
1332 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1333 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1335 return { likesObject, dislikesObject }
1338 getTruncatedDescription () {
1339 if (!this.description) return null
1341 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1342 return peertubeTruncate(this.description, maxLength)
1345 async optimizeOriginalVideofile () {
1346 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1347 const newExtname = '.mp4'
1348 const inputVideoFile = this.getOriginalFile()
1349 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1350 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1352 const transcodeOptions = {
1353 inputPath: videoInputPath,
1354 outputPath: videoOutputPath
1357 // Could be very long!
1358 await transcode(transcodeOptions)
1361 await unlinkPromise(videoInputPath)
1363 // Important to do this before getVideoFilename() to take in account the new file extension
1364 inputVideoFile.set('extname', newExtname)
1366 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1367 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1369 inputVideoFile.set('size', stats.size)
1371 await this.createTorrentAndSetInfoHash(inputVideoFile)
1372 await inputVideoFile.save()
1375 // Auto destruction...
1376 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1382 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1383 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1384 const extname = '.mp4'
1386 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1387 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1389 const newVideoFile = new VideoFileModel({
1395 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1397 const transcodeOptions = {
1398 inputPath: videoInputPath,
1399 outputPath: videoOutputPath,
1404 await transcode(transcodeOptions)
1406 const stats = await statPromise(videoOutputPath)
1408 newVideoFile.set('size', stats.size)
1410 await this.createTorrentAndSetInfoHash(newVideoFile)
1412 await newVideoFile.save()
1414 this.VideoFiles.push(newVideoFile)
1417 getOriginalFileResolution () {
1418 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1420 return getVideoFileResolution(originalFilePath)
1423 getDescriptionPath () {
1424 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1427 removeThumbnail () {
1428 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1429 return unlinkPromise(thumbnailPath)
1433 // Same name than video thumbnail
1434 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1437 removeFile (videoFile: VideoFileModel) {
1438 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1439 return unlinkPromise(filePath)
1442 removeTorrent (videoFile: VideoFileModel) {
1443 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1444 return unlinkPromise(torrentPath)
1447 getActivityStreamDuration () {
1448 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1449 return 'PT' + this.duration + 'S'
1452 private getBaseUrls () {
1456 if (this.isOwned()) {
1457 baseUrlHttp = CONFIG.WEBSERVER.URL
1458 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1460 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1461 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1464 return { baseUrlHttp, baseUrlWs }
1467 private getThumbnailUrl (baseUrlHttp: string) {
1468 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1471 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1472 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1475 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1476 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1479 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1480 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1481 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1482 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1484 const magnetHash = {
1488 infoHash: videoFile.infoHash,
1492 return magnetUtil.encode(magnetHash)