X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fmodels%2Fvideo%2Fvideo.ts;h=ec3d5ddb06cb22fb772fd73092ee0e85f50240e2;hb=30ff39e7f07898ebb716c938123825c678b4e5af;hp=5fb254b2d8f43ec7acd31868dbb310fe15d917a0;hpb=21e0727a84734cb0c81c1c9bb22a49b13e46fe5f;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/models/video/video.ts b/server/models/video/video.ts index 5fb254b2d..ec3d5ddb0 100644 --- a/server/models/video/video.ts +++ b/server/models/video/video.ts @@ -1,1171 +1,1948 @@ -import { map, maxBy, truncate } from 'lodash' +import * as Bluebird from 'bluebird' +import { maxBy } from 'lodash' import * as magnetUtil from 'magnet-uri' import * as parseTorrent from 'parse-torrent' import { join } from 'path' -import * as safeBuffer from 'safe-buffer' -import * as Sequelize from 'sequelize' -import { VideoPrivacy, VideoResolution } from '../../../shared' -import { VideoTorrentObject } from '../../../shared/models/activitypub/objects/video-torrent-object' import { - createTorrentPromise, - generateImageFromVideoFile, - getActivityPubUrl, - getVideoFileHeight, + CountOptions, + FindOptions, + IncludeOptions, + ModelIndexesOptions, + Op, + QueryTypes, + ScopeOptions, + Sequelize, + Transaction, + WhereOptions +} from 'sequelize' +import { + AllowNull, + BeforeDestroy, + BelongsTo, + BelongsToMany, + Column, + CreatedAt, + DataType, + Default, + ForeignKey, + HasMany, + HasOne, + Is, + IsInt, + IsUUID, + Min, + Model, + Scopes, + Table, + UpdatedAt +} from 'sequelize-typescript' +import { UserRight, VideoPrivacy, VideoState } from '../../../shared' +import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' +import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos' +import { VideoFilter } from '../../../shared/models/videos/video-query.type' +import { peertubeTruncate } from '../../helpers/core-utils' +import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' +import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc' +import { isVideoCategoryValid, isVideoDescriptionValid, isVideoDurationValid, isVideoLanguageValid, isVideoLicenceValid, isVideoNameValid, - isVideoNSFWValid, isVideoPrivacyValid, - logger, - renamePromise, - statPromise, - transcode, - unlinkPromise, - writeFilePromise -} from '../../helpers' -import { isVideoUrlValid } from '../../helpers/custom-validators/videos' + isVideoStateValid, + isVideoSupportValid +} from '../../helpers/custom-validators/videos' +import { getVideoFileResolution } from '../../helpers/ffmpeg-utils' +import { logger } from '../../helpers/logger' +import { getServerActor } from '../../helpers/utils' import { + ACTIVITY_PUB, API_VERSION, - CONFIG, CONSTRAINTS_FIELDS, - PREVIEWS_SIZE, + HLS_REDUNDANCY_DIRECTORY, + HLS_STREAMING_PLAYLIST_DIRECTORY, REMOTE_SCHEME, + STATIC_DOWNLOAD_PATHS, STATIC_PATHS, - THUMBNAILS_SIZE, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, - VIDEO_PRIVACIES -} from '../../initializers' -import { sendDeleteVideo } from '../../lib/activitypub/send-request' - -import { addMethodsToModel, getSort } from '../utils' - -import { TagInstance } from './tag-interface' -import { VideoFileInstance, VideoFileModel } from './video-file-interface' -import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface' - -const Buffer = safeBuffer.Buffer - -let Video: Sequelize.Model -let getOriginalFile: VideoMethods.GetOriginalFile -let getVideoFilename: VideoMethods.GetVideoFilename -let getThumbnailName: VideoMethods.GetThumbnailName -let getThumbnailPath: VideoMethods.GetThumbnailPath -let getPreviewName: VideoMethods.GetPreviewName -let getPreviewPath: VideoMethods.GetPreviewPath -let getTorrentFileName: VideoMethods.GetTorrentFileName -let isOwned: VideoMethods.IsOwned -let toFormattedJSON: VideoMethods.ToFormattedJSON -let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON -let toActivityPubObject: VideoMethods.ToActivityPubObject -let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile -let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile -let createPreview: VideoMethods.CreatePreview -let createThumbnail: VideoMethods.CreateThumbnail -let getVideoFilePath: VideoMethods.GetVideoFilePath -let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash -let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight -let getEmbedPath: VideoMethods.GetEmbedPath -let getDescriptionPath: VideoMethods.GetDescriptionPath -let getTruncatedDescription: VideoMethods.GetTruncatedDescription -let getCategoryLabel: VideoMethods.GetCategoryLabel -let getLicenceLabel: VideoMethods.GetLicenceLabel -let getLanguageLabel: VideoMethods.GetLanguageLabel - -let generateThumbnailFromData: VideoMethods.GenerateThumbnailFromData -let list: VideoMethods.List -let listForApi: VideoMethods.ListForApi -let listUserVideosForApi: VideoMethods.ListUserVideosForApi -let loadByHostAndUUID: VideoMethods.LoadByHostAndUUID -let listOwnedAndPopulateAccountAndTags: VideoMethods.ListOwnedAndPopulateAccountAndTags -let listOwnedByAccount: VideoMethods.ListOwnedByAccount -let load: VideoMethods.Load -let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount -let loadByUUID: VideoMethods.LoadByUUID -let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL -let loadLocalVideoByUUID: VideoMethods.LoadLocalVideoByUUID -let loadAndPopulateAccount: VideoMethods.LoadAndPopulateAccount -let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags -let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags -let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags -let removeThumbnail: VideoMethods.RemoveThumbnail -let removePreview: VideoMethods.RemovePreview -let removeFile: VideoMethods.RemoveFile -let removeTorrent: VideoMethods.RemoveTorrent - -export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) { - Video = sequelize.define('Video', - { - uuid: { - type: DataTypes.UUID, - defaultValue: DataTypes.UUIDV4, - allowNull: false, - validate: { - isUUID: 4 + VIDEO_PRIVACIES, + VIDEO_STATES, + WEBSERVER +} from '../../initializers/constants' +import { sendDeleteVideo } from '../../lib/activitypub/send' +import { AccountModel } from '../account/account' +import { AccountVideoRateModel } from '../account/account-video-rate' +import { ActorModel } from '../activitypub/actor' +import { AvatarModel } from '../avatar/avatar' +import { ServerModel } from '../server/server' +import { + buildBlockedAccountSQL, + buildTrigramSearchIndex, + buildWhereIdOrUUID, + createSafeIn, + createSimilarityAttribute, + getVideoSort, + isOutdated, + throwIfNotValid +} from '../utils' +import { TagModel } from './tag' +import { VideoAbuseModel } from './video-abuse' +import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel' +import { VideoCommentModel } from './video-comment' +import { VideoFileModel } from './video-file' +import { VideoShareModel } from './video-share' +import { VideoTagModel } from './video-tag' +import { ScheduleVideoUpdateModel } from './schedule-video-update' +import { VideoCaptionModel } from './video-caption' +import { VideoBlacklistModel } from './video-blacklist' +import { remove, writeFile } from 'fs-extra' +import { VideoViewModel } from './video-views' +import { VideoRedundancyModel } from '../redundancy/video-redundancy' +import { + videoFilesModelToFormattedJSON, + VideoFormattingJSONOptions, + videoModelToActivityPubObject, + videoModelToFormattedDetailsJSON, + videoModelToFormattedJSON +} from './video-format-utils' +import { UserVideoHistoryModel } from '../account/user-video-history' +import { UserModel } from '../account/user' +import { VideoImportModel } from './video-import' +import { VideoStreamingPlaylistModel } from './video-streaming-playlist' +import { VideoPlaylistElementModel } from './video-playlist-element' +import { CONFIG } from '../../initializers/config' +import { ThumbnailModel } from './thumbnail' +import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type' +import { createTorrentPromise } from '../../helpers/webtorrent' + +// FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation +const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [ + buildTrigramSearchIndex('video_name_trigram', 'name'), + + { fields: [ 'createdAt' ] }, + { fields: [ 'publishedAt' ] }, + { fields: [ 'duration' ] }, + { fields: [ 'views' ] }, + { fields: [ 'channelId' ] }, + { + fields: [ 'originallyPublishedAt' ], + where: { + originallyPublishedAt: { + [Op.ne]: null + } + } + }, + { + fields: [ 'category' ], // We don't care videos with an unknown category + where: { + category: { + [Op.ne]: null + } + } + }, + { + fields: [ 'licence' ], // We don't care videos with an unknown licence + where: { + licence: { + [Op.ne]: null + } + } + }, + { + fields: [ 'language' ], // We don't care videos with an unknown language + where: { + language: { + [Op.ne]: null + } + } + }, + { + fields: [ 'nsfw' ], // Most of the videos are not NSFW + where: { + nsfw: true + } + }, + { + fields: [ 'remote' ], // Only index local videos + where: { + remote: false + } + }, + { + fields: [ 'uuid' ], + unique: true + }, + { + fields: [ 'url' ], + unique: true + } +] + +export enum ScopeNames { + AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS', + FOR_API = 'FOR_API', + WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS', + WITH_TAGS = 'WITH_TAGS', + WITH_FILES = 'WITH_FILES', + WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE', + WITH_BLACKLISTED = 'WITH_BLACKLISTED', + WITH_USER_HISTORY = 'WITH_USER_HISTORY', + WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS', + WITH_USER_ID = 'WITH_USER_ID', + WITH_THUMBNAILS = 'WITH_THUMBNAILS' +} + +type ForAPIOptions = { + ids: number[] + + videoPlaylistId?: number + + withFiles?: boolean +} + +type AvailableForListIDsOptions = { + serverAccountId: number + followerActorId: number + includeLocalVideos: boolean + + withoutId?: boolean + + filter?: VideoFilter + categoryOneOf?: number[] + nsfw?: boolean + licenceOneOf?: number[] + languageOneOf?: string[] + tagsOneOf?: string[] + tagsAllOf?: string[] + + withFiles?: boolean + + accountId?: number + videoChannelId?: number + + videoPlaylistId?: number + + trendingDays?: number + user?: UserModel, + historyOfUser?: UserModel + + baseWhere?: WhereOptions[] +} + +@Scopes(() => ({ + [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => { + const query: FindOptions = { + where: { + id: { + [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken } }, - name: { - type: DataTypes.STRING, - allowNull: false, - validate: { - nameValid: value => { - const res = isVideoNameValid(value) - if (res === false) throw new Error('Video name is not valid.') - } + include: [ + { + model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }), + required: true + }, + { + attributes: [ 'type', 'filename' ], + model: ThumbnailModel, + required: false } - }, - category: { - type: DataTypes.INTEGER, - allowNull: false, - validate: { - categoryValid: value => { - const res = isVideoCategoryValid(value) - if (res === false) throw new Error('Video category is not valid.') - } + ] + } + + if (options.withFiles === true) { + query.include.push({ + model: VideoFileModel.unscoped(), + required: true + }) + } + + if (options.videoPlaylistId) { + query.include.push({ + model: VideoPlaylistElementModel.unscoped(), + required: true, + where: { + videoPlaylistId: options.videoPlaylistId } - }, - licence: { - type: DataTypes.INTEGER, - allowNull: false, - defaultValue: null, - validate: { - licenceValid: value => { - const res = isVideoLicenceValid(value) - if (res === false) throw new Error('Video licence is not valid.') + }) + } + + return query + }, + [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => { + const whereAnd = options.baseWhere ? options.baseWhere : [] + + const query: FindOptions = { + raw: true, + attributes: options.withoutId === true ? [] : [ 'id' ], + include: [] + } + + whereAnd.push({ + id: { + [ Op.notIn ]: Sequelize.literal( + '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")' + ) + } + }) + + whereAnd.push({ + channelId: { + [ Op.notIn ]: Sequelize.literal( + '(' + + 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' + + buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) + + ')' + + ')' + ) + } + }) + + // Only list public/published videos + if (!options.filter || options.filter !== 'all-local') { + const privacyWhere = { + // Always list public videos + privacy: VideoPrivacy.PUBLIC, + // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding + [ Op.or ]: [ + { + state: VideoState.PUBLISHED + }, + { + [ Op.and ]: { + state: VideoState.TO_TRANSCODE, + waitTranscoding: false + } } + ] + } + + whereAnd.push(privacyWhere) + } + + if (options.videoPlaylistId) { + query.include.push({ + attributes: [], + model: VideoPlaylistElementModel.unscoped(), + required: true, + where: { + videoPlaylistId: options.videoPlaylistId } - }, - language: { - type: DataTypes.INTEGER, - allowNull: true, - validate: { - languageValid: value => { - const res = isVideoLanguageValid(value) - if (res === false) throw new Error('Video language is not valid.') - } + }) + + query.subQuery = false + } + + if (options.filter || options.accountId || options.videoChannelId) { + const videoChannelInclude: IncludeOptions = { + attributes: [], + model: VideoChannelModel.unscoped(), + required: true + } + + if (options.videoChannelId) { + videoChannelInclude.where = { + id: options.videoChannelId } - }, - privacy: { - type: DataTypes.INTEGER, - allowNull: false, - validate: { - privacyValid: value => { - const res = isVideoPrivacyValid(value) - if (res === false) throw new Error('Video privacy is not valid.') - } + } + + if (options.filter || options.accountId) { + const accountInclude: IncludeOptions = { + attributes: [], + model: AccountModel.unscoped(), + required: true } - }, - nsfw: { - type: DataTypes.BOOLEAN, - allowNull: false, - validate: { - nsfwValid: value => { - const res = isVideoNSFWValid(value) - if (res === false) throw new Error('Video nsfw attribute is not valid.') - } + + if (options.filter) { + accountInclude.include = [ + { + attributes: [], + model: ActorModel.unscoped(), + required: true, + where: VideoModel.buildActorWhereWithFilter(options.filter) + } + ] } - }, - description: { - type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max), - allowNull: false, - validate: { - descriptionValid: value => { - const res = isVideoDescriptionValid(value) - if (res === false) throw new Error('Video description is not valid.') - } + + if (options.accountId) { + accountInclude.where = { id: options.accountId } } - }, - duration: { - type: DataTypes.INTEGER, - allowNull: false, - validate: { - durationValid: value => { - const res = isVideoDurationValid(value) - if (res === false) throw new Error('Video duration is not valid.') - } + + videoChannelInclude.include = [ accountInclude ] + } + + query.include.push(videoChannelInclude) + } + + if (options.followerActorId) { + let localVideosReq = '' + if (options.includeLocalVideos === true) { + localVideosReq = ' UNION ALL ' + + 'SELECT "video"."id" AS "id" FROM "video" ' + + 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + + 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + + 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + + 'WHERE "actor"."serverId" IS NULL' + } + + // Force actorId to be a number to avoid SQL injections + const actorIdNumber = parseInt(options.followerActorId.toString(), 10) + whereAnd.push({ + id: { + [ Op.in ]: Sequelize.literal( + '(' + + 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' + + 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' + + 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + + ' UNION ALL ' + + 'SELECT "video"."id" AS "id" FROM "video" ' + + 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + + 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + + 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + + 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' + + 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + + localVideosReq + + ')' + ) } - }, - views: { - type: DataTypes.INTEGER, - allowNull: false, - defaultValue: 0, - validate: { - min: 0, - isInt: true + }) + } + + if (options.withFiles === true) { + whereAnd.push({ + id: { + [ Op.in ]: Sequelize.literal( + '(SELECT "videoId" FROM "videoFile")' + ) } - }, - likes: { - type: DataTypes.INTEGER, - allowNull: false, - defaultValue: 0, - validate: { - min: 0, - isInt: true + }) + } + + // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN() + if (options.tagsAllOf || options.tagsOneOf) { + if (options.tagsOneOf) { + whereAnd.push({ + id: { + [ Op.in ]: Sequelize.literal( + '(' + + 'SELECT "videoId" FROM "videoTag" ' + + 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + + 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' + + ')' + ) + } + }) + } + + if (options.tagsAllOf) { + whereAnd.push({ + id: { + [ Op.in ]: Sequelize.literal( + '(' + + 'SELECT "videoId" FROM "videoTag" ' + + 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + + 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' + + 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length + + ')' + ) + } + }) + } + } + + if (options.nsfw === true || options.nsfw === false) { + whereAnd.push({ nsfw: options.nsfw }) + } + + if (options.categoryOneOf) { + whereAnd.push({ + category: { + [ Op.or ]: options.categoryOneOf } - }, - dislikes: { - type: DataTypes.INTEGER, - allowNull: false, - defaultValue: 0, - validate: { - min: 0, - isInt: true + }) + } + + if (options.licenceOneOf) { + whereAnd.push({ + licence: { + [ Op.or ]: options.licenceOneOf } - }, - remote: { - type: DataTypes.BOOLEAN, - allowNull: false, - defaultValue: false - }, - url: { - type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max), - allowNull: false, - validate: { - urlValid: value => { - const res = isVideoUrlValid(value) - if (res === false) throw new Error('Video URL is not valid.') + }) + } + + if (options.languageOneOf) { + let videoLanguages = options.languageOneOf + if (options.languageOneOf.find(l => l === '_unknown')) { + videoLanguages = videoLanguages.concat([ null ]) + } + + whereAnd.push({ + [Op.or]: [ + { + language: { + [ Op.or ]: videoLanguages + } + }, + { + id: { + [ Op.in ]: Sequelize.literal( + '(' + + 'SELECT "videoId" FROM "videoCaption" ' + + 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' + + ')' + ) + } } + ] + }) + } + + if (options.trendingDays) { + query.include.push(VideoModel.buildTrendingQuery(options.trendingDays)) + + query.subQuery = false + } + + if (options.historyOfUser) { + query.include.push({ + model: UserVideoHistoryModel, + required: true, + where: { + userId: options.historyOfUser.id } + }) + + // Even if the relation is n:m, we know that a user only have 0..1 video history + // So we won't have multiple rows for the same video + // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel + query.subQuery = false + } + + query.where = { + [ Op.and ]: whereAnd + } + + return query + }, + [ ScopeNames.WITH_THUMBNAILS ]: { + include: [ + { + model: ThumbnailModel, + required: false } - }, - { - indexes: [ - { - fields: [ 'name' ] - }, - { - fields: [ 'createdAt' ] - }, - { - fields: [ 'duration' ] - }, + ] + }, + [ ScopeNames.WITH_USER_ID ]: { + include: [ + { + attributes: [ 'accountId' ], + model: VideoChannelModel.unscoped(), + required: true, + include: [ + { + attributes: [ 'userId' ], + model: AccountModel.unscoped(), + required: true + } + ] + } + ] + }, + [ ScopeNames.WITH_ACCOUNT_DETAILS ]: { + include: [ + { + model: VideoChannelModel.unscoped(), + required: true, + include: [ + { + attributes: { + exclude: [ 'privateKey', 'publicKey' ] + }, + model: ActorModel.unscoped(), + required: true, + include: [ + { + attributes: [ 'host' ], + model: ServerModel.unscoped(), + required: false + }, + { + model: AvatarModel.unscoped(), + required: false + } + ] + }, + { + model: AccountModel.unscoped(), + required: true, + include: [ + { + model: ActorModel.unscoped(), + attributes: { + exclude: [ 'privateKey', 'publicKey' ] + }, + required: true, + include: [ + { + attributes: [ 'host' ], + model: ServerModel.unscoped(), + required: false + }, + { + model: AvatarModel.unscoped(), + required: false + } + ] + } + ] + } + ] + } + ] + }, + [ ScopeNames.WITH_TAGS ]: { + include: [ TagModel ] + }, + [ ScopeNames.WITH_BLACKLISTED ]: { + include: [ + { + attributes: [ 'id', 'reason' ], + model: VideoBlacklistModel, + required: false + } + ] + }, + [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => { + let subInclude: any[] = [] + + if (withRedundancies === true) { + subInclude = [ { - fields: [ 'views' ] - }, + attributes: [ 'fileUrl' ], + model: VideoRedundancyModel.unscoped(), + required: false + } + ] + } + + return { + include: [ { - fields: [ 'likes' ] - }, + model: VideoFileModel.unscoped(), + separate: true, // We may have multiple files, having multiple redundancies so let's separate this join + required: false, + include: subInclude + } + ] + } + }, + [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => { + let subInclude: any[] = [] + + if (withRedundancies === true) { + subInclude = [ { - fields: [ 'uuid' ] - }, + attributes: [ 'fileUrl' ], + model: VideoRedundancyModel.unscoped(), + required: false + } + ] + } + + return { + include: [ { - fields: [ 'channelId' ] + model: VideoStreamingPlaylistModel.unscoped(), + separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join + required: false, + include: subInclude } - ], - hooks: { - afterDestroy + ] + } + }, + [ ScopeNames.WITH_SCHEDULED_UPDATE ]: { + include: [ + { + model: ScheduleVideoUpdateModel.unscoped(), + required: false } + ] + }, + [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => { + return { + include: [ + { + attributes: [ 'currentTime' ], + model: UserVideoHistoryModel.unscoped(), + required: false, + where: { + userId + } + } + ] } - ) - - const classMethods = [ - associate, - - generateThumbnailFromData, - list, - listForApi, - listUserVideosForApi, - listOwnedAndPopulateAccountAndTags, - listOwnedByAccount, - load, - loadByUrlAndPopulateAccount, - loadAndPopulateAccount, - loadAndPopulateAccountAndServerAndTags, - loadByHostAndUUID, - loadByUUIDOrURL, - loadByUUID, - loadLocalVideoByUUID, - loadByUUIDAndPopulateAccountAndServerAndTags, - searchAndPopulateAccountAndServerAndTags - ] - const instanceMethods = [ - createPreview, - createThumbnail, - createTorrentAndSetInfoHash, - getPreviewName, - getPreviewPath, - getThumbnailName, - getThumbnailPath, - getTorrentFileName, - getVideoFilename, - getVideoFilePath, - getOriginalFile, - isOwned, - removeFile, - removePreview, - removeThumbnail, - removeTorrent, - toActivityPubObject, - toFormattedJSON, - toFormattedDetailsJSON, - optimizeOriginalVideofile, - transcodeOriginalVideofile, - getOriginalFileHeight, - getEmbedPath, - getTruncatedDescription, - getDescriptionPath, - getCategoryLabel, - getLicenceLabel, - getLanguageLabel - ] - addMethodsToModel(Video, classMethods, instanceMethods) - - return Video -} + } +})) +@Table({ + tableName: 'video', + indexes +}) +export class VideoModel extends Model { + + @AllowNull(false) + @Default(DataType.UUIDV4) + @IsUUID(4) + @Column(DataType.UUID) + uuid: string + + @AllowNull(false) + @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name')) + @Column + name: string + + @AllowNull(true) + @Default(null) + @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true)) + @Column + category: number + + @AllowNull(true) + @Default(null) + @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true)) + @Column + licence: number + + @AllowNull(true) + @Default(null) + @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true)) + @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max)) + language: string + + @AllowNull(false) + @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy')) + @Column + privacy: number + + @AllowNull(false) + @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean')) + @Column + nsfw: boolean + + @AllowNull(true) + @Default(null) + @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true)) + @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max)) + description: string + + @AllowNull(true) + @Default(null) + @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true)) + @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max)) + support: string + + @AllowNull(false) + @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration')) + @Column + duration: number + + @AllowNull(false) + @Default(0) + @IsInt + @Min(0) + @Column + views: number + + @AllowNull(false) + @Default(0) + @IsInt + @Min(0) + @Column + likes: number + + @AllowNull(false) + @Default(0) + @IsInt + @Min(0) + @Column + dislikes: number + + @AllowNull(false) + @Column + remote: boolean + + @AllowNull(false) + @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) + @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max)) + url: string + + @AllowNull(false) + @Column + commentsEnabled: boolean + + @AllowNull(false) + @Column + downloadEnabled: boolean + + @AllowNull(false) + @Column + waitTranscoding: boolean + + @AllowNull(false) + @Default(null) + @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state')) + @Column + state: VideoState + + @CreatedAt + createdAt: Date + + @UpdatedAt + updatedAt: Date + + @AllowNull(false) + @Default(DataType.NOW) + @Column + publishedAt: Date + + @AllowNull(true) + @Default(null) + @Column + originallyPublishedAt: Date + + @ForeignKey(() => VideoChannelModel) + @Column + channelId: number + + @BelongsTo(() => VideoChannelModel, { + foreignKey: { + allowNull: true + }, + hooks: true + }) + VideoChannel: VideoChannelModel -// ------------------------------ METHODS ------------------------------ + @BelongsToMany(() => TagModel, { + foreignKey: 'videoId', + through: () => VideoTagModel, + onDelete: 'CASCADE' + }) + Tags: TagModel[] -function associate (models) { - Video.belongsTo(models.VideoChannel, { + @HasMany(() => ThumbnailModel, { foreignKey: { - name: 'channelId', + name: 'videoId', + allowNull: true + }, + hooks: true, + onDelete: 'cascade' + }) + Thumbnails: ThumbnailModel[] + + @HasMany(() => VideoPlaylistElementModel, { + foreignKey: { + name: 'videoId', allowNull: false }, onDelete: 'cascade' }) + VideoPlaylistElements: VideoPlaylistElementModel[] - Video.belongsToMany(models.Tag, { - foreignKey: 'videoId', - through: models.VideoTag, + @HasMany(() => VideoAbuseModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, onDelete: 'cascade' }) + VideoAbuses: VideoAbuseModel[] - Video.hasMany(models.VideoAbuse, { + @HasMany(() => VideoFileModel, { foreignKey: { name: 'videoId', allowNull: false }, + hooks: true, onDelete: 'cascade' }) + VideoFiles: VideoFileModel[] - Video.hasMany(models.VideoFile, { + @HasMany(() => VideoStreamingPlaylistModel, { foreignKey: { name: 'videoId', allowNull: false }, + hooks: true, onDelete: 'cascade' }) -} + VideoStreamingPlaylists: VideoStreamingPlaylistModel[] + + @HasMany(() => VideoShareModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade' + }) + VideoShares: VideoShareModel[] + + @HasMany(() => AccountVideoRateModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade' + }) + AccountVideoRates: AccountVideoRateModel[] + + @HasMany(() => VideoCommentModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade', + hooks: true + }) + VideoComments: VideoCommentModel[] + + @HasMany(() => VideoViewModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade' + }) + VideoViews: VideoViewModel[] -function afterDestroy (video: VideoInstance) { - const tasks = [] + @HasMany(() => UserVideoHistoryModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade' + }) + UserVideoHistories: UserVideoHistoryModel[] - tasks.push( - video.removeThumbnail() - ) + @HasOne(() => ScheduleVideoUpdateModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade' + }) + ScheduleVideoUpdate: ScheduleVideoUpdateModel - if (video.isOwned()) { - tasks.push( - video.removePreview(), - sendDeleteVideo(video, undefined) - ) + @HasOne(() => VideoBlacklistModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade' + }) + VideoBlacklist: VideoBlacklistModel + + @HasOne(() => VideoImportModel, { + foreignKey: { + name: 'videoId', + allowNull: true + }, + onDelete: 'set null' + }) + VideoImport: VideoImportModel - // Remove physical files and torrents - video.VideoFiles.forEach(file => { - tasks.push(video.removeFile(file)) - tasks.push(video.removeTorrent(file)) + @HasMany(() => VideoCaptionModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade', + hooks: true, + [ 'separate' as any ]: true + }) + VideoCaptions: VideoCaptionModel[] + + @BeforeDestroy + static async sendDelete (instance: VideoModel, options) { + if (instance.isOwned()) { + if (!instance.VideoChannel) { + instance.VideoChannel = await instance.$get('VideoChannel', { + include: [ + { + model: AccountModel, + include: [ ActorModel ] + } + ], + transaction: options.transaction + }) as VideoChannelModel + } + + return sendDeleteVideo(instance, options.transaction) + } + + return undefined + } + + @BeforeDestroy + static async removeFiles (instance: VideoModel) { + const tasks: Promise[] = [] + + logger.info('Removing files of video %s.', instance.url) + + if (instance.isOwned()) { + if (!Array.isArray(instance.VideoFiles)) { + instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[] + } + + // Remove physical files and torrents + instance.VideoFiles.forEach(file => { + tasks.push(instance.removeFile(file)) + tasks.push(instance.removeTorrent(file)) + }) + + // Remove playlists file + tasks.push(instance.removeStreamingPlaylist()) + } + + // Do not wait video deletion because we could be in a transaction + Promise.all(tasks) + .catch(err => { + logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }) + }) + + return undefined + } + + static listLocal () { + const query = { + where: { + remote: false + } + } + + return VideoModel.scope([ + ScopeNames.WITH_FILES, + ScopeNames.WITH_STREAMING_PLAYLISTS, + ScopeNames.WITH_THUMBNAILS + ]).findAll(query) + } + + static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) { + function getRawQuery (select: string) { + const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' + + 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' + + 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' + + 'WHERE "Account"."actorId" = ' + actorId + const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' + + 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' + + 'WHERE "VideoShare"."actorId" = ' + actorId + + return `(${queryVideo}) UNION (${queryVideoShare})` + } + + const rawQuery = getRawQuery('"Video"."id"') + const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"') + + const query = { + distinct: true, + offset: start, + limit: count, + order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings + where: { + id: { + [ Op.in ]: Sequelize.literal('(' + rawQuery + ')') + }, + [ Op.or ]: [ + { privacy: VideoPrivacy.PUBLIC }, + { privacy: VideoPrivacy.UNLISTED } + ] + }, + include: [ + { + attributes: [ 'language' ], + model: VideoCaptionModel.unscoped(), + required: false + }, + { + attributes: [ 'id', 'url' ], + model: VideoShareModel.unscoped(), + required: false, + // We only want videos shared by this actor + where: { + [ Op.and ]: [ + { + id: { + [ Op.not ]: null + } + }, + { + actorId + } + ] + }, + include: [ + { + attributes: [ 'id', 'url' ], + model: ActorModel.unscoped() + } + ] + }, + { + model: VideoChannelModel.unscoped(), + required: true, + include: [ + { + attributes: [ 'name' ], + model: AccountModel.unscoped(), + required: true, + include: [ + { + attributes: [ 'id', 'url', 'followersUrl' ], + model: ActorModel.unscoped(), + required: true + } + ] + }, + { + attributes: [ 'id', 'url', 'followersUrl' ], + model: ActorModel.unscoped(), + required: true + } + ] + }, + VideoFileModel, + TagModel + ] + } + + return Bluebird.all([ + VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query), + VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT }) + ]).then(([ rows, totals ]) => { + // totals: totalVideos + totalVideoShares + let totalVideos = 0 + let totalVideoShares = 0 + if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10) + if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10) + + const total = totalVideos + totalVideoShares + return { + data: rows, + total: total + } }) } - return Promise.all(tasks) - .catch(err => { - logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err) + static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) { + function buildBaseQuery (): FindOptions { + return { + offset: start, + limit: count, + order: getVideoSort(sort), + include: [ + { + model: VideoChannelModel, + required: true, + include: [ + { + model: AccountModel, + where: { + id: accountId + }, + required: true + } + ] + } + ] + } + } + + const countQuery = buildBaseQuery() + const findQuery = buildBaseQuery() + + const findScopes = [ + ScopeNames.WITH_SCHEDULED_UPDATE, + ScopeNames.WITH_BLACKLISTED, + ScopeNames.WITH_THUMBNAILS + ] + + if (withFiles === true) { + findQuery.include.push({ + model: VideoFileModel.unscoped(), + required: true + }) + } + + return Promise.all([ + VideoModel.count(countQuery), + VideoModel.scope(findScopes).findAll(findQuery) + ]).then(([ count, rows ]) => { + return { + data: rows, + total: count + } }) -} + } -getOriginalFile = function (this: VideoInstance) { - if (Array.isArray(this.VideoFiles) === false) return undefined + static async listForApi (options: { + start: number, + count: number, + sort: string, + nsfw: boolean, + includeLocalVideos: boolean, + withFiles: boolean, + categoryOneOf?: number[], + licenceOneOf?: number[], + languageOneOf?: string[], + tagsOneOf?: string[], + tagsAllOf?: string[], + filter?: VideoFilter, + accountId?: number, + videoChannelId?: number, + followerActorId?: number + videoPlaylistId?: number, + trendingDays?: number, + user?: UserModel, + historyOfUser?: UserModel + }, countVideos = true) { + if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) { + throw new Error('Try to filter all-local but no user has not the see all videos right') + } - // The original file is the file that have the higher resolution - return maxBy(this.VideoFiles, file => file.resolution) -} + const query: FindOptions & { where?: null } = { + offset: options.start, + limit: options.count, + order: getVideoSort(options.sort) + } -getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) { - return this.uuid + '-' + videoFile.resolution + videoFile.extname -} + let trendingDays: number + if (options.sort.endsWith('trending')) { + trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS -getThumbnailName = function (this: VideoInstance) { - // We always have a copy of the thumbnail - const extension = '.jpg' - return this.uuid + extension -} + query.group = 'VideoModel.id' + } -getPreviewName = function (this: VideoInstance) { - const extension = '.jpg' - return this.uuid + extension -} + const serverActor = await getServerActor() + + // followerActorId === null has a meaning, so just check undefined + const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id + + const queryOptions = { + followerActorId, + serverAccountId: serverActor.Account.id, + nsfw: options.nsfw, + categoryOneOf: options.categoryOneOf, + licenceOneOf: options.licenceOneOf, + languageOneOf: options.languageOneOf, + tagsOneOf: options.tagsOneOf, + tagsAllOf: options.tagsAllOf, + filter: options.filter, + withFiles: options.withFiles, + accountId: options.accountId, + videoChannelId: options.videoChannelId, + videoPlaylistId: options.videoPlaylistId, + includeLocalVideos: options.includeLocalVideos, + user: options.user, + historyOfUser: options.historyOfUser, + trendingDays + } -getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) { - const extension = '.torrent' - return this.uuid + '-' + videoFile.resolution + extension -} + return VideoModel.getAvailableForApi(query, queryOptions, countVideos) + } -isOwned = function (this: VideoInstance) { - return this.remote === false -} + static async searchAndPopulateAccountAndServer (options: { + includeLocalVideos: boolean + search?: string + start?: number + count?: number + sort?: string + startDate?: string // ISO 8601 + endDate?: string // ISO 8601 + originallyPublishedStartDate?: string + originallyPublishedEndDate?: string + nsfw?: boolean + categoryOneOf?: number[] + licenceOneOf?: number[] + languageOneOf?: string[] + tagsOneOf?: string[] + tagsAllOf?: string[] + durationMin?: number // seconds + durationMax?: number // seconds + user?: UserModel, + filter?: VideoFilter + }) { + const whereAnd = [] + + if (options.startDate || options.endDate) { + const publishedAtRange = {} + + if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate + if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate + + whereAnd.push({ publishedAt: publishedAtRange }) + } -createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) { - const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height + if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) { + const originallyPublishedAtRange = {} - return generateImageFromVideoFile( - this.getVideoFilePath(videoFile), - CONFIG.STORAGE.PREVIEWS_DIR, - this.getPreviewName(), - imageSize - ) -} + if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate + if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate -createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) { - const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height + whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange }) + } - return generateImageFromVideoFile( - this.getVideoFilePath(videoFile), - CONFIG.STORAGE.THUMBNAILS_DIR, - this.getThumbnailName(), - imageSize - ) -} + if (options.durationMin || options.durationMax) { + const durationRange = {} + + if (options.durationMin) durationRange[ Op.gte ] = options.durationMin + if (options.durationMax) durationRange[ Op.lte ] = options.durationMax + + whereAnd.push({ duration: durationRange }) + } + + const attributesInclude = [] + const escapedSearch = VideoModel.sequelize.escape(options.search) + const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%') + if (options.search) { + whereAnd.push( + { + id: { + [ Op.in ]: Sequelize.literal( + '(' + + 'SELECT "video"."id" FROM "video" ' + + 'WHERE ' + + 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' + + 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' + + 'UNION ALL ' + + 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' + + 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + + 'WHERE "tag"."name" = ' + escapedSearch + + ')' + ) + } + } + ) + + attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search)) + } + + // Cannot search on similarity if we don't have a search + if (!options.search) { + attributesInclude.push( + Sequelize.literal('0 as similarity') + ) + } + + const query = { + attributes: { + include: attributesInclude + }, + offset: options.start, + limit: options.count, + order: getVideoSort(options.sort) + } + + const serverActor = await getServerActor() + const queryOptions = { + followerActorId: serverActor.id, + serverAccountId: serverActor.Account.id, + includeLocalVideos: options.includeLocalVideos, + nsfw: options.nsfw, + categoryOneOf: options.categoryOneOf, + licenceOneOf: options.licenceOneOf, + languageOneOf: options.languageOneOf, + tagsOneOf: options.tagsOneOf, + tagsAllOf: options.tagsAllOf, + user: options.user, + filter: options.filter, + baseWhere: whereAnd + } + + return VideoModel.getAvailableForApi(query, queryOptions) + } + + static load (id: number | string, t?: Transaction) { + const where = buildWhereIdOrUUID(id) + const options = { + where, + transaction: t + } + + return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) + } + + static loadWithRights (id: number | string, t?: Transaction) { + const where = buildWhereIdOrUUID(id) + const options = { + where, + transaction: t + } + + return VideoModel.scope([ + ScopeNames.WITH_BLACKLISTED, + ScopeNames.WITH_USER_ID, + ScopeNames.WITH_THUMBNAILS + ]).findOne(options) + } + + static loadOnlyId (id: number | string, t?: Transaction) { + const where = buildWhereIdOrUUID(id) + + const options = { + attributes: [ 'id' ], + where, + transaction: t + } + + return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) + } + + static loadWithFiles (id: number, t?: Transaction, logging?: boolean) { + return VideoModel.scope([ + ScopeNames.WITH_FILES, + ScopeNames.WITH_STREAMING_PLAYLISTS, + ScopeNames.WITH_THUMBNAILS + ]).findByPk(id, { transaction: t, logging }) + } + + static loadByUUIDWithFile (uuid: string) { + const options = { + where: { + uuid + } + } + + return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) + } + + static loadByUrl (url: string, transaction?: Transaction) { + const query: FindOptions = { + where: { + url + }, + transaction + } + + return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query) + } -getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) { - return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) -} + static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) { + const query: FindOptions = { + where: { + url + }, + transaction + } -createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) { - const options = { - announceList: [ - [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ] - ], - urlList: [ - CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) - ] + return VideoModel.scope([ + ScopeNames.WITH_ACCOUNT_DETAILS, + ScopeNames.WITH_FILES, + ScopeNames.WITH_STREAMING_PLAYLISTS, + ScopeNames.WITH_THUMBNAILS + ]).findOne(query) } - const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options) + static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) { + const where = buildWhereIdOrUUID(id) - const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) - logger.info('Creating torrent %s.', filePath) + const options = { + order: [ [ 'Tags', 'name', 'ASC' ] ] as any, + where, + transaction: t + } - await writeFilePromise(filePath, torrent) + const scopes: (string | ScopeOptions)[] = [ + ScopeNames.WITH_TAGS, + ScopeNames.WITH_BLACKLISTED, + ScopeNames.WITH_ACCOUNT_DETAILS, + ScopeNames.WITH_SCHEDULED_UPDATE, + ScopeNames.WITH_FILES, + ScopeNames.WITH_STREAMING_PLAYLISTS, + ScopeNames.WITH_THUMBNAILS + ] - const parsedTorrent = parseTorrent(torrent) - videoFile.infoHash = parsedTorrent.infoHash -} + if (userId) { + scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] }) + } -getEmbedPath = function (this: VideoInstance) { - return '/videos/embed/' + this.uuid -} + return VideoModel + .scope(scopes) + .findOne(options) + } -getThumbnailPath = function (this: VideoInstance) { - return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName()) -} + static loadForGetAPI (id: number | string, t?: Transaction, userId?: number) { + const where = buildWhereIdOrUUID(id) -getPreviewPath = function (this: VideoInstance) { - return join(STATIC_PATHS.PREVIEWS, this.getPreviewName()) -} + const options = { + order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings + where, + transaction: t + } -toFormattedJSON = function (this: VideoInstance) { - let serverHost - - if (this.VideoChannel.Account.Server) { - serverHost = this.VideoChannel.Account.Server.host - } else { - // It means it's our video - serverHost = CONFIG.WEBSERVER.HOST - } - - const json = { - id: this.id, - uuid: this.uuid, - name: this.name, - category: this.category, - categoryLabel: this.getCategoryLabel(), - licence: this.licence, - licenceLabel: this.getLicenceLabel(), - language: this.language, - languageLabel: this.getLanguageLabel(), - nsfw: this.nsfw, - description: this.getTruncatedDescription(), - serverHost, - isLocal: this.isOwned(), - account: this.VideoChannel.Account.name, - duration: this.duration, - views: this.views, - likes: this.likes, - dislikes: this.dislikes, - tags: map(this.Tags, 'name'), - thumbnailPath: this.getThumbnailPath(), - previewPath: this.getPreviewPath(), - embedPath: this.getEmbedPath(), - createdAt: this.createdAt, - updatedAt: this.updatedAt - } - - return json -} + const scopes: (string | ScopeOptions)[] = [ + ScopeNames.WITH_TAGS, + ScopeNames.WITH_BLACKLISTED, + ScopeNames.WITH_ACCOUNT_DETAILS, + ScopeNames.WITH_SCHEDULED_UPDATE, + ScopeNames.WITH_THUMBNAILS, + { method: [ ScopeNames.WITH_FILES, true ] }, + { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } + ] -toFormattedDetailsJSON = function (this: VideoInstance) { - const formattedJson = this.toFormattedJSON() - - // Maybe our server is not up to date and there are new privacy settings since our version - let privacyLabel = VIDEO_PRIVACIES[this.privacy] - if (!privacyLabel) privacyLabel = 'Unknown' - - const detailsJson = { - privacyLabel, - privacy: this.privacy, - descriptionPath: this.getDescriptionPath(), - channel: this.VideoChannel.toFormattedJSON(), - files: [] - } - - // Format and sort video files - const { baseUrlHttp, baseUrlWs } = getBaseUrls(this) - detailsJson.files = this.VideoFiles - .map(videoFile => { - let resolutionLabel = videoFile.resolution + 'p' - - const videoFileJson = { - resolution: videoFile.resolution, - resolutionLabel, - magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs), - size: videoFile.size, - torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp), - fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp) - } - - return videoFileJson - }) - .sort((a, b) => { - if (a.resolution < b.resolution) return 1 - if (a.resolution === b.resolution) return 0 - return -1 - }) - - return Object.assign(formattedJson, detailsJson) -} + if (userId) { + scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] }) + } -toActivityPubObject = function (this: VideoInstance) { - const { baseUrlHttp, baseUrlWs } = getBaseUrls(this) - - const tag = this.Tags.map(t => ({ - type: 'Hashtag' as 'Hashtag', - name: t.name - })) - - const url = [] - for (const file of this.VideoFiles) { - url.push({ - type: 'Link', - mimeType: 'video/' + file.extname.replace('.', ''), - url: getVideoFileUrl(this, file, baseUrlHttp), - width: file.resolution, - size: file.size - }) + return VideoModel + .scope(scopes) + .findOne(options) + } - url.push({ - type: 'Link', - mimeType: 'application/x-bittorrent', - url: getTorrentUrl(this, file, baseUrlHttp), - width: file.resolution + static async getStats () { + const totalLocalVideos = await VideoModel.count({ + where: { + remote: false + } }) + const totalVideos = await VideoModel.count() - url.push({ - type: 'Link', - mimeType: 'application/x-bittorrent;x-scheme-handler/magnet', - url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs), - width: file.resolution + let totalLocalVideoViews = await VideoModel.sum('views', { + where: { + remote: false + } }) + // Sequelize could return null... + if (!totalLocalVideoViews) totalLocalVideoViews = 0 + + return { + totalLocalVideos, + totalLocalVideoViews, + totalVideos + } } - const videoObject: VideoTorrentObject = { - type: 'Video' as 'Video', - id: getActivityPubUrl('video', this.uuid), - name: this.name, - // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration - duration: 'PT' + this.duration + 'S', - uuid: this.uuid, - tag, - category: { - identifier: this.category + '', - name: this.getCategoryLabel() - }, - licence: { - identifier: this.licence + '', - name: this.getLicenceLabel() - }, - language: { - identifier: this.language + '', - name: this.getLanguageLabel() - }, - views: this.views, - nsfw: this.nsfw, - published: this.createdAt.toISOString(), - updated: this.updatedAt.toISOString(), - mediaType: 'text/markdown', - content: this.getTruncatedDescription(), - icon: { - type: 'Image', - url: getThumbnailUrl(this, baseUrlHttp), - mediaType: 'image/jpeg', - width: THUMBNAILS_SIZE.width, - height: THUMBNAILS_SIZE.height - }, - url + static incrementViews (id: number, views: number) { + return VideoModel.increment('views', { + by: views, + where: { + id + } + }) } - return videoObject -} + static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) { + // Instances only share videos + const query = 'SELECT 1 FROM "videoShare" ' + + 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' + + 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' + + 'LIMIT 1' + + const options = { + type: QueryTypes.SELECT, + bind: { followerActorId, videoId }, + raw: true + } -getTruncatedDescription = function (this: VideoInstance) { - const options = { - length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max + return VideoModel.sequelize.query(query, options) + .then(results => results.length === 1) } - return truncate(this.description, options) -} - -optimizeOriginalVideofile = async function (this: VideoInstance) { - const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR - const newExtname = '.mp4' - const inputVideoFile = this.getOriginalFile() - const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile)) - const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname) + static bulkUpdateSupportField (videoChannel: VideoChannelModel, t: Transaction) { + const options = { + where: { + channelId: videoChannel.id + }, + transaction: t + } - const transcodeOptions = { - inputPath: videoInputPath, - outputPath: videoOutputPath + return VideoModel.update({ support: videoChannel.support }, options) } - try { - // Could be very long! - await transcode(transcodeOptions) - - await unlinkPromise(videoInputPath) + static getAllIdsFromChannel (videoChannel: VideoChannelModel) { + const query = { + attributes: [ 'id' ], + where: { + channelId: videoChannel.id + } + } - // Important to do this before getVideoFilename() to take in account the new file extension - inputVideoFile.set('extname', newExtname) + return VideoModel.findAll(query) + .then(videos => videos.map(v => v.id)) + } - await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile)) - const stats = await statPromise(this.getVideoFilePath(inputVideoFile)) + // threshold corresponds to how many video the field should have to be returned + static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) { + const serverActor = await getServerActor() + const followerActorId = serverActor.id - inputVideoFile.set('size', stats.size) + const scopeOptions: AvailableForListIDsOptions = { + serverAccountId: serverActor.Account.id, + followerActorId, + includeLocalVideos: true, + withoutId: true // Don't break aggregation + } - await this.createTorrentAndSetInfoHash(inputVideoFile) - await inputVideoFile.save() + const query: FindOptions = { + attributes: [ field ], + limit: count, + group: field, + having: Sequelize.where( + Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold } + ), + order: [ (this.sequelize as any).random() ] + } - } catch (err) { - // Auto destruction... - this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err)) + return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] }) + .findAll(query) + .then(rows => rows.map(r => r[ field ])) + } - throw err + static buildTrendingQuery (trendingDays: number) { + return { + attributes: [], + subQuery: false, + model: VideoViewModel, + required: false, + where: { + startDate: { + [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays) + } + } + } } -} -transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) { - const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR - const extname = '.mp4' + private static buildActorWhereWithFilter (filter?: VideoFilter) { + if (filter && (filter === 'local' || filter === 'all-local')) { + return { + serverId: null + } + } - // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed - const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile())) + return {} + } - const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({ - resolution, - extname, - size: 0, - videoId: this.id - }) - const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile)) + private static async getAvailableForApi ( + query: FindOptions & { where?: null }, // Forbid where field in query + options: AvailableForListIDsOptions, + countVideos = true + ) { + const idsScope: ScopeOptions = { + method: [ + ScopeNames.AVAILABLE_FOR_LIST_IDS, options + ] + } - const transcodeOptions = { - inputPath: videoInputPath, - outputPath: videoOutputPath, - resolution - } + // Remove trending sort on count, because it uses a group by + const countOptions = Object.assign({}, options, { trendingDays: undefined }) + const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined }) + const countScope: ScopeOptions = { + method: [ + ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions + ] + } - await transcode(transcodeOptions) + const [ count, ids ] = await Promise.all([ + countVideos + ? VideoModel.scope(countScope).count(countQuery) + : Promise.resolve(undefined), + + VideoModel.scope(idsScope) + .findAll(query) + .then(rows => rows.map(r => r.id)) + ]) + + if (ids.length === 0) return { data: [], total: count } + + const secondQuery: FindOptions = { + offset: 0, + limit: query.limit, + attributes: query.attributes, + order: [ // Keep original order + Sequelize.literal( + ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ') + ) + ] + } - const stats = await statPromise(videoOutputPath) + const apiScope: (string | ScopeOptions)[] = [] - newVideoFile.set('size', stats.size) + if (options.user) { + apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] }) + } - await this.createTorrentAndSetInfoHash(newVideoFile) + apiScope.push({ + method: [ + ScopeNames.FOR_API, { + ids, + withFiles: options.withFiles, + videoPlaylistId: options.videoPlaylistId + } as ForAPIOptions + ] + }) - await newVideoFile.save() + const rows = await VideoModel.scope(apiScope).findAll(secondQuery) - this.VideoFiles.push(newVideoFile) -} + return { + data: rows, + total: count + } + } -getOriginalFileHeight = function (this: VideoInstance) { - const originalFilePath = this.getVideoFilePath(this.getOriginalFile()) + static getCategoryLabel (id: number) { + return VIDEO_CATEGORIES[ id ] || 'Misc' + } - return getVideoFileHeight(originalFilePath) -} + static getLicenceLabel (id: number) { + return VIDEO_LICENCES[ id ] || 'Unknown' + } -getDescriptionPath = function (this: VideoInstance) { - return `/api/${API_VERSION}/videos/${this.uuid}/description` -} + static getLanguageLabel (id: string) { + return VIDEO_LANGUAGES[ id ] || 'Unknown' + } -getCategoryLabel = function (this: VideoInstance) { - let categoryLabel = VIDEO_CATEGORIES[this.category] + static getPrivacyLabel (id: number) { + return VIDEO_PRIVACIES[ id ] || 'Unknown' + } - // Maybe our server is not up to date and there are new categories since our version - if (!categoryLabel) categoryLabel = 'Misc' + static getStateLabel (id: number) { + return VIDEO_STATES[ id ] || 'Unknown' + } - return categoryLabel -} + getOriginalFile () { + if (Array.isArray(this.VideoFiles) === false) return undefined -getLicenceLabel = function (this: VideoInstance) { - let licenceLabel = VIDEO_LICENCES[this.licence] + // The original file is the file that have the higher resolution + return maxBy(this.VideoFiles, file => file.resolution) + } - // Maybe our server is not up to date and there are new licences since our version - if (!licenceLabel) licenceLabel = 'Unknown' + async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) { + thumbnail.videoId = this.id - return licenceLabel -} + const savedThumbnail = await thumbnail.save({ transaction }) -getLanguageLabel = function (this: VideoInstance) { - // Language is an optional attribute - let languageLabel = VIDEO_LANGUAGES[this.language] - if (!languageLabel) languageLabel = 'Unknown' + if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = [] - return languageLabel -} + // Already have this thumbnail, skip + if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return -removeThumbnail = function (this: VideoInstance) { - const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName()) - return unlinkPromise(thumbnailPath) -} + this.Thumbnails.push(savedThumbnail) + } -removePreview = function (this: VideoInstance) { - // Same name than video thumbnail - return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName()) -} + getVideoFilename (videoFile: VideoFileModel) { + return this.uuid + '-' + videoFile.resolution + videoFile.extname + } -removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) { - const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) - return unlinkPromise(filePath) -} + generateThumbnailName () { + return this.uuid + '.jpg' + } -removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) { - const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) - return unlinkPromise(torrentPath) -} + getMiniature () { + if (Array.isArray(this.Thumbnails) === false) return undefined -// ------------------------------ STATICS ------------------------------ + return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE) + } -generateThumbnailFromData = function (video: VideoInstance, thumbnailData: string) { - // Creating the thumbnail for a remote video + generatePreviewName () { + return this.uuid + '.jpg' + } - const thumbnailName = video.getThumbnailName() - const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName) - return writeFilePromise(thumbnailPath, Buffer.from(thumbnailData, 'binary')).then(() => { - return thumbnailName - }) -} + getPreview () { + if (Array.isArray(this.Thumbnails) === false) return undefined -list = function () { - const query = { - include: [ Video['sequelize'].models.VideoFile ] + return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW) } - return Video.findAll(query) -} + getTorrentFileName (videoFile: VideoFileModel) { + const extension = '.torrent' + return this.uuid + '-' + videoFile.resolution + extension + } -listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) { - const query = { - distinct: true, - offset: start, - limit: count, - order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ], - include: [ - { - model: Video['sequelize'].models.VideoChannel, - required: true, - include: [ - { - model: Video['sequelize'].models.Account, - where: { - userId - }, - required: true - } - ] - }, - Video['sequelize'].models.Tag - ] + isOwned () { + return this.remote === false } - return Video.findAndCountAll(query).then(({ rows, count }) => { - return { - data: rows, - total: count - } - }) -} + getTorrentFilePath (videoFile: VideoFileModel) { + return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) + } -listForApi = function (start: number, count: number, sort: string) { - const query = { - distinct: true, - offset: start, - limit: count, - order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ], - include: [ - { - model: Video['sequelize'].models.VideoChannel, - required: true, - include: [ - { - model: Video['sequelize'].models.Account, - required: true, - include: [ - { - model: Video['sequelize'].models.Server, - required: false - } - ] - } - ] - }, - Video['sequelize'].models.Tag - ], - where: createBaseVideosWhere() + getVideoFilePath (videoFile: VideoFileModel) { + return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) } - return Video.findAndCountAll(query).then(({ rows, count }) => { - return { - data: rows, - total: count + async createTorrentAndSetInfoHash (videoFile: VideoFileModel) { + const options = { + // Keep the extname, it's used by the client to stream the file inside a web browser + name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`, + createdBy: 'PeerTube', + announceList: [ + [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ], + [ WEBSERVER.URL + '/tracker/announce' ] + ], + urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ] } - }) -} -loadByHostAndUUID = function (fromHost: string, uuid: string, t?: Sequelize.Transaction) { - const query: Sequelize.FindOptions = { - where: { - uuid - }, - include: [ - { - model: Video['sequelize'].models.VideoFile - }, - { - model: Video['sequelize'].models.VideoChannel, - include: [ - { - model: Video['sequelize'].models.Account, - include: [ - { - model: Video['sequelize'].models.Server, - required: true, - where: { - host: fromHost - } - } - ] - } - ] - } - ] - } + const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options) - if (t !== undefined) query.transaction = t + const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) + logger.info('Creating torrent %s.', filePath) - return Video.findOne(query) -} + await writeFile(filePath, torrent) -listOwnedAndPopulateAccountAndTags = function () { - const query = { - where: { - remote: false - }, - include: [ - Video['sequelize'].models.VideoFile, - { - model: Video['sequelize'].models.VideoChannel, - include: [ Video['sequelize'].models.Account ] - }, - Video['sequelize'].models.Tag - ] + const parsedTorrent = parseTorrent(torrent) + videoFile.infoHash = parsedTorrent.infoHash } - return Video.findAll(query) -} - -listOwnedByAccount = function (account: string) { - const query = { - where: { - remote: false - }, - include: [ - { - model: Video['sequelize'].models.VideoFile - }, - { - model: Video['sequelize'].models.VideoChannel, - include: [ - { - model: Video['sequelize'].models.Account, - where: { - name: account - } - } - ] - } - ] + getWatchStaticPath () { + return '/videos/watch/' + this.uuid } - return Video.findAll(query) -} + getEmbedStaticPath () { + return '/videos/embed/' + this.uuid + } -load = function (id: number) { - return Video.findById(id) -} + getMiniatureStaticPath () { + const thumbnail = this.getMiniature() + if (!thumbnail) return null -loadByUUID = function (uuid: string, t?: Sequelize.Transaction) { - const query: Sequelize.FindOptions = { - where: { - uuid - }, - include: [ Video['sequelize'].models.VideoFile ] + return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename) } - if (t !== undefined) query.transaction = t + getPreviewStaticPath () { + const preview = this.getPreview() + if (!preview) return null - return Video.findOne(query) -} - -loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) { - const query: Sequelize.FindOptions = { - where: { - url - }, - include: [ - Video['sequelize'].models.VideoFile, - { - model: Video['sequelize'].models.VideoChannel, - include: [ Video['sequelize'].models.Account ] - } - ] + // We use a local cache, so specify our cache endpoint instead of potential remote URL + return join(STATIC_PATHS.PREVIEWS, preview.filename) } - if (t !== undefined) query.transaction = t + toFormattedJSON (options?: VideoFormattingJSONOptions): Video { + return videoModelToFormattedJSON(this, options) + } - return Video.findOne(query) -} + toFormattedDetailsJSON (): VideoDetails { + return videoModelToFormattedDetailsJSON(this) + } -loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) { - const query: Sequelize.FindOptions = { - where: { - [Sequelize.Op.or]: [ - { uuid }, - { url } - ] - }, - include: [ Video['sequelize'].models.VideoFile ] + getFormattedVideoFilesJSON (): VideoFile[] { + return videoFilesModelToFormattedJSON(this, this.VideoFiles) } - if (t !== undefined) query.transaction = t + toActivityPubObject (): VideoTorrentObject { + return videoModelToActivityPubObject(this) + } - return Video.findOne(query) -} + getTruncatedDescription () { + if (!this.description) return null -loadLocalVideoByUUID = function (uuid: string, t?: Sequelize.Transaction) { - const query: Sequelize.FindOptions = { - where: { - uuid, - remote: false - }, - include: [ Video['sequelize'].models.VideoFile ] + const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max + return peertubeTruncate(this.description, maxLength) } - if (t !== undefined) query.transaction = t + getOriginalFileResolution () { + const originalFilePath = this.getVideoFilePath(this.getOriginalFile()) - return Video.findOne(query) -} + return getVideoFileResolution(originalFilePath) + } -loadAndPopulateAccount = function (id: number) { - const options = { - include: [ - Video['sequelize'].models.VideoFile, - { - model: Video['sequelize'].models.VideoChannel, - include: [ Video['sequelize'].models.Account ] - } - ] + getDescriptionAPIPath () { + return `/api/${API_VERSION}/videos/${this.uuid}/description` } - return Video.findById(id, options) -} + removeFile (videoFile: VideoFileModel, isRedundancy = false) { + const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR -loadAndPopulateAccountAndServerAndTags = function (id: number) { - const options = { - include: [ - { - model: Video['sequelize'].models.VideoChannel, - include: [ - { - model: Video['sequelize'].models.Account, - include: [ { model: Video['sequelize'].models.Server, required: false } ] - } - ] - }, - Video['sequelize'].models.Tag, - Video['sequelize'].models.VideoFile - ] + const filePath = join(baseDir, this.getVideoFilename(videoFile)) + return remove(filePath) + .catch(err => logger.warn('Cannot delete file %s.', filePath, { err })) } - return Video.findById(id, options) -} - -loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) { - const options = { - where: { - uuid - }, - include: [ - { - model: Video['sequelize'].models.VideoChannel, - include: [ - { - model: Video['sequelize'].models.Account, - include: [ { model: Video['sequelize'].models.Server, required: false } ] - } - ] - }, - Video['sequelize'].models.Tag, - Video['sequelize'].models.VideoFile - ] + removeTorrent (videoFile: VideoFileModel) { + const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) + return remove(torrentPath) + .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err })) } - return Video.findOne(options) -} + removeStreamingPlaylist (isRedundancy = false) { + const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY -searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) { - const serverInclude: Sequelize.IncludeOptions = { - model: Video['sequelize'].models.Server, - required: false + const filePath = join(baseDir, this.uuid) + return remove(filePath) + .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err })) } - const accountInclude: Sequelize.IncludeOptions = { - model: Video['sequelize'].models.Account, - include: [ serverInclude ] - } + isOutdated () { + if (this.isOwned()) return false - const videoChannelInclude: Sequelize.IncludeOptions = { - model: Video['sequelize'].models.VideoChannel, - include: [ accountInclude ], - required: true + return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL) } - const tagInclude: Sequelize.IncludeOptions = { - model: Video['sequelize'].models.Tag - } + setAsRefreshed () { + this.changed('updatedAt', true) - const query: Sequelize.FindOptions = { - distinct: true, - where: createBaseVideosWhere(), - offset: start, - limit: count, - order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ] + return this.save() } - if (field === 'tags') { - const escapedValue = Video['sequelize'].escape('%' + value + '%') - query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal( - `(SELECT "VideoTags"."videoId" - FROM "Tags" - INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" - WHERE name ILIKE ${escapedValue} - )` - ) - } else if (field === 'host') { - // FIXME: Include our server? (not stored in the database) - serverInclude.where = { - host: { - [Sequelize.Op.iLike]: '%' + value + '%' - } - } - serverInclude.required = true - } else if (field === 'account') { - accountInclude.where = { - name: { - [Sequelize.Op.iLike]: '%' + value + '%' - } - } - } else { - query.where[field] = { - [Sequelize.Op.iLike]: '%' + value + '%' + getBaseUrls () { + let baseUrlHttp + let baseUrlWs + + if (this.isOwned()) { + baseUrlHttp = WEBSERVER.URL + baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + } else { + baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host + baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host } + + return { baseUrlHttp, baseUrlWs } } - query.include = [ - videoChannelInclude, tagInclude - ] + generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) { + const xs = this.getTorrentUrl(videoFile, baseUrlHttp) + const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs) + let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ] - return Video.findAndCountAll(query).then(({ rows, count }) => { - return { - data: rows, - total: count - } - }) -} + const redundancies = videoFile.RedundancyVideos + if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl)) -// --------------------------------------------------------------------------- + const magnetHash = { + xs, + announce, + urlList, + infoHash: videoFile.infoHash, + name: this.name + } -function createBaseVideosWhere () { - return { - id: { - [Sequelize.Op.notIn]: Video['sequelize'].literal( - '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")' - ) - }, - privacy: VideoPrivacy.PUBLIC + return magnetUtil.encode(magnetHash) } -} - -function getBaseUrls (video: VideoInstance) { - let baseUrlHttp - let baseUrlWs - if (video.isOwned()) { - baseUrlHttp = CONFIG.WEBSERVER.URL - baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT - } else { - baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host - baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host + getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) { + return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ] } - return { baseUrlHttp, baseUrlWs } -} - -function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) { - return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName() -} + getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) { + return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile) + } -function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) { - return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile) -} + getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) { + return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile) + } -function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) { - return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile) -} + getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) { + return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) + } -function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) { - const xs = getTorrentUrl(video, videoFile, baseUrlHttp) - const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ] - const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ] + getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) { + return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile) + } - const magnetHash = { - xs, - announce, - urlList, - infoHash: videoFile.infoHash, - name: video.name + getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) { + return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile) } - return magnetUtil.encode(magnetHash) + getBandwidthBits (videoFile: VideoFileModel) { + return Math.ceil((videoFile.size * 8) / this.duration) + } }