1 import * as Bluebird from 'bluebird'
2 import { map, maxBy, truncate } 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 { activityPubCollection } from '../../helpers/activitypub'
33 import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
34 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
35 import { isBooleanValid } from '../../helpers/custom-validators/misc'
38 isVideoDescriptionValid,
44 } from '../../helpers/custom-validators/videos'
45 import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
46 import { logger } from '../../helpers/logger'
47 import { getServerActor } from '../../helpers/utils'
60 } from '../../initializers'
61 import { sendDeleteVideo } from '../../lib/activitypub/send'
62 import { AccountModel } from '../account/account'
63 import { AccountVideoRateModel } from '../account/account-video-rate'
64 import { ActorModel } from '../activitypub/actor'
65 import { ServerModel } from '../server/server'
66 import { getSort, throwIfNotValid } from '../utils'
67 import { TagModel } from './tag'
68 import { VideoAbuseModel } from './video-abuse'
69 import { VideoChannelModel } from './video-channel'
70 import { VideoCommentModel } from './video-comment'
71 import { VideoFileModel } from './video-file'
72 import { VideoShareModel } from './video-share'
73 import { VideoTagModel } from './video-tag'
76 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
77 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
78 WITH_TAGS = 'WITH_TAGS',
79 WITH_FILES = 'WITH_FILES',
80 WITH_SHARES = 'WITH_SHARES',
81 WITH_RATES = 'WITH_RATES',
82 WITH_COMMENTS = 'WITH_COMMENTS'
86 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number) => ({
89 [Sequelize.Op.notIn]: Sequelize.literal(
90 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
92 [ Sequelize.Op.in ]: Sequelize.literal(
94 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
95 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
96 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
98 'SELECT "video"."id" AS "id" FROM "video" ' +
99 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
100 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
101 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
102 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
103 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
107 privacy: VideoPrivacy.PUBLIC
111 attributes: [ 'name', 'description' ],
112 model: VideoChannelModel.unscoped(),
116 attributes: [ 'name' ],
117 model: AccountModel.unscoped(),
121 attributes: [ 'serverId' ],
122 model: ActorModel.unscoped(),
126 attributes: [ 'host' ],
127 model: ServerModel.unscoped()
137 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
140 model: () => VideoChannelModel.unscoped(),
145 exclude: [ 'privateKey', 'publicKey' ]
147 model: () => ActorModel.unscoped(),
151 attributes: [ 'host' ],
152 model: () => ServerModel.unscoped(),
158 model: () => AccountModel.unscoped(),
162 model: () => ActorModel.unscoped(),
164 exclude: [ 'privateKey', 'publicKey' ]
169 attributes: [ 'host' ],
170 model: () => ServerModel.unscoped(),
181 [ScopeNames.WITH_TAGS]: {
182 include: [ () => TagModel ]
184 [ScopeNames.WITH_FILES]: {
187 model: () => VideoFileModel,
192 [ScopeNames.WITH_SHARES]: {
195 model: () => VideoShareModel,
196 include: [ () => ActorModel ]
200 [ScopeNames.WITH_RATES]: {
203 model: () => AccountVideoRateModel,
204 include: [ () => AccountModel ]
208 [ScopeNames.WITH_COMMENTS]: {
211 model: () => VideoCommentModel
223 fields: [ 'createdAt' ]
226 fields: [ 'duration' ]
238 fields: [ 'channelId' ]
241 fields: [ 'id', 'privacy' ]
249 export class VideoModel extends Model<VideoModel> {
252 @Default(DataType.UUIDV4)
254 @Column(DataType.UUID)
258 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
264 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
270 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
276 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
281 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
286 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
292 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
293 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
297 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
327 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
328 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
333 commentsEnabled: boolean
341 @ForeignKey(() => VideoChannelModel)
345 @BelongsTo(() => VideoChannelModel, {
351 VideoChannel: VideoChannelModel
353 @BelongsToMany(() => TagModel, {
354 foreignKey: 'videoId',
355 through: () => VideoTagModel,
360 @HasMany(() => VideoAbuseModel, {
367 VideoAbuses: VideoAbuseModel[]
369 @HasMany(() => VideoFileModel, {
376 VideoFiles: VideoFileModel[]
378 @HasMany(() => VideoShareModel, {
385 VideoShares: VideoShareModel[]
387 @HasMany(() => AccountVideoRateModel, {
394 AccountVideoRates: AccountVideoRateModel[]
396 @HasMany(() => VideoCommentModel, {
404 VideoComments: VideoCommentModel[]
407 static async sendDelete (instance: VideoModel, options) {
408 if (instance.isOwned()) {
409 if (!instance.VideoChannel) {
410 instance.VideoChannel = await instance.$get('VideoChannel', {
414 include: [ ActorModel ]
417 transaction: options.transaction
418 }) as VideoChannelModel
421 logger.debug('Sending delete of video %s.', instance.url)
423 return sendDeleteVideo(instance, options.transaction)
430 static async removeFilesAndSendDelete (instance: VideoModel) {
431 const tasks: Promise<any>[] = []
433 tasks.push(instance.removeThumbnail())
435 if (instance.isOwned()) {
436 if (!Array.isArray(instance.VideoFiles)) {
437 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
440 tasks.push(instance.removePreview())
442 // Remove physical files and torrents
443 instance.VideoFiles.forEach(file => {
444 tasks.push(instance.removeFile(file))
445 tasks.push(instance.removeTorrent(file))
449 return Promise.all(tasks)
451 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
456 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
459 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
460 function getRawQuery (select: string) {
461 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
462 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
463 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
464 'WHERE "Account"."actorId" = ' + actorId
465 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
466 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
467 'WHERE "VideoShare"."actorId" = ' + actorId
469 return `(${queryVideo}) UNION (${queryVideoShare})`
472 const rawQuery = getRawQuery('"Video"."id"')
473 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
479 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
482 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
487 attributes: [ 'id' ],
488 model: VideoShareModel.unscoped(),
491 [Sequelize.Op.and]: [
494 [Sequelize.Op.not]: null
504 attributes: [ 'id', 'url' ],
505 model: ActorModel.unscoped()
510 model: VideoChannelModel.unscoped(),
514 attributes: [ 'name' ],
515 model: AccountModel.unscoped(),
519 attributes: [ 'id', 'url' ],
520 model: ActorModel.unscoped(),
526 attributes: [ 'id', 'url' ],
527 model: ActorModel.unscoped(),
533 attributes: [ 'type' ],
534 model: AccountVideoRateModel,
538 attributes: [ 'id' ],
539 model: AccountModel.unscoped(),
542 attributes: [ 'url' ],
543 model: ActorModel.unscoped(),
546 attributes: [ 'host' ],
557 attributes: [ 'url' ],
558 model: VideoCommentModel,
566 return Bluebird.all([
567 // FIXME: typing issue
568 VideoModel.findAll(query as any),
569 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
570 ]).then(([ rows, totals ]) => {
571 // totals: totalVideos + totalVideoShares
573 let totalVideoShares = 0
574 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
575 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
577 const total = totalVideos + totalVideoShares
585 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
589 order: [ getSort(sort) ],
592 model: VideoChannelModel,
607 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
615 static async listForApi (start: number, count: number, sort: string) {
619 order: [ getSort(sort) ]
622 const serverActor = await getServerActor()
624 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
625 .findAndCountAll(query)
626 .then(({ rows, count }) => {
634 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
635 const query: IFindOptions<VideoModel> = {
638 order: [ getSort(sort) ],
641 [Sequelize.Op.iLike]: '%' + value + '%'
646 const serverActor = await getServerActor()
648 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
649 .findAndCountAll(query).then(({ rows, count }) => {
657 static load (id: number) {
658 return VideoModel.findById(id)
661 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
662 const query: IFindOptions<VideoModel> = {
668 if (t !== undefined) query.transaction = t
670 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
673 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
674 const query: IFindOptions<VideoModel> = {
683 if (t !== undefined) query.transaction = t
685 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
688 static loadAndPopulateAccountAndServerAndTags (id: number) {
690 order: [ [ 'Tags', 'name', 'ASC' ] ]
694 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
695 .findById(id, options)
698 static loadByUUID (uuid: string) {
706 .scope([ ScopeNames.WITH_FILES ])
710 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
712 order: [ [ 'Tags', 'name', 'ASC' ] ],
719 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
723 static loadAndPopulateAll (id: number) {
725 order: [ [ 'Tags', 'name', 'ASC' ] ],
733 ScopeNames.WITH_RATES,
734 ScopeNames.WITH_SHARES,
735 ScopeNames.WITH_TAGS,
736 ScopeNames.WITH_FILES,
737 ScopeNames.WITH_ACCOUNT_DETAILS,
738 ScopeNames.WITH_COMMENTS
744 if (Array.isArray(this.VideoFiles) === false) return undefined
746 // The original file is the file that have the higher resolution
747 return maxBy(this.VideoFiles, file => file.resolution)
750 getVideoFilename (videoFile: VideoFileModel) {
751 return this.uuid + '-' + videoFile.resolution + videoFile.extname
754 getThumbnailName () {
755 // We always have a copy of the thumbnail
756 const extension = '.jpg'
757 return this.uuid + extension
761 const extension = '.jpg'
762 return this.uuid + extension
765 getTorrentFileName (videoFile: VideoFileModel) {
766 const extension = '.torrent'
767 return this.uuid + '-' + videoFile.resolution + extension
771 return this.remote === false
774 createPreview (videoFile: VideoFileModel) {
775 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
777 return generateImageFromVideoFile(
778 this.getVideoFilePath(videoFile),
779 CONFIG.STORAGE.PREVIEWS_DIR,
780 this.getPreviewName(),
785 createThumbnail (videoFile: VideoFileModel) {
786 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
788 return generateImageFromVideoFile(
789 this.getVideoFilePath(videoFile),
790 CONFIG.STORAGE.THUMBNAILS_DIR,
791 this.getThumbnailName(),
796 getVideoFilePath (videoFile: VideoFileModel) {
797 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
800 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
803 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
804 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
807 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
811 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
813 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
814 logger.info('Creating torrent %s.', filePath)
816 await writeFilePromise(filePath, torrent)
818 const parsedTorrent = parseTorrent(torrent)
819 videoFile.infoHash = parsedTorrent.infoHash
823 return '/videos/embed/' + this.uuid
826 getThumbnailPath () {
827 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
831 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
837 if (this.VideoChannel.Account.Actor.Server) {
838 serverHost = this.VideoChannel.Account.Actor.Server.host
840 // It means it's our video
841 serverHost = CONFIG.WEBSERVER.HOST
848 category: this.category,
849 categoryLabel: this.getCategoryLabel(),
850 licence: this.licence,
851 licenceLabel: this.getLicenceLabel(),
852 language: this.language,
853 languageLabel: this.getLanguageLabel(),
855 description: this.getTruncatedDescription(),
857 isLocal: this.isOwned(),
858 accountName: this.VideoChannel.Account.name,
859 duration: this.duration,
862 dislikes: this.dislikes,
863 thumbnailPath: this.getThumbnailPath(),
864 previewPath: this.getPreviewPath(),
865 embedPath: this.getEmbedPath(),
866 createdAt: this.createdAt,
867 updatedAt: this.updatedAt
871 toFormattedDetailsJSON () {
872 const formattedJson = this.toFormattedJSON()
874 // Maybe our server is not up to date and there are new privacy settings since our version
875 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
876 if (!privacyLabel) privacyLabel = 'Unknown'
878 const detailsJson = {
880 privacy: this.privacy,
881 descriptionPath: this.getDescriptionPath(),
882 channel: this.VideoChannel.toFormattedJSON(),
883 account: this.VideoChannel.Account.toFormattedJSON(),
884 tags: map<TagModel, string>(this.Tags, 'name'),
885 commentsEnabled: this.commentsEnabled,
889 // Format and sort video files
890 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
891 detailsJson.files = this.VideoFiles
893 let resolutionLabel = videoFile.resolution + 'p'
896 resolution: videoFile.resolution,
898 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
899 size: videoFile.size,
900 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
901 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
905 if (a.resolution < b.resolution) return 1
906 if (a.resolution === b.resolution) return 0
910 return Object.assign(formattedJson, detailsJson) as VideoDetails
913 toActivityPubObject (): VideoTorrentObject {
914 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
915 if (!this.Tags) this.Tags = []
917 const tag = this.Tags.map(t => ({
918 type: 'Hashtag' as 'Hashtag',
925 identifier: this.language + '',
926 name: this.getLanguageLabel()
933 identifier: this.category + '',
934 name: this.getCategoryLabel()
941 identifier: this.licence + '',
942 name: this.getLicenceLabel()
949 if (Array.isArray(this.AccountVideoRates)) {
950 const likes: string[] = []
951 const dislikes: string[] = []
953 for (const rate of this.AccountVideoRates) {
954 if (rate.type === 'like') {
955 likes.push(rate.Account.Actor.url)
956 } else if (rate.type === 'dislike') {
957 dislikes.push(rate.Account.Actor.url)
961 likesObject = activityPubCollection(likes)
962 dislikesObject = activityPubCollection(dislikes)
966 if (Array.isArray(this.VideoShares)) {
967 const shares: string[] = []
969 for (const videoShare of this.VideoShares) {
970 shares.push(videoShare.url)
973 sharesObject = activityPubCollection(shares)
977 if (Array.isArray(this.VideoComments)) {
978 const comments: string[] = []
980 for (const videoComment of this.VideoComments) {
981 comments.push(videoComment.url)
984 commentsObject = activityPubCollection(comments)
988 for (const file of this.VideoFiles) {
991 mimeType: 'video/' + file.extname.replace('.', ''),
992 href: this.getVideoFileUrl(file, baseUrlHttp),
993 width: file.resolution,
999 mimeType: 'application/x-bittorrent',
1000 href: this.getTorrentUrl(file, baseUrlHttp),
1001 width: file.resolution
1006 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1007 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1008 width: file.resolution
1012 // Add video url too
1015 mimeType: 'text/html',
1016 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1020 type: 'Video' as 'Video',
1023 duration: this.getActivityStreamDuration(),
1031 commentsEnabled: this.commentsEnabled,
1032 published: this.createdAt.toISOString(),
1033 updated: this.updatedAt.toISOString(),
1034 mediaType: 'text/markdown',
1035 content: this.getTruncatedDescription(),
1038 url: this.getThumbnailUrl(baseUrlHttp),
1039 mediaType: 'image/jpeg',
1040 width: THUMBNAILS_SIZE.width,
1041 height: THUMBNAILS_SIZE.height
1045 dislikes: dislikesObject,
1046 shares: sharesObject,
1047 comments: commentsObject,
1051 id: this.VideoChannel.Actor.url
1055 id: this.VideoChannel.Account.Actor.url
1061 getTruncatedDescription () {
1062 if (!this.description) return null
1065 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1068 return truncate(this.description, options)
1071 optimizeOriginalVideofile = async function () {
1072 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1073 const newExtname = '.mp4'
1074 const inputVideoFile = this.getOriginalFile()
1075 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1076 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1078 const transcodeOptions = {
1079 inputPath: videoInputPath,
1080 outputPath: videoOutputPath
1084 // Could be very long!
1085 await transcode(transcodeOptions)
1087 await unlinkPromise(videoInputPath)
1089 // Important to do this before getVideoFilename() to take in account the new file extension
1090 inputVideoFile.set('extname', newExtname)
1092 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1093 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1095 inputVideoFile.set('size', stats.size)
1097 await this.createTorrentAndSetInfoHash(inputVideoFile)
1098 await inputVideoFile.save()
1101 // Auto destruction...
1102 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1108 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1109 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1110 const extname = '.mp4'
1112 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1113 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1115 const newVideoFile = new VideoFileModel({
1121 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1123 const transcodeOptions = {
1124 inputPath: videoInputPath,
1125 outputPath: videoOutputPath,
1129 await transcode(transcodeOptions)
1131 const stats = await statPromise(videoOutputPath)
1133 newVideoFile.set('size', stats.size)
1135 await this.createTorrentAndSetInfoHash(newVideoFile)
1137 await newVideoFile.save()
1139 this.VideoFiles.push(newVideoFile)
1142 getOriginalFileHeight () {
1143 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1145 return getVideoFileHeight(originalFilePath)
1148 getDescriptionPath () {
1149 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1152 getCategoryLabel () {
1153 let categoryLabel = VIDEO_CATEGORIES[this.category]
1154 if (!categoryLabel) categoryLabel = 'Misc'
1156 return categoryLabel
1159 getLicenceLabel () {
1160 let licenceLabel = VIDEO_LICENCES[this.licence]
1161 if (!licenceLabel) licenceLabel = 'Unknown'
1166 getLanguageLabel () {
1167 let languageLabel = VIDEO_LANGUAGES[this.language]
1168 if (!languageLabel) languageLabel = 'Unknown'
1170 return languageLabel
1173 removeThumbnail () {
1174 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1175 return unlinkPromise(thumbnailPath)
1179 // Same name than video thumbnail
1180 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1183 removeFile (videoFile: VideoFileModel) {
1184 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1185 return unlinkPromise(filePath)
1188 removeTorrent (videoFile: VideoFileModel) {
1189 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1190 return unlinkPromise(torrentPath)
1193 getActivityStreamDuration () {
1194 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1195 return 'PT' + this.duration + 'S'
1198 private getBaseUrls () {
1202 if (this.isOwned()) {
1203 baseUrlHttp = CONFIG.WEBSERVER.URL
1204 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1206 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1207 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1210 return { baseUrlHttp, baseUrlWs }
1213 private getThumbnailUrl (baseUrlHttp: string) {
1214 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1217 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1218 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1221 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1222 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1225 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1226 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1227 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1228 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1230 const magnetHash = {
1234 infoHash: videoFile.infoHash,
1238 return magnetUtil.encode(magnetHash)