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]: (options: {
101 filter?: VideoFilter,
104 videoChannelId?: number
106 const accountInclude = {
107 attributes: [ 'id', 'name' ],
108 model: AccountModel.unscoped(),
113 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
114 model: ActorModel.unscoped(),
116 where: VideoModel.buildActorWhereWithFilter(options.filter),
119 attributes: [ 'host' ],
120 model: ServerModel.unscoped(),
124 model: AvatarModel.unscoped(),
132 const videoChannelInclude = {
133 attributes: [ 'name', 'description', 'id' ],
134 model: VideoChannelModel.unscoped(),
139 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
140 model: ActorModel.unscoped(),
144 attributes: [ 'host' ],
145 model: ServerModel.unscoped(),
149 model: AvatarModel.unscoped(),
158 // Force actorId to be a number to avoid SQL injections
159 const actorIdNumber = parseInt(options.actorId.toString(), 10)
160 const query: IFindOptions<VideoModel> = {
163 [Sequelize.Op.notIn]: Sequelize.literal(
164 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
166 [ Sequelize.Op.in ]: Sequelize.literal(
168 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
169 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
170 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
172 'SELECT "video"."id" AS "id" FROM "video" ' +
173 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
174 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
175 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
176 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
177 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
181 privacy: VideoPrivacy.PUBLIC
183 include: [ videoChannelInclude ]
186 if (options.withFiles === true) {
188 model: VideoFileModel.unscoped(),
194 if (options.hideNSFW === true) {
195 query.where['nsfw'] = false
198 if (options.accountId) {
199 accountInclude.where = {
200 id: options.accountId
204 if (options.videoChannelId) {
205 videoChannelInclude.where = {
206 id: options.videoChannelId
212 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
215 model: () => VideoChannelModel.unscoped(),
220 exclude: [ 'privateKey', 'publicKey' ]
222 model: () => ActorModel.unscoped(),
226 attributes: [ 'host' ],
227 model: () => ServerModel.unscoped(),
233 model: () => AccountModel.unscoped(),
237 model: () => ActorModel.unscoped(),
239 exclude: [ 'privateKey', 'publicKey' ]
244 attributes: [ 'host' ],
245 model: () => ServerModel.unscoped(),
249 model: () => AvatarModel.unscoped(),
260 [ScopeNames.WITH_TAGS]: {
261 include: [ () => TagModel ]
263 [ScopeNames.WITH_FILES]: {
266 model: () => VideoFileModel.unscoped(),
271 [ScopeNames.WITH_SHARES]: {
274 ['separate' as any]: true,
275 model: () => VideoShareModel.unscoped()
279 [ScopeNames.WITH_RATES]: {
282 ['separate' as any]: true,
283 model: () => AccountVideoRateModel,
286 model: () => AccountModel.unscoped(),
290 attributes: [ 'url' ],
291 model: () => ActorModel.unscoped()
299 [ScopeNames.WITH_COMMENTS]: {
302 ['separate' as any]: true,
303 model: () => VideoCommentModel.unscoped()
315 fields: [ 'createdAt' ]
318 fields: [ 'duration' ]
330 fields: [ 'channelId' ]
333 fields: [ 'id', 'privacy' ]
341 export class VideoModel extends Model<VideoModel> {
344 @Default(DataType.UUIDV4)
346 @Column(DataType.UUID)
350 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
356 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
362 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
368 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
369 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
373 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
378 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
384 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
385 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
390 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
391 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
395 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
425 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
426 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
431 commentsEnabled: boolean
440 @Default(Sequelize.NOW)
444 @ForeignKey(() => VideoChannelModel)
448 @BelongsTo(() => VideoChannelModel, {
454 VideoChannel: VideoChannelModel
456 @BelongsToMany(() => TagModel, {
457 foreignKey: 'videoId',
458 through: () => VideoTagModel,
463 @HasMany(() => VideoAbuseModel, {
470 VideoAbuses: VideoAbuseModel[]
472 @HasMany(() => VideoFileModel, {
479 VideoFiles: VideoFileModel[]
481 @HasMany(() => VideoShareModel, {
488 VideoShares: VideoShareModel[]
490 @HasMany(() => AccountVideoRateModel, {
497 AccountVideoRates: AccountVideoRateModel[]
499 @HasMany(() => VideoCommentModel, {
507 VideoComments: VideoCommentModel[]
510 static async sendDelete (instance: VideoModel, options) {
511 if (instance.isOwned()) {
512 if (!instance.VideoChannel) {
513 instance.VideoChannel = await instance.$get('VideoChannel', {
517 include: [ ActorModel ]
520 transaction: options.transaction
521 }) as VideoChannelModel
524 logger.debug('Sending delete of video %s.', instance.url)
526 return sendDeleteVideo(instance, options.transaction)
533 static async removeFilesAndSendDelete (instance: VideoModel) {
534 const tasks: Promise<any>[] = []
536 logger.debug('Removing files of video %s.', instance.url)
538 tasks.push(instance.removeThumbnail())
540 if (instance.isOwned()) {
541 if (!Array.isArray(instance.VideoFiles)) {
542 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
545 tasks.push(instance.removePreview())
547 // Remove physical files and torrents
548 instance.VideoFiles.forEach(file => {
549 tasks.push(instance.removeFile(file))
550 tasks.push(instance.removeTorrent(file))
554 // Do not wait video deletion because we could be in a transaction
557 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
564 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
567 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
568 function getRawQuery (select: string) {
569 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
570 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
571 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
572 'WHERE "Account"."actorId" = ' + actorId
573 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
574 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
575 'WHERE "VideoShare"."actorId" = ' + actorId
577 return `(${queryVideo}) UNION (${queryVideoShare})`
580 const rawQuery = getRawQuery('"Video"."id"')
581 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
587 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
590 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
593 { privacy: VideoPrivacy.PUBLIC },
594 { privacy: VideoPrivacy.UNLISTED }
599 attributes: [ 'id', 'url' ],
600 model: VideoShareModel.unscoped(),
603 [Sequelize.Op.and]: [
606 [Sequelize.Op.not]: null
616 attributes: [ 'id', 'url' ],
617 model: ActorModel.unscoped()
622 model: VideoChannelModel.unscoped(),
626 attributes: [ 'name' ],
627 model: AccountModel.unscoped(),
631 attributes: [ 'id', 'url' ],
632 model: ActorModel.unscoped(),
638 attributes: [ 'id', 'url' ],
639 model: ActorModel.unscoped(),
645 attributes: [ 'type' ],
646 model: AccountVideoRateModel,
650 attributes: [ 'id' ],
651 model: AccountModel.unscoped(),
654 attributes: [ 'url' ],
655 model: ActorModel.unscoped(),
658 attributes: [ 'host' ],
669 attributes: [ 'url' ],
670 model: VideoCommentModel,
678 return Bluebird.all([
679 // FIXME: typing issue
680 VideoModel.findAll(query as any),
681 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
682 ]).then(([ rows, totals ]) => {
683 // totals: totalVideos + totalVideoShares
685 let totalVideoShares = 0
686 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
687 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
689 const total = totalVideos + totalVideoShares
697 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
698 const query: IFindOptions<VideoModel> = {
701 order: getSort(sort),
704 model: VideoChannelModel,
719 if (withFiles === true) {
721 model: VideoFileModel.unscoped(),
726 if (hideNSFW === true) {
732 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
740 static async listForApi (options: {
746 filter?: VideoFilter,
748 videoChannelId?: number
751 offset: options.start,
752 limit: options.count,
753 order: getSort(options.sort)
756 const serverActor = await getServerActor()
759 ScopeNames.AVAILABLE_FOR_LIST, {
760 actorId: serverActor.id,
761 hideNSFW: options.hideNSFW,
762 filter: options.filter,
763 withFiles: options.withFiles,
764 accountId: options.accountId,
765 videoChannelId: options.videoChannelId
770 return VideoModel.scope(scopes)
771 .findAndCountAll(query)
772 .then(({ rows, count }) => {
780 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
781 const query: IFindOptions<VideoModel> = {
784 order: getSort(sort),
789 [ Sequelize.Op.iLike ]: '%' + value + '%'
793 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
794 [ Sequelize.Op.iLike ]: '%' + value + '%'
798 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
799 [ Sequelize.Op.iLike ]: '%' + value + '%'
803 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
804 [ Sequelize.Op.iLike ]: '%' + value + '%'
811 const serverActor = await getServerActor()
814 ScopeNames.AVAILABLE_FOR_LIST, {
815 actorId: serverActor.id,
821 return VideoModel.scope(scopes)
822 .findAndCountAll(query)
823 .then(({ rows, count }) => {
831 static load (id: number) {
832 return VideoModel.findById(id)
835 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
836 const query: IFindOptions<VideoModel> = {
842 if (t !== undefined) query.transaction = t
844 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
847 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
848 const query: IFindOptions<VideoModel> = {
857 if (t !== undefined) query.transaction = t
859 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
862 static loadAndPopulateAccountAndServerAndTags (id: number) {
864 order: [ [ 'Tags', 'name', 'ASC' ] ]
868 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
869 .findById(id, options)
872 static loadByUUID (uuid: string) {
880 .scope([ ScopeNames.WITH_FILES ])
884 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
886 order: [ [ 'Tags', 'name', 'ASC' ] ],
893 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
897 static loadAndPopulateAll (id: number) {
899 order: [ [ 'Tags', 'name', 'ASC' ] ],
907 ScopeNames.WITH_RATES,
908 ScopeNames.WITH_SHARES,
909 ScopeNames.WITH_TAGS,
910 ScopeNames.WITH_FILES,
911 ScopeNames.WITH_ACCOUNT_DETAILS,
912 ScopeNames.WITH_COMMENTS
917 static async getStats () {
918 const totalLocalVideos = await VideoModel.count({
923 const totalVideos = await VideoModel.count()
925 let totalLocalVideoViews = await VideoModel.sum('views', {
930 // Sequelize could return null...
931 if (!totalLocalVideoViews) totalLocalVideoViews = 0
935 totalLocalVideoViews,
940 private static buildActorWhereWithFilter (filter?: VideoFilter) {
941 if (filter && filter === 'local') {
950 private static getCategoryLabel (id: number) {
951 let categoryLabel = VIDEO_CATEGORIES[id]
952 if (!categoryLabel) categoryLabel = 'Misc'
957 private static getLicenceLabel (id: number) {
958 let licenceLabel = VIDEO_LICENCES[id]
959 if (!licenceLabel) licenceLabel = 'Unknown'
964 private static getLanguageLabel (id: string) {
965 let languageLabel = VIDEO_LANGUAGES[id]
966 if (!languageLabel) languageLabel = 'Unknown'
971 private static getPrivacyLabel (id: number) {
972 let privacyLabel = VIDEO_PRIVACIES[id]
973 if (!privacyLabel) privacyLabel = 'Unknown'
979 if (Array.isArray(this.VideoFiles) === false) return undefined
981 // The original file is the file that have the higher resolution
982 return maxBy(this.VideoFiles, file => file.resolution)
985 getVideoFilename (videoFile: VideoFileModel) {
986 return this.uuid + '-' + videoFile.resolution + videoFile.extname
989 getThumbnailName () {
990 // We always have a copy of the thumbnail
991 const extension = '.jpg'
992 return this.uuid + extension
996 const extension = '.jpg'
997 return this.uuid + extension
1000 getTorrentFileName (videoFile: VideoFileModel) {
1001 const extension = '.torrent'
1002 return this.uuid + '-' + videoFile.resolution + extension
1006 return this.remote === false
1009 createPreview (videoFile: VideoFileModel) {
1010 return generateImageFromVideoFile(
1011 this.getVideoFilePath(videoFile),
1012 CONFIG.STORAGE.PREVIEWS_DIR,
1013 this.getPreviewName(),
1018 createThumbnail (videoFile: VideoFileModel) {
1019 return generateImageFromVideoFile(
1020 this.getVideoFilePath(videoFile),
1021 CONFIG.STORAGE.THUMBNAILS_DIR,
1022 this.getThumbnailName(),
1027 getVideoFilePath (videoFile: VideoFileModel) {
1028 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1031 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1033 // Keep the extname, it's used by the client to stream the file inside a web browser
1034 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1035 createdBy: 'PeerTube',
1037 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1038 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1041 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1045 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1047 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1048 logger.info('Creating torrent %s.', filePath)
1050 await writeFilePromise(filePath, torrent)
1052 const parsedTorrent = parseTorrent(torrent)
1053 videoFile.infoHash = parsedTorrent.infoHash
1057 return '/videos/embed/' + this.uuid
1060 getThumbnailPath () {
1061 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1065 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1068 toFormattedJSON (): Video {
1069 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1070 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1078 label: VideoModel.getCategoryLabel(this.category)
1082 label: VideoModel.getLicenceLabel(this.licence)
1086 label: VideoModel.getLanguageLabel(this.language)
1090 label: VideoModel.getPrivacyLabel(this.privacy)
1093 description: this.getTruncatedDescription(),
1094 isLocal: this.isOwned(),
1095 duration: this.duration,
1098 dislikes: this.dislikes,
1099 thumbnailPath: this.getThumbnailPath(),
1100 previewPath: this.getPreviewPath(),
1101 embedPath: this.getEmbedPath(),
1102 createdAt: this.createdAt,
1103 updatedAt: this.updatedAt,
1104 publishedAt: this.publishedAt,
1106 id: formattedAccount.id,
1107 uuid: formattedAccount.uuid,
1108 name: formattedAccount.name,
1109 displayName: formattedAccount.displayName,
1110 url: formattedAccount.url,
1111 host: formattedAccount.host,
1112 avatar: formattedAccount.avatar
1115 id: formattedVideoChannel.id,
1116 uuid: formattedVideoChannel.uuid,
1117 name: formattedVideoChannel.name,
1118 displayName: formattedVideoChannel.displayName,
1119 url: formattedVideoChannel.url,
1120 host: formattedVideoChannel.host,
1121 avatar: formattedVideoChannel.avatar
1126 toFormattedDetailsJSON (): VideoDetails {
1127 const formattedJson = this.toFormattedJSON()
1129 const detailsJson = {
1130 support: this.support,
1131 descriptionPath: this.getDescriptionPath(),
1132 channel: this.VideoChannel.toFormattedJSON(),
1133 account: this.VideoChannel.Account.toFormattedJSON(),
1134 tags: map(this.Tags, 'name'),
1135 commentsEnabled: this.commentsEnabled,
1139 // Format and sort video files
1140 detailsJson.files = this.getFormattedVideoFilesJSON()
1142 return Object.assign(formattedJson, detailsJson)
1145 getFormattedVideoFilesJSON (): VideoFile[] {
1146 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1148 return this.VideoFiles
1150 let resolutionLabel = videoFile.resolution + 'p'
1154 id: videoFile.resolution,
1155 label: resolutionLabel
1157 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1158 size: videoFile.size,
1159 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1160 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1164 if (a.resolution.id < b.resolution.id) return 1
1165 if (a.resolution.id === b.resolution.id) return 0
1170 toActivityPubObject (): VideoTorrentObject {
1171 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1172 if (!this.Tags) this.Tags = []
1174 const tag = this.Tags.map(t => ({
1175 type: 'Hashtag' as 'Hashtag',
1180 if (this.language) {
1182 identifier: this.language,
1183 name: VideoModel.getLanguageLabel(this.language)
1188 if (this.category) {
1190 identifier: this.category + '',
1191 name: VideoModel.getCategoryLabel(this.category)
1198 identifier: this.licence + '',
1199 name: VideoModel.getLicenceLabel(this.licence)
1206 if (Array.isArray(this.AccountVideoRates)) {
1207 const res = this.toRatesActivityPubObjects()
1208 likesObject = res.likesObject
1209 dislikesObject = res.dislikesObject
1213 if (Array.isArray(this.VideoShares)) {
1214 sharesObject = this.toAnnouncesActivityPubObject()
1218 if (Array.isArray(this.VideoComments)) {
1219 commentsObject = this.toCommentsActivityPubObject()
1223 for (const file of this.VideoFiles) {
1226 mimeType: 'video/' + file.extname.replace('.', ''),
1227 href: this.getVideoFileUrl(file, baseUrlHttp),
1228 width: file.resolution,
1234 mimeType: 'application/x-bittorrent',
1235 href: this.getTorrentUrl(file, baseUrlHttp),
1236 width: file.resolution
1241 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1242 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1243 width: file.resolution
1247 // Add video url too
1250 mimeType: 'text/html',
1251 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1255 type: 'Video' as 'Video',
1258 duration: this.getActivityStreamDuration(),
1265 sensitive: this.nsfw,
1266 commentsEnabled: this.commentsEnabled,
1267 published: this.publishedAt.toISOString(),
1268 updated: this.updatedAt.toISOString(),
1269 mediaType: 'text/markdown',
1270 content: this.getTruncatedDescription(),
1271 support: this.support,
1274 url: this.getThumbnailUrl(baseUrlHttp),
1275 mediaType: 'image/jpeg',
1276 width: THUMBNAILS_SIZE.width,
1277 height: THUMBNAILS_SIZE.height
1281 dislikes: dislikesObject,
1282 shares: sharesObject,
1283 comments: commentsObject,
1287 id: this.VideoChannel.Account.Actor.url
1291 id: this.VideoChannel.Actor.url
1297 toAnnouncesActivityPubObject () {
1298 const shares: string[] = []
1300 for (const videoShare of this.VideoShares) {
1301 shares.push(videoShare.url)
1304 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1307 toCommentsActivityPubObject () {
1308 const comments: string[] = []
1310 for (const videoComment of this.VideoComments) {
1311 comments.push(videoComment.url)
1314 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1317 toRatesActivityPubObjects () {
1318 const likes: string[] = []
1319 const dislikes: string[] = []
1321 for (const rate of this.AccountVideoRates) {
1322 if (rate.type === 'like') {
1323 likes.push(rate.Account.Actor.url)
1324 } else if (rate.type === 'dislike') {
1325 dislikes.push(rate.Account.Actor.url)
1329 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1330 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1332 return { likesObject, dislikesObject }
1335 getTruncatedDescription () {
1336 if (!this.description) return null
1338 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1339 return peertubeTruncate(this.description, maxLength)
1342 async optimizeOriginalVideofile () {
1343 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1344 const newExtname = '.mp4'
1345 const inputVideoFile = this.getOriginalFile()
1346 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1347 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1349 const transcodeOptions = {
1350 inputPath: videoInputPath,
1351 outputPath: videoOutputPath
1354 // Could be very long!
1355 await transcode(transcodeOptions)
1358 await unlinkPromise(videoInputPath)
1360 // Important to do this before getVideoFilename() to take in account the new file extension
1361 inputVideoFile.set('extname', newExtname)
1363 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1364 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1366 inputVideoFile.set('size', stats.size)
1368 await this.createTorrentAndSetInfoHash(inputVideoFile)
1369 await inputVideoFile.save()
1372 // Auto destruction...
1373 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1379 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1380 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1381 const extname = '.mp4'
1383 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1384 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1386 const newVideoFile = new VideoFileModel({
1392 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1394 const transcodeOptions = {
1395 inputPath: videoInputPath,
1396 outputPath: videoOutputPath,
1401 await transcode(transcodeOptions)
1403 const stats = await statPromise(videoOutputPath)
1405 newVideoFile.set('size', stats.size)
1407 await this.createTorrentAndSetInfoHash(newVideoFile)
1409 await newVideoFile.save()
1411 this.VideoFiles.push(newVideoFile)
1414 getOriginalFileResolution () {
1415 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1417 return getVideoFileResolution(originalFilePath)
1420 getDescriptionPath () {
1421 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1424 removeThumbnail () {
1425 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1426 return unlinkPromise(thumbnailPath)
1430 // Same name than video thumbnail
1431 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1434 removeFile (videoFile: VideoFileModel) {
1435 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1436 return unlinkPromise(filePath)
1439 removeTorrent (videoFile: VideoFileModel) {
1440 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1441 return unlinkPromise(torrentPath)
1444 getActivityStreamDuration () {
1445 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1446 return 'PT' + this.duration + 'S'
1449 private getBaseUrls () {
1453 if (this.isOwned()) {
1454 baseUrlHttp = CONFIG.WEBSERVER.URL
1455 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1457 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1458 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1461 return { baseUrlHttp, baseUrlWs }
1464 private getThumbnailUrl (baseUrlHttp: string) {
1465 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1468 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1469 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1472 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1473 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1476 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1477 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1478 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1479 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1481 const magnetHash = {
1485 infoHash: videoFile.infoHash,
1489 return magnetUtil.encode(magnetHash)